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.

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