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.

980 lines
27 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
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
  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/hermeznetwork/hermez-node/log"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. "github.com/jmoiron/sqlx"
  14. //nolint:errcheck // driver for postgres DB
  15. _ "github.com/lib/pq"
  16. "github.com/russross/meddler"
  17. )
  18. const (
  19. // OrderAsc indicates ascending order when using pagination
  20. OrderAsc = "ASC"
  21. // OrderDesc indicates descending order when using pagination
  22. OrderDesc = "DESC"
  23. )
  24. // TODO(Edu): Document here how HistoryDB is kept consistent
  25. // HistoryDB persist the historic of the rollup
  26. type HistoryDB struct {
  27. db *sqlx.DB
  28. }
  29. // NewHistoryDB initialize the DB
  30. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  31. return &HistoryDB{db: db}
  32. }
  33. // AddBlock insert a block into the DB
  34. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  35. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  36. return meddler.Insert(d, "block", block)
  37. }
  38. // AddBlocks inserts blocks into the DB
  39. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  40. return hdb.addBlocks(hdb.db, blocks)
  41. }
  42. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  43. return db.BulkInsert(
  44. d,
  45. `INSERT INTO block (
  46. eth_block_num,
  47. timestamp,
  48. hash
  49. ) VALUES %s;`,
  50. blocks[:],
  51. )
  52. }
  53. // GetBlock retrieve a block from the DB, given a block number
  54. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  55. block := &common.Block{}
  56. err := meddler.QueryRow(
  57. hdb.db, block,
  58. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  59. )
  60. return block, err
  61. }
  62. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  63. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  64. var blocks []*common.Block
  65. err := meddler.QueryAll(
  66. hdb.db, &blocks,
  67. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  68. from, to,
  69. )
  70. return db.SlicePtrsToSlice(blocks).([]common.Block), err
  71. }
  72. // GetLastBlock retrieve the block with the highest block number from the DB
  73. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  74. block := &common.Block{}
  75. err := meddler.QueryRow(
  76. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  77. )
  78. return block, err
  79. }
  80. // AddBatch insert a Batch into the DB
  81. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  82. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  83. // Calculate total collected fees in USD
  84. // Get IDs of collected tokens for fees
  85. tokenIDs := []common.TokenID{}
  86. for id := range batch.CollectedFees {
  87. tokenIDs = append(tokenIDs, id)
  88. }
  89. // Get USD value of the tokens
  90. type tokenPrice struct {
  91. ID common.TokenID `meddler:"token_id"`
  92. USD *float64 `meddler:"usd"`
  93. Decimals int `meddler:"decimals"`
  94. }
  95. var tokenPrices []*tokenPrice
  96. if len(tokenIDs) > 0 {
  97. query, args, err := sqlx.In(
  98. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
  99. tokenIDs,
  100. )
  101. if err != nil {
  102. return err
  103. }
  104. query = hdb.db.Rebind(query)
  105. if err := meddler.QueryAll(
  106. hdb.db, &tokenPrices, query, args...,
  107. ); err != nil {
  108. return err
  109. }
  110. }
  111. // Calculate total collected
  112. var total float64
  113. for _, tokenPrice := range tokenPrices {
  114. if tokenPrice.USD == nil {
  115. continue
  116. }
  117. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  118. amount, _ := f.Float64()
  119. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  120. }
  121. batch.TotalFeesUSD = &total
  122. // Insert to DB
  123. return meddler.Insert(d, "batch", batch)
  124. }
  125. // AddBatches insert Bids into the DB
  126. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  127. return hdb.addBatches(hdb.db, batches)
  128. }
  129. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  130. for i := 0; i < len(batches); i++ {
  131. if err := hdb.addBatch(d, &batches[i]); err != nil {
  132. return err
  133. }
  134. }
  135. return nil
  136. }
  137. // GetBatch return the batch with the given batchNum
  138. func (hdb *HistoryDB) GetBatch(batchNum common.BatchNum) (HistoryBatch, error) {
  139. var batch *common.Batch
  140. return batch, meddler.QueryRow(
  141. hdb.db, &batch,
  142. "SELECT * FROM batch WHERE batch_num == $1;", batchNum,
  143. )
  144. }
  145. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  146. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  147. var batches []*common.Batch
  148. err := meddler.QueryAll(
  149. hdb.db, &batches,
  150. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
  151. from, to,
  152. )
  153. return db.SlicePtrsToSlice(batches).([]common.Batch), err
  154. }
  155. // GetLastBatchNum returns the BatchNum of the latest forged batch
  156. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  157. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  158. var batchNum common.BatchNum
  159. return batchNum, row.Scan(&batchNum)
  160. }
  161. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  162. // batches. If there's no batch in the DB (nil, nil) is returned.
  163. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  164. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  165. lastL1TxsNum := new(int64)
  166. return lastL1TxsNum, row.Scan(&lastL1TxsNum)
  167. }
  168. // Reorg deletes all the information that was added into the DB after the
  169. // lastValidBlock. If lastValidBlock is negative, all block information is
  170. // deleted.
  171. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  172. var err error
  173. if lastValidBlock < 0 {
  174. _, err = hdb.db.Exec("DELETE FROM block;")
  175. } else {
  176. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  177. }
  178. return err
  179. }
  180. // SyncPoD stores all the data that can be changed / added on a block in the PoD SC
  181. func (hdb *HistoryDB) SyncPoD(
  182. blockNum uint64,
  183. bids []common.Bid,
  184. coordinators []common.Coordinator,
  185. vars *common.AuctionVars,
  186. ) error {
  187. return nil
  188. }
  189. // AddBids insert Bids into the DB
  190. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  191. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  192. // TODO: check the coordinator info
  193. return db.BulkInsert(
  194. d,
  195. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  196. bids[:],
  197. )
  198. }
  199. // GetBids return the bids
  200. func (hdb *HistoryDB) GetBids() ([]common.Bid, error) {
  201. var bids []*common.Bid
  202. err := meddler.QueryAll(
  203. hdb.db, &bids,
  204. "SELECT * FROM bid;",
  205. )
  206. return db.SlicePtrsToSlice(bids).([]common.Bid), err
  207. }
  208. // AddCoordinators insert Coordinators into the DB
  209. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  210. return hdb.addCoordinators(hdb.db, coordinators)
  211. }
  212. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  213. return db.BulkInsert(
  214. d,
  215. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  216. coordinators[:],
  217. )
  218. }
  219. // AddExitTree insert Exit tree into the DB
  220. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  221. return hdb.addExitTree(hdb.db, exitTree)
  222. }
  223. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  224. return db.BulkInsert(
  225. d,
  226. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  227. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  228. exitTree[:],
  229. )
  230. }
  231. // AddToken insert a token into the DB
  232. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  233. return meddler.Insert(hdb.db, "token", token)
  234. }
  235. // AddTokens insert tokens into the DB
  236. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  237. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  238. return db.BulkInsert(
  239. d,
  240. `INSERT INTO token (
  241. token_id,
  242. eth_block_num,
  243. eth_addr,
  244. name,
  245. symbol,
  246. decimals
  247. ) VALUES %s;`,
  248. tokens[:],
  249. )
  250. }
  251. // UpdateTokenValue updates the USD value of a token
  252. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  253. _, err := hdb.db.Exec(
  254. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  255. value, tokenSymbol,
  256. )
  257. return err
  258. }
  259. // GetToken returns a token from the DB given a TokenID
  260. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenRead, error) {
  261. token := &TokenRead{}
  262. err := meddler.QueryRow(
  263. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  264. )
  265. return token, err
  266. }
  267. // GetAllTokens returns all tokens from the DB
  268. func (hdb *HistoryDB) GetAllTokens() ([]TokenRead, error) {
  269. var tokens []*TokenRead
  270. err := meddler.QueryAll(
  271. hdb.db, &tokens,
  272. "SELECT * FROM token ORDER BY token_id;",
  273. )
  274. return db.SlicePtrsToSlice(tokens).([]TokenRead), err
  275. }
  276. // GetTokens returns a list of tokens from the DB
  277. func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenRead, *db.Pagination, error) {
  278. var query string
  279. var args []interface{}
  280. 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 `
  281. // Apply filters
  282. nextIsAnd := false
  283. if len(ids) > 0 {
  284. queryStr += "WHERE token_id IN (?) "
  285. nextIsAnd = true
  286. args = append(args, ids)
  287. }
  288. if len(symbols) > 0 {
  289. if nextIsAnd {
  290. queryStr += "AND "
  291. } else {
  292. queryStr += "WHERE "
  293. }
  294. queryStr += "symbol IN (?) "
  295. args = append(args, symbols)
  296. nextIsAnd = true
  297. }
  298. if name != "" {
  299. if nextIsAnd {
  300. queryStr += "AND "
  301. } else {
  302. queryStr += "WHERE "
  303. }
  304. queryStr += "name ~ ? "
  305. args = append(args, name)
  306. nextIsAnd = true
  307. }
  308. if fromItem != nil {
  309. if nextIsAnd {
  310. queryStr += "AND "
  311. } else {
  312. queryStr += "WHERE "
  313. }
  314. if order == OrderAsc {
  315. queryStr += "item_id >= ? "
  316. } else {
  317. queryStr += "item_id <= ? "
  318. }
  319. args = append(args, fromItem)
  320. }
  321. // pagination
  322. queryStr += "ORDER BY item_id "
  323. if order == OrderAsc {
  324. queryStr += "ASC "
  325. } else {
  326. queryStr += "DESC "
  327. }
  328. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  329. query, argsQ, err := sqlx.In(queryStr, args...)
  330. if err != nil {
  331. return nil, nil, err
  332. }
  333. query = hdb.db.Rebind(query)
  334. tokens := []*TokenRead{}
  335. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  336. return nil, nil, err
  337. }
  338. if len(tokens) == 0 {
  339. return nil, nil, sql.ErrNoRows
  340. }
  341. return db.SlicePtrsToSlice(tokens).([]TokenRead), &db.Pagination{
  342. TotalItems: tokens[0].TotalItems,
  343. FirstItem: tokens[0].FirstItem,
  344. LastItem: tokens[0].LastItem,
  345. }, nil
  346. }
  347. // GetTokenSymbols returns all the token symbols from the DB
  348. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  349. var tokenSymbols []string
  350. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  351. if err != nil {
  352. return nil, err
  353. }
  354. sym := new(string)
  355. for rows.Next() {
  356. err = rows.Scan(sym)
  357. if err != nil {
  358. return nil, err
  359. }
  360. tokenSymbols = append(tokenSymbols, *sym)
  361. }
  362. return tokenSymbols, nil
  363. }
  364. // AddAccounts insert accounts into the DB
  365. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  366. return hdb.addAccounts(hdb.db, accounts)
  367. }
  368. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  369. return db.BulkInsert(
  370. d,
  371. `INSERT INTO account (
  372. idx,
  373. token_id,
  374. batch_num,
  375. bjj,
  376. eth_addr
  377. ) VALUES %s;`,
  378. accounts[:],
  379. )
  380. }
  381. // GetAccounts returns a list of accounts from the DB
  382. func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
  383. var accs []*common.Account
  384. err := meddler.QueryAll(
  385. hdb.db, &accs,
  386. "SELECT * FROM account ORDER BY idx;",
  387. )
  388. return db.SlicePtrsToSlice(accs).([]common.Account), err
  389. }
  390. // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  391. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  392. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  393. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
  394. // addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
  395. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  396. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  397. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  398. txs := []txWrite{}
  399. for i := 0; i < len(l1txs); i++ {
  400. af := new(big.Float).SetInt(l1txs[i].Amount)
  401. amountFloat, _ := af.Float64()
  402. laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
  403. loadAmountFloat, _ := laf.Float64()
  404. txs = append(txs, txWrite{
  405. // Generic
  406. IsL1: true,
  407. TxID: l1txs[i].TxID,
  408. Type: l1txs[i].Type,
  409. Position: l1txs[i].Position,
  410. FromIdx: &l1txs[i].FromIdx,
  411. ToIdx: l1txs[i].ToIdx,
  412. Amount: l1txs[i].Amount,
  413. AmountFloat: amountFloat,
  414. TokenID: l1txs[i].TokenID,
  415. BatchNum: l1txs[i].BatchNum,
  416. EthBlockNum: l1txs[i].EthBlockNum,
  417. // L1
  418. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  419. UserOrigin: &l1txs[i].UserOrigin,
  420. FromEthAddr: &l1txs[i].FromEthAddr,
  421. FromBJJ: l1txs[i].FromBJJ,
  422. LoadAmount: l1txs[i].LoadAmount,
  423. LoadAmountFloat: &loadAmountFloat,
  424. })
  425. }
  426. return hdb.addTxs(d, txs)
  427. }
  428. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  429. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
  430. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  431. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  432. txs := []txWrite{}
  433. for i := 0; i < len(l2txs); i++ {
  434. f := new(big.Float).SetInt(l2txs[i].Amount)
  435. amountFloat, _ := f.Float64()
  436. txs = append(txs, txWrite{
  437. // Generic
  438. IsL1: false,
  439. TxID: l2txs[i].TxID,
  440. Type: l2txs[i].Type,
  441. Position: l2txs[i].Position,
  442. FromIdx: &l2txs[i].FromIdx,
  443. ToIdx: l2txs[i].ToIdx,
  444. Amount: l2txs[i].Amount,
  445. AmountFloat: amountFloat,
  446. BatchNum: &l2txs[i].BatchNum,
  447. EthBlockNum: l2txs[i].EthBlockNum,
  448. // L2
  449. Fee: &l2txs[i].Fee,
  450. Nonce: &l2txs[i].Nonce,
  451. })
  452. }
  453. return hdb.addTxs(d, txs)
  454. }
  455. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  456. return db.BulkInsert(
  457. d,
  458. `INSERT INTO tx (
  459. is_l1,
  460. id,
  461. type,
  462. position,
  463. from_idx,
  464. to_idx,
  465. amount,
  466. amount_f,
  467. token_id,
  468. batch_num,
  469. eth_block_num,
  470. to_forge_l1_txs_num,
  471. user_origin,
  472. from_eth_addr,
  473. from_bjj,
  474. load_amount,
  475. load_amount_f,
  476. fee,
  477. nonce
  478. ) VALUES %s;`,
  479. txs[:],
  480. )
  481. }
  482. // // GetTxs returns a list of txs from the DB
  483. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  484. // var txs []*common.Tx
  485. // err := meddler.QueryAll(
  486. // hdb.db, &txs,
  487. // `SELECT * FROM tx
  488. // ORDER BY (batch_num, position) ASC`,
  489. // )
  490. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  491. // }
  492. // GetHistoryTx returns a tx from the DB given a TxID
  493. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*HistoryTx, error) {
  494. tx := &HistoryTx{}
  495. err := meddler.QueryRow(
  496. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  497. tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
  498. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  499. tx.from_eth_addr, tx.from_bjj, tx.load_amount,
  500. tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  501. token.token_id, token.eth_block_num AS token_block,
  502. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  503. token.usd_update, block.timestamp
  504. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  505. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  506. WHERE tx.id = $1;`, txID,
  507. )
  508. return tx, err
  509. }
  510. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  511. // and pagination info
  512. func (hdb *HistoryDB) GetHistoryTxs(
  513. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  514. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  515. fromItem, limit *uint, order string,
  516. ) ([]HistoryTx, *db.Pagination, error) {
  517. if ethAddr != nil && bjj != nil {
  518. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  519. }
  520. var query string
  521. var args []interface{}
  522. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  523. tx.from_idx, tx.to_idx, tx.amount, tx.token_id, tx.amount_usd,
  524. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  525. tx.from_eth_addr, tx.from_bjj, tx.load_amount,
  526. tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
  527. token.token_id, token.eth_block_num AS token_block,
  528. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  529. token.usd_update, block.timestamp, count(*) OVER() AS total_items,
  530. MIN(tx.item_id) OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item
  531. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  532. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  533. // Apply filters
  534. nextIsAnd := false
  535. // ethAddr filter
  536. if ethAddr != nil {
  537. queryStr = `WITH acc AS
  538. (select idx from account where eth_addr = ?) ` + queryStr
  539. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  540. nextIsAnd = true
  541. args = append(args, ethAddr)
  542. } else if bjj != nil { // bjj filter
  543. queryStr = `WITH acc AS
  544. (select idx from account where bjj = ?) ` + queryStr
  545. queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
  546. nextIsAnd = true
  547. args = append(args, bjj)
  548. }
  549. // tokenID filter
  550. if tokenID != nil {
  551. if nextIsAnd {
  552. queryStr += "AND "
  553. } else {
  554. queryStr += "WHERE "
  555. }
  556. queryStr += "tx.token_id = ? "
  557. args = append(args, tokenID)
  558. nextIsAnd = true
  559. }
  560. // idx filter
  561. if idx != nil {
  562. if nextIsAnd {
  563. queryStr += "AND "
  564. } else {
  565. queryStr += "WHERE "
  566. }
  567. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  568. args = append(args, idx, idx)
  569. nextIsAnd = true
  570. }
  571. // batchNum filter
  572. if batchNum != nil {
  573. if nextIsAnd {
  574. queryStr += "AND "
  575. } else {
  576. queryStr += "WHERE "
  577. }
  578. queryStr += "tx.batch_num = ? "
  579. args = append(args, batchNum)
  580. nextIsAnd = true
  581. }
  582. // txType filter
  583. if txType != nil {
  584. if nextIsAnd {
  585. queryStr += "AND "
  586. } else {
  587. queryStr += "WHERE "
  588. }
  589. queryStr += "tx.type = ? "
  590. args = append(args, txType)
  591. nextIsAnd = true
  592. }
  593. if fromItem != nil {
  594. if nextIsAnd {
  595. queryStr += "AND "
  596. } else {
  597. queryStr += "WHERE "
  598. }
  599. if order == OrderAsc {
  600. queryStr += "tx.item_id >= ? "
  601. } else {
  602. queryStr += "tx.item_id <= ? "
  603. }
  604. args = append(args, fromItem)
  605. nextIsAnd = true
  606. }
  607. if nextIsAnd {
  608. queryStr += "AND "
  609. } else {
  610. queryStr += "WHERE "
  611. }
  612. queryStr += "tx.batch_num IS NOT NULL "
  613. // pagination
  614. queryStr += "ORDER BY tx.item_id "
  615. if order == OrderAsc {
  616. queryStr += " ASC "
  617. } else {
  618. queryStr += " DESC "
  619. }
  620. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  621. query = hdb.db.Rebind(queryStr)
  622. log.Debug(query)
  623. txsPtrs := []*HistoryTx{}
  624. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  625. return nil, nil, err
  626. }
  627. txs := db.SlicePtrsToSlice(txsPtrs).([]HistoryTx)
  628. if len(txs) == 0 {
  629. return nil, nil, sql.ErrNoRows
  630. }
  631. return txs, &db.Pagination{
  632. TotalItems: txs[0].TotalItems,
  633. FirstItem: txs[0].FirstItem,
  634. LastItem: txs[0].LastItem,
  635. }, nil
  636. }
  637. // GetExit returns a exit from the DB
  638. func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
  639. exit := &HistoryExit{}
  640. err := meddler.QueryRow(
  641. hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  642. token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  643. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  644. INNER JOIN token ON account.token_id = token.token_id
  645. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  646. )
  647. return exit, err
  648. }
  649. // GetExits returns a list of exits from the DB and pagination info
  650. func (hdb *HistoryDB) GetExits(
  651. ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
  652. tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
  653. fromItem, limit *uint, order string,
  654. ) ([]HistoryExit, *db.Pagination, error) {
  655. if ethAddr != nil && bjj != nil {
  656. return nil, nil, errors.New("ethAddr and bjj are incompatible")
  657. }
  658. var query string
  659. var args []interface{}
  660. queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
  661. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  662. token.usd_update, COUNT(*) OVER() AS total_items, MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
  663. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  664. INNER JOIN token ON account.token_id = token.token_id `
  665. // Apply filters
  666. nextIsAnd := false
  667. // ethAddr filter
  668. if ethAddr != nil {
  669. queryStr += "WHERE account.eth_addr = ? "
  670. nextIsAnd = true
  671. args = append(args, ethAddr)
  672. } else if bjj != nil { // bjj filter
  673. queryStr += "WHERE account.bjj = ? "
  674. nextIsAnd = true
  675. args = append(args, bjj)
  676. }
  677. // tokenID filter
  678. if tokenID != nil {
  679. if nextIsAnd {
  680. queryStr += "AND "
  681. } else {
  682. queryStr += "WHERE "
  683. }
  684. queryStr += "account.token_id = ? "
  685. args = append(args, tokenID)
  686. nextIsAnd = true
  687. }
  688. // idx filter
  689. if idx != nil {
  690. if nextIsAnd {
  691. queryStr += "AND "
  692. } else {
  693. queryStr += "WHERE "
  694. }
  695. queryStr += "exit_tree.account_idx = ? "
  696. args = append(args, idx)
  697. nextIsAnd = true
  698. }
  699. // batchNum filter
  700. if batchNum != nil {
  701. if nextIsAnd {
  702. queryStr += "AND "
  703. } else {
  704. queryStr += "WHERE "
  705. }
  706. queryStr += "exit_tree.batch_num = ? "
  707. args = append(args, batchNum)
  708. nextIsAnd = true
  709. }
  710. if fromItem != nil {
  711. if nextIsAnd {
  712. queryStr += "AND "
  713. } else {
  714. queryStr += "WHERE "
  715. }
  716. if order == OrderAsc {
  717. queryStr += "exit_tree.item_id >= ? "
  718. } else {
  719. queryStr += "exit_tree.item_id <= ? "
  720. }
  721. args = append(args, fromItem)
  722. // nextIsAnd = true
  723. }
  724. // pagination
  725. queryStr += "ORDER BY exit_tree.item_id "
  726. if order == OrderAsc {
  727. queryStr += " ASC "
  728. } else {
  729. queryStr += " DESC "
  730. }
  731. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  732. query = hdb.db.Rebind(queryStr)
  733. // log.Debug(query)
  734. exits := []*HistoryExit{}
  735. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  736. return nil, nil, err
  737. }
  738. if len(exits) == 0 {
  739. return nil, nil, sql.ErrNoRows
  740. }
  741. return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
  742. TotalItems: exits[0].TotalItems,
  743. FirstItem: exits[0].FirstItem,
  744. LastItem: exits[0].LastItem,
  745. }, nil
  746. }
  747. // // GetTx returns a tx from the DB
  748. // func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
  749. // tx := new(common.Tx)
  750. // return tx, meddler.QueryRow(
  751. // hdb.db, tx,
  752. // "SELECT * FROM tx WHERE id = $1;",
  753. // txID,
  754. // )
  755. // }
  756. // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  757. func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  758. var txs []*common.L1Tx
  759. err := meddler.QueryAll(
  760. hdb.db, &txs,
  761. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  762. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
  763. tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
  764. FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
  765. toForgeL1TxsNum,
  766. )
  767. return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
  768. }
  769. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  770. // GetLastTxsPosition for a given to_forge_l1_txs_num
  771. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  772. row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
  773. var lastL1TxsPosition int
  774. return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
  775. }
  776. // AddBlockSCData stores all the information of a block retrieved by the
  777. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  778. // the pagination system of the API/DB depends on this. Within blocks, all
  779. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  780. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  781. txn, err := hdb.db.Begin()
  782. if err != nil {
  783. return err
  784. }
  785. defer func() {
  786. if err != nil {
  787. errRollback := txn.Rollback()
  788. if errRollback != nil {
  789. log.Errorw("Rollback", "err", errRollback)
  790. }
  791. }
  792. }()
  793. // Add block
  794. err = hdb.addBlock(txn, &blockData.Block)
  795. if err != nil {
  796. return err
  797. }
  798. // Add Coordinators
  799. if len(blockData.Coordinators) > 0 {
  800. err = hdb.addCoordinators(txn, blockData.Coordinators)
  801. if err != nil {
  802. return err
  803. }
  804. }
  805. // Add Bids
  806. if len(blockData.Bids) > 0 {
  807. err = hdb.addBids(txn, blockData.Bids)
  808. if err != nil {
  809. return err
  810. }
  811. }
  812. // Add Tokens
  813. if len(blockData.AddedTokens) > 0 {
  814. err = hdb.addTokens(txn, blockData.AddedTokens)
  815. if err != nil {
  816. return err
  817. }
  818. }
  819. // Add l1 Txs
  820. if len(blockData.L1UserTxs) > 0 {
  821. err = hdb.addL1Txs(txn, blockData.L1UserTxs)
  822. if err != nil {
  823. return err
  824. }
  825. }
  826. // Add Batches
  827. for i := range blockData.Batches {
  828. batch := &blockData.Batches[i]
  829. // Add Batch: this will trigger an update on the DB
  830. // that will set the batch num of forged L1 txs in this batch
  831. err = hdb.addBatch(txn, &batch.Batch)
  832. if err != nil {
  833. return err
  834. }
  835. // Add unforged l1 Txs
  836. if batch.L1Batch {
  837. if len(batch.L1CoordinatorTxs) > 0 {
  838. err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
  839. if err != nil {
  840. return err
  841. }
  842. }
  843. }
  844. // Add l2 Txs
  845. if len(batch.L2Txs) > 0 {
  846. err = hdb.addL2Txs(txn, batch.L2Txs)
  847. if err != nil {
  848. return err
  849. }
  850. }
  851. // Add accounts
  852. if len(batch.CreatedAccounts) > 0 {
  853. err = hdb.addAccounts(txn, batch.CreatedAccounts)
  854. if err != nil {
  855. return err
  856. }
  857. }
  858. // Add exit tree
  859. if len(batch.ExitTree) > 0 {
  860. err = hdb.addExitTree(txn, batch.ExitTree)
  861. if err != nil {
  862. return err
  863. }
  864. }
  865. // TODO: INSERT CONTRACTS VARS
  866. }
  867. return txn.Commit()
  868. }
  869. // GetCoordinator returns a coordinator by its bidderAddr
  870. func (hdb *HistoryDB) GetCoordinator(bidderAddr ethCommon.Address) (*HistoryCoordinator, error) {
  871. coordinator := &HistoryCoordinator{}
  872. err := meddler.QueryRow(
  873. hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
  874. )
  875. return coordinator, err
  876. }
  877. // GetCoordinators returns a list of coordinators from the DB and pagination info
  878. func (hdb *HistoryDB) GetCoordinators(fromItem, limit *uint, order string) ([]HistoryCoordinator, *db.Pagination, error) {
  879. var query string
  880. var args []interface{}
  881. queryStr := `SELECT coordinator.*,
  882. COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
  883. FROM coordinator `
  884. // Apply filters
  885. if fromItem != nil {
  886. queryStr += "WHERE "
  887. if order == OrderAsc {
  888. queryStr += "coordinator.item_id >= ? "
  889. } else {
  890. queryStr += "coordinator.item_id <= ? "
  891. }
  892. args = append(args, fromItem)
  893. }
  894. // pagination
  895. queryStr += "ORDER BY coordinator.item_id "
  896. if order == OrderAsc {
  897. queryStr += " ASC "
  898. } else {
  899. queryStr += " DESC "
  900. }
  901. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  902. query = hdb.db.Rebind(queryStr)
  903. coordinators := []*HistoryCoordinator{}
  904. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  905. return nil, nil, err
  906. }
  907. if len(coordinators) == 0 {
  908. return nil, nil, sql.ErrNoRows
  909. }
  910. return db.SlicePtrsToSlice(coordinators).([]HistoryCoordinator), &db.Pagination{
  911. TotalItems: coordinators[0].TotalItems,
  912. FirstItem: coordinators[0].FirstItem,
  913. LastItem: coordinators[0].LastItem,
  914. }, nil
  915. }