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.

1946 lines
61 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
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
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
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
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
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
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 coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package historydb
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "math/big"
  7. "strings"
  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/tracerr"
  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. // DB returns a pointer to the L2DB.db. This method should be used only for
  34. // internal testing purposes.
  35. func (hdb *HistoryDB) DB() *sqlx.DB {
  36. return hdb.db
  37. }
  38. // AddBlock insert a block into the DB
  39. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  40. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  41. return tracerr.Wrap(meddler.Insert(d, "block", block))
  42. }
  43. // AddBlocks inserts blocks into the DB
  44. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  45. return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
  46. }
  47. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  48. return tracerr.Wrap(db.BulkInsert(
  49. d,
  50. `INSERT INTO block (
  51. eth_block_num,
  52. timestamp,
  53. hash
  54. ) VALUES %s;`,
  55. blocks[:],
  56. ))
  57. }
  58. // GetBlock retrieve a block from the DB, given a block number
  59. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  60. block := &common.Block{}
  61. err := meddler.QueryRow(
  62. hdb.db, block,
  63. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  64. )
  65. return block, tracerr.Wrap(err)
  66. }
  67. // GetAllBlocks retrieve all blocks from the DB
  68. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  69. var blocks []*common.Block
  70. err := meddler.QueryAll(
  71. hdb.db, &blocks,
  72. "SELECT * FROM block ORDER BY eth_block_num;",
  73. )
  74. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  75. }
  76. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  77. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  78. var blocks []*common.Block
  79. err := meddler.QueryAll(
  80. hdb.db, &blocks,
  81. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
  82. from, to,
  83. )
  84. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  85. }
  86. // GetLastBlock retrieve the block with the highest block number from the DB
  87. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  88. block := &common.Block{}
  89. err := meddler.QueryRow(
  90. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  91. )
  92. return block, tracerr.Wrap(err)
  93. }
  94. // AddBatch insert a Batch into the DB
  95. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  96. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  97. // Calculate total collected fees in USD
  98. // Get IDs of collected tokens for fees
  99. tokenIDs := []common.TokenID{}
  100. for id := range batch.CollectedFees {
  101. tokenIDs = append(tokenIDs, id)
  102. }
  103. // Get USD value of the tokens
  104. type tokenPrice struct {
  105. ID common.TokenID `meddler:"token_id"`
  106. USD *float64 `meddler:"usd"`
  107. Decimals int `meddler:"decimals"`
  108. }
  109. var tokenPrices []*tokenPrice
  110. if len(tokenIDs) > 0 {
  111. query, args, err := sqlx.In(
  112. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
  113. tokenIDs,
  114. )
  115. if err != nil {
  116. return tracerr.Wrap(err)
  117. }
  118. query = hdb.db.Rebind(query)
  119. if err := meddler.QueryAll(
  120. hdb.db, &tokenPrices, query, args...,
  121. ); err != nil {
  122. return tracerr.Wrap(err)
  123. }
  124. }
  125. // Calculate total collected
  126. var total float64
  127. for _, tokenPrice := range tokenPrices {
  128. if tokenPrice.USD == nil {
  129. continue
  130. }
  131. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  132. amount, _ := f.Float64()
  133. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  134. }
  135. batch.TotalFeesUSD = &total
  136. // Insert to DB
  137. return tracerr.Wrap(meddler.Insert(d, "batch", batch))
  138. }
  139. // AddBatches insert Bids into the DB
  140. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  141. return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
  142. }
  143. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  144. for i := 0; i < len(batches); i++ {
  145. if err := hdb.addBatch(d, &batches[i]); err != nil {
  146. return tracerr.Wrap(err)
  147. }
  148. }
  149. return nil
  150. }
  151. // GetBatchAPI return the batch with the given batchNum
  152. func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
  153. batch := &BatchAPI{}
  154. return batch, tracerr.Wrap(meddler.QueryRow(
  155. hdb.db, batch,
  156. `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
  157. batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
  158. batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
  159. block.timestamp, block.hash,
  160. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs
  161. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
  162. WHERE batch_num = $1;`, batchNum,
  163. ))
  164. }
  165. // GetBatchesAPI return the batches applying the given filters
  166. func (hdb *HistoryDB) GetBatchesAPI(
  167. minBatchNum, maxBatchNum, slotNum *uint,
  168. forgerAddr *ethCommon.Address,
  169. fromItem, limit *uint, order string,
  170. ) ([]BatchAPI, uint64, error) {
  171. var query string
  172. var args []interface{}
  173. queryStr := `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
  174. batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
  175. batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
  176. block.timestamp, block.hash,
  177. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs,
  178. count(*) OVER() AS total_items
  179. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
  180. // Apply filters
  181. nextIsAnd := false
  182. // minBatchNum filter
  183. if minBatchNum != nil {
  184. if nextIsAnd {
  185. queryStr += "AND "
  186. } else {
  187. queryStr += "WHERE "
  188. }
  189. queryStr += "batch.batch_num > ? "
  190. args = append(args, minBatchNum)
  191. nextIsAnd = true
  192. }
  193. // maxBatchNum filter
  194. if maxBatchNum != nil {
  195. if nextIsAnd {
  196. queryStr += "AND "
  197. } else {
  198. queryStr += "WHERE "
  199. }
  200. queryStr += "batch.batch_num < ? "
  201. args = append(args, maxBatchNum)
  202. nextIsAnd = true
  203. }
  204. // slotNum filter
  205. if slotNum != nil {
  206. if nextIsAnd {
  207. queryStr += "AND "
  208. } else {
  209. queryStr += "WHERE "
  210. }
  211. queryStr += "batch.slot_num = ? "
  212. args = append(args, slotNum)
  213. nextIsAnd = true
  214. }
  215. // forgerAddr filter
  216. if forgerAddr != nil {
  217. if nextIsAnd {
  218. queryStr += "AND "
  219. } else {
  220. queryStr += "WHERE "
  221. }
  222. queryStr += "batch.forger_addr = ? "
  223. args = append(args, forgerAddr)
  224. nextIsAnd = true
  225. }
  226. // pagination
  227. if fromItem != nil {
  228. if nextIsAnd {
  229. queryStr += "AND "
  230. } else {
  231. queryStr += "WHERE "
  232. }
  233. if order == OrderAsc {
  234. queryStr += "batch.item_id >= ? "
  235. } else {
  236. queryStr += "batch.item_id <= ? "
  237. }
  238. args = append(args, fromItem)
  239. }
  240. queryStr += "ORDER BY batch.item_id "
  241. if order == OrderAsc {
  242. queryStr += " ASC "
  243. } else {
  244. queryStr += " DESC "
  245. }
  246. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  247. query = hdb.db.Rebind(queryStr)
  248. // log.Debug(query)
  249. batchPtrs := []*BatchAPI{}
  250. if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
  251. return nil, 0, tracerr.Wrap(err)
  252. }
  253. batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
  254. if len(batches) == 0 {
  255. return batches, 0, nil
  256. }
  257. return batches, batches[0].TotalItems - uint64(len(batches)), nil
  258. }
  259. // GetAllBatches retrieve all batches from the DB
  260. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  261. var batches []*common.Batch
  262. err := meddler.QueryAll(
  263. hdb.db, &batches,
  264. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  265. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  266. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
  267. ORDER BY item_id;`,
  268. )
  269. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  270. }
  271. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  272. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  273. var batches []*common.Batch
  274. err := meddler.QueryAll(
  275. hdb.db, &batches,
  276. `SELECT batch_num, eth_block_num, forger_addr, fees_collected, fee_idxs_coordinator,
  277. state_root, num_accounts, last_idx, exit_root, forge_l1_txs_num, slot_num, total_fees_usd
  278. FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;`,
  279. from, to,
  280. )
  281. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  282. }
  283. // GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
  284. // batch within a slot
  285. func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
  286. row := hdb.db.QueryRow(
  287. `SELECT eth_block_num FROM batch
  288. WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
  289. )
  290. var blockNum int64
  291. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  292. }
  293. // GetLastBatchNum returns the BatchNum of the latest forged batch
  294. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  295. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  296. var batchNum common.BatchNum
  297. return batchNum, tracerr.Wrap(row.Scan(&batchNum))
  298. }
  299. // GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
  300. func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
  301. row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
  302. WHERE forge_l1_txs_num IS NOT NULL
  303. ORDER BY batch_num DESC LIMIT 1;`)
  304. var blockNum int64
  305. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  306. }
  307. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  308. // batches. If there's no batch in the DB (nil, nil) is returned.
  309. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  310. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  311. lastL1TxsNum := new(int64)
  312. return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
  313. }
  314. // Reorg deletes all the information that was added into the DB after the
  315. // lastValidBlock. If lastValidBlock is negative, all block information is
  316. // deleted.
  317. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  318. var err error
  319. if lastValidBlock < 0 {
  320. _, err = hdb.db.Exec("DELETE FROM block;")
  321. } else {
  322. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  323. }
  324. return tracerr.Wrap(err)
  325. }
  326. // AddBids insert Bids into the DB
  327. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  328. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  329. if len(bids) == 0 {
  330. return nil
  331. }
  332. // TODO: check the coordinator info
  333. return tracerr.Wrap(db.BulkInsert(
  334. d,
  335. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  336. bids[:],
  337. ))
  338. }
  339. // GetAllBids retrieve all bids from the DB
  340. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  341. var bids []*common.Bid
  342. err := meddler.QueryAll(
  343. hdb.db, &bids,
  344. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
  345. ORDER BY item_id;`,
  346. )
  347. return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
  348. }
  349. // GetBestBidAPI returns the best bid in specific slot by slotNum
  350. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  351. bid := &BidAPI{}
  352. err := meddler.QueryRow(
  353. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  354. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  355. INNER JOIN (
  356. SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
  357. GROUP BY bidder_addr
  358. ) c ON bid.bidder_addr = c.bidder_addr
  359. INNER JOIN coordinator ON c.item_id = coordinator.item_id
  360. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  361. )
  362. return *bid, tracerr.Wrap(err)
  363. }
  364. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  365. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  366. bidCoord := &common.BidCoordinator{}
  367. err := meddler.QueryRow(
  368. hdb.db, bidCoord,
  369. `SELECT (
  370. SELECT default_slot_set_bid
  371. FROM auction_vars
  372. WHERE default_slot_set_bid_slot_num <= $1
  373. ORDER BY eth_block_num DESC LIMIT 1
  374. ),
  375. bid.slot_num, bid.bid_value, bid.bidder_addr,
  376. coordinator.forger_addr, coordinator.url
  377. FROM bid
  378. INNER JOIN (
  379. SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
  380. GROUP BY bidder_addr
  381. ) c ON bid.bidder_addr = c.bidder_addr
  382. INNER JOIN coordinator ON c.item_id = coordinator.item_id
  383. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  384. slotNum)
  385. return bidCoord, tracerr.Wrap(err)
  386. }
  387. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  388. func (hdb *HistoryDB) GetBestBidsAPI(
  389. minSlotNum, maxSlotNum *int64,
  390. bidderAddr *ethCommon.Address,
  391. limit *uint, order string,
  392. ) ([]BidAPI, uint64, error) {
  393. var query string
  394. var args []interface{}
  395. // JOIN the best bid of each slot with the latest update of each coordinator
  396. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  397. COUNT(*) OVER() AS total_items FROM (
  398. SELECT slot_num, MAX(item_id) as maxitem
  399. FROM bid GROUP BY slot_num
  400. )
  401. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  402. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  403. INNER JOIN (
  404. SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
  405. GROUP BY bidder_addr
  406. ) c ON b.bidder_addr = c.bidder_addr
  407. INNER JOIN coordinator ON c.item_id = coordinator.item_id
  408. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  409. args = append(args, minSlotNum)
  410. args = append(args, maxSlotNum)
  411. // Apply filters
  412. if bidderAddr != nil {
  413. queryStr += " AND b.bidder_addr = ? "
  414. args = append(args, bidderAddr)
  415. }
  416. queryStr += " ORDER BY b.slot_num "
  417. if order == OrderAsc {
  418. queryStr += "ASC "
  419. } else {
  420. queryStr += "DESC "
  421. }
  422. if limit != nil {
  423. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  424. }
  425. query = hdb.db.Rebind(queryStr)
  426. bidPtrs := []*BidAPI{}
  427. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  428. return nil, 0, tracerr.Wrap(err)
  429. }
  430. // log.Debug(query)
  431. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  432. if len(bids) == 0 {
  433. return bids, 0, nil
  434. }
  435. return bids, bids[0].TotalItems - uint64(len(bids)), nil
  436. }
  437. // GetBidsAPI return the bids applying the given filters
  438. func (hdb *HistoryDB) GetBidsAPI(
  439. slotNum *int64, bidderAddr *ethCommon.Address,
  440. fromItem, limit *uint, order string,
  441. ) ([]BidAPI, uint64, error) {
  442. var query string
  443. var args []interface{}
  444. // JOIN each bid with the latest update of each coordinator
  445. queryStr := `SELECT bid.*, block.timestamp, coord.forger_addr, coord.url,
  446. COUNT(*) OVER() AS total_items
  447. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  448. INNER JOIN (
  449. SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
  450. GROUP BY bidder_addr
  451. ) c ON bid.bidder_addr = c.bidder_addr
  452. INNER JOIN coordinator coord ON c.item_id = coord.item_id `
  453. // Apply filters
  454. nextIsAnd := false
  455. // slotNum filter
  456. if slotNum != nil {
  457. if nextIsAnd {
  458. queryStr += "AND "
  459. } else {
  460. queryStr += "WHERE "
  461. }
  462. queryStr += "bid.slot_num = ? "
  463. args = append(args, slotNum)
  464. nextIsAnd = true
  465. }
  466. // bidder filter
  467. if bidderAddr != nil {
  468. if nextIsAnd {
  469. queryStr += "AND "
  470. } else {
  471. queryStr += "WHERE "
  472. }
  473. queryStr += "bid.bidder_addr = ? "
  474. args = append(args, bidderAddr)
  475. nextIsAnd = true
  476. }
  477. if fromItem != nil {
  478. if nextIsAnd {
  479. queryStr += "AND "
  480. } else {
  481. queryStr += "WHERE "
  482. }
  483. if order == OrderAsc {
  484. queryStr += "bid.item_id >= ? "
  485. } else {
  486. queryStr += "bid.item_id <= ? "
  487. }
  488. args = append(args, fromItem)
  489. }
  490. // pagination
  491. queryStr += "ORDER BY bid.item_id "
  492. if order == OrderAsc {
  493. queryStr += "ASC "
  494. } else {
  495. queryStr += "DESC "
  496. }
  497. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  498. query, argsQ, err := sqlx.In(queryStr, args...)
  499. if err != nil {
  500. return nil, 0, tracerr.Wrap(err)
  501. }
  502. query = hdb.db.Rebind(query)
  503. bids := []*BidAPI{}
  504. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  505. return nil, 0, tracerr.Wrap(err)
  506. }
  507. if len(bids) == 0 {
  508. return []BidAPI{}, 0, nil
  509. }
  510. return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
  511. }
  512. // AddCoordinators insert Coordinators into the DB
  513. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  514. return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
  515. }
  516. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  517. if len(coordinators) == 0 {
  518. return nil
  519. }
  520. return tracerr.Wrap(db.BulkInsert(
  521. d,
  522. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  523. coordinators[:],
  524. ))
  525. }
  526. // AddExitTree insert Exit tree into the DB
  527. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  528. return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
  529. }
  530. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  531. if len(exitTree) == 0 {
  532. return nil
  533. }
  534. return tracerr.Wrap(db.BulkInsert(
  535. d,
  536. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  537. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  538. exitTree[:],
  539. ))
  540. }
  541. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  542. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  543. if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
  544. return nil
  545. }
  546. type withdrawal struct {
  547. BatchNum int64 `db:"batch_num"`
  548. AccountIdx int64 `db:"account_idx"`
  549. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  550. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  551. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  552. Owner *ethCommon.Address `db:"owner"`
  553. Token *ethCommon.Address `db:"token"`
  554. }
  555. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  556. for i := range rollupWithdrawals {
  557. info := &rollupWithdrawals[i]
  558. withdrawals[i] = withdrawal{
  559. BatchNum: int64(info.NumExitRoot),
  560. AccountIdx: int64(info.Idx),
  561. }
  562. if info.InstantWithdraw {
  563. withdrawals[i].InstantWithdrawn = &blockNum
  564. } else {
  565. withdrawals[i].DelayedWithdrawRequest = &blockNum
  566. withdrawals[i].Owner = &info.Owner
  567. withdrawals[i].Token = &info.Token
  568. }
  569. }
  570. for i := range wDelayerWithdrawals {
  571. info := &wDelayerWithdrawals[i]
  572. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  573. DelayedWithdrawn: &blockNum,
  574. Owner: &info.Owner,
  575. Token: &info.Token,
  576. }
  577. }
  578. // In VALUES we set an initial row of NULLs to set the types of each
  579. // variable passed as argument
  580. const query string = `
  581. UPDATE exit_tree e SET
  582. instant_withdrawn = d.instant_withdrawn,
  583. delayed_withdraw_request = CASE
  584. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  585. ELSE d.delayed_withdraw_request
  586. END,
  587. delayed_withdrawn = d.delayed_withdrawn,
  588. owner = d.owner,
  589. token = d.token
  590. FROM (VALUES
  591. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  592. (:batch_num,
  593. :account_idx,
  594. :instant_withdrawn,
  595. :delayed_withdraw_request,
  596. :delayed_withdrawn,
  597. :owner,
  598. :token)
  599. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  600. WHERE
  601. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  602. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
  603. `
  604. if len(withdrawals) > 0 {
  605. if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
  606. return tracerr.Wrap(err)
  607. }
  608. }
  609. return nil
  610. }
  611. // AddToken insert a token into the DB
  612. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  613. return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
  614. }
  615. // AddTokens insert tokens into the DB
  616. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  617. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  618. if len(tokens) == 0 {
  619. return nil
  620. }
  621. // Sanitize name and symbol
  622. for i, token := range tokens {
  623. token.Name = strings.ToValidUTF8(token.Name, " ")
  624. token.Symbol = strings.ToValidUTF8(token.Symbol, " ")
  625. tokens[i] = token
  626. }
  627. return tracerr.Wrap(db.BulkInsert(
  628. d,
  629. `INSERT INTO token (
  630. token_id,
  631. eth_block_num,
  632. eth_addr,
  633. name,
  634. symbol,
  635. decimals
  636. ) VALUES %s;`,
  637. tokens[:],
  638. ))
  639. }
  640. // UpdateTokenValue updates the USD value of a token
  641. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  642. // Sanitize symbol
  643. tokenSymbol = strings.ToValidUTF8(tokenSymbol, " ")
  644. _, err := hdb.db.Exec(
  645. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  646. value, tokenSymbol,
  647. )
  648. return tracerr.Wrap(err)
  649. }
  650. // GetToken returns a token from the DB given a TokenID
  651. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  652. token := &TokenWithUSD{}
  653. err := meddler.QueryRow(
  654. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  655. )
  656. return token, tracerr.Wrap(err)
  657. }
  658. // GetAllTokens returns all tokens from the DB
  659. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  660. var tokens []*TokenWithUSD
  661. err := meddler.QueryAll(
  662. hdb.db, &tokens,
  663. "SELECT * FROM token ORDER BY token_id;",
  664. )
  665. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
  666. }
  667. // GetTokens returns a list of tokens from the DB
  668. func (hdb *HistoryDB) GetTokens(
  669. ids []common.TokenID, symbols []string, name string, fromItem,
  670. limit *uint, order string,
  671. ) ([]TokenWithUSD, uint64, error) {
  672. var query string
  673. var args []interface{}
  674. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  675. // Apply filters
  676. nextIsAnd := false
  677. if len(ids) > 0 {
  678. queryStr += "WHERE token_id IN (?) "
  679. nextIsAnd = true
  680. args = append(args, ids)
  681. }
  682. if len(symbols) > 0 {
  683. if nextIsAnd {
  684. queryStr += "AND "
  685. } else {
  686. queryStr += "WHERE "
  687. }
  688. queryStr += "symbol IN (?) "
  689. args = append(args, symbols)
  690. nextIsAnd = true
  691. }
  692. if name != "" {
  693. if nextIsAnd {
  694. queryStr += "AND "
  695. } else {
  696. queryStr += "WHERE "
  697. }
  698. queryStr += "name ~ ? "
  699. args = append(args, name)
  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 += "item_id >= ? "
  710. } else {
  711. queryStr += "item_id <= ? "
  712. }
  713. args = append(args, fromItem)
  714. }
  715. // pagination
  716. queryStr += "ORDER BY item_id "
  717. if order == OrderAsc {
  718. queryStr += "ASC "
  719. } else {
  720. queryStr += "DESC "
  721. }
  722. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  723. query, argsQ, err := sqlx.In(queryStr, args...)
  724. if err != nil {
  725. return nil, 0, tracerr.Wrap(err)
  726. }
  727. query = hdb.db.Rebind(query)
  728. tokens := []*TokenWithUSD{}
  729. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  730. return nil, 0, tracerr.Wrap(err)
  731. }
  732. if len(tokens) == 0 {
  733. return []TokenWithUSD{}, 0, nil
  734. }
  735. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  736. }
  737. // GetTokenSymbols returns all the token symbols from the DB
  738. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  739. var tokenSymbols []string
  740. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  741. if err != nil {
  742. return nil, tracerr.Wrap(err)
  743. }
  744. defer db.RowsClose(rows)
  745. sym := new(string)
  746. for rows.Next() {
  747. err = rows.Scan(sym)
  748. if err != nil {
  749. return nil, tracerr.Wrap(err)
  750. }
  751. tokenSymbols = append(tokenSymbols, *sym)
  752. }
  753. return tokenSymbols, nil
  754. }
  755. // AddAccounts insert accounts into the DB
  756. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  757. return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
  758. }
  759. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  760. if len(accounts) == 0 {
  761. return nil
  762. }
  763. return tracerr.Wrap(db.BulkInsert(
  764. d,
  765. `INSERT INTO account (
  766. idx,
  767. token_id,
  768. batch_num,
  769. bjj,
  770. eth_addr
  771. ) VALUES %s;`,
  772. accounts[:],
  773. ))
  774. }
  775. // GetAllAccounts returns a list of accounts from the DB
  776. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  777. var accs []*common.Account
  778. err := meddler.QueryAll(
  779. hdb.db, &accs,
  780. "SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
  781. )
  782. return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
  783. }
  784. // AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  785. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  786. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  787. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  788. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
  789. return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
  790. }
  791. // addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  792. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  793. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  794. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  795. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  796. if len(l1txs) == 0 {
  797. return nil
  798. }
  799. txs := []txWrite{}
  800. for i := 0; i < len(l1txs); i++ {
  801. af := new(big.Float).SetInt(l1txs[i].Amount)
  802. amountFloat, _ := af.Float64()
  803. laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
  804. depositAmountFloat, _ := laf.Float64()
  805. txs = append(txs, txWrite{
  806. // Generic
  807. IsL1: true,
  808. TxID: l1txs[i].TxID,
  809. Type: l1txs[i].Type,
  810. Position: l1txs[i].Position,
  811. FromIdx: &l1txs[i].FromIdx,
  812. ToIdx: l1txs[i].ToIdx,
  813. Amount: l1txs[i].Amount,
  814. AmountFloat: amountFloat,
  815. TokenID: l1txs[i].TokenID,
  816. BatchNum: l1txs[i].BatchNum,
  817. EthBlockNum: l1txs[i].EthBlockNum,
  818. // L1
  819. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  820. UserOrigin: &l1txs[i].UserOrigin,
  821. FromEthAddr: &l1txs[i].FromEthAddr,
  822. FromBJJ: &l1txs[i].FromBJJ,
  823. DepositAmount: l1txs[i].DepositAmount,
  824. DepositAmountFloat: &depositAmountFloat,
  825. })
  826. }
  827. return tracerr.Wrap(hdb.addTxs(d, txs))
  828. }
  829. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  830. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
  831. return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
  832. }
  833. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  834. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  835. txs := []txWrite{}
  836. for i := 0; i < len(l2txs); i++ {
  837. f := new(big.Float).SetInt(l2txs[i].Amount)
  838. amountFloat, _ := f.Float64()
  839. txs = append(txs, txWrite{
  840. // Generic
  841. IsL1: false,
  842. TxID: l2txs[i].TxID,
  843. Type: l2txs[i].Type,
  844. Position: l2txs[i].Position,
  845. FromIdx: &l2txs[i].FromIdx,
  846. ToIdx: l2txs[i].ToIdx,
  847. Amount: l2txs[i].Amount,
  848. AmountFloat: amountFloat,
  849. BatchNum: &l2txs[i].BatchNum,
  850. EthBlockNum: l2txs[i].EthBlockNum,
  851. // L2
  852. Fee: &l2txs[i].Fee,
  853. Nonce: &l2txs[i].Nonce,
  854. })
  855. }
  856. return tracerr.Wrap(hdb.addTxs(d, txs))
  857. }
  858. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  859. if len(txs) == 0 {
  860. return nil
  861. }
  862. return tracerr.Wrap(db.BulkInsert(
  863. d,
  864. `INSERT INTO tx (
  865. is_l1,
  866. id,
  867. type,
  868. position,
  869. from_idx,
  870. to_idx,
  871. amount,
  872. amount_f,
  873. token_id,
  874. batch_num,
  875. eth_block_num,
  876. to_forge_l1_txs_num,
  877. user_origin,
  878. from_eth_addr,
  879. from_bjj,
  880. deposit_amount,
  881. deposit_amount_f,
  882. fee,
  883. nonce
  884. ) VALUES %s;`,
  885. txs[:],
  886. ))
  887. }
  888. // // GetTxs returns a list of txs from the DB
  889. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  890. // var txs []*common.Tx
  891. // err := meddler.QueryAll(
  892. // hdb.db, &txs,
  893. // `SELECT * FROM tx
  894. // ORDER BY (batch_num, position) ASC`,
  895. // )
  896. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  897. // }
  898. // GetHistoryTx returns a tx from the DB given a TxID
  899. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  900. // Warning: amount_success and deposit_amount_success have true as default for
  901. // performance reasons. The expected default value is false (when txs are unforged)
  902. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  903. tx := &TxAPI{}
  904. err := meddler.QueryRow(
  905. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  906. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  907. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  908. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  909. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  910. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  911. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  912. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  913. token.usd_update, block.timestamp
  914. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  915. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  916. WHERE tx.id = $1;`, txID,
  917. )
  918. return tx, tracerr.Wrap(err)
  919. }
  920. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  921. // and pagination info
  922. func (hdb *HistoryDB) GetHistoryTxs(
  923. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
  924. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  925. fromItem, limit *uint, order string,
  926. ) ([]TxAPI, uint64, error) {
  927. // Warning: amount_success and deposit_amount_success have true as default for
  928. // performance reasons. The expected default value is false (when txs are unforged)
  929. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  930. if ethAddr != nil && bjj != nil {
  931. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  932. }
  933. var query string
  934. var args []interface{}
  935. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  936. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  937. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  938. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  939. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  940. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  941. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  942. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  943. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  944. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  945. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  946. // Apply filters
  947. nextIsAnd := false
  948. // ethAddr filter
  949. if ethAddr != nil {
  950. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  951. nextIsAnd = true
  952. args = append(args, ethAddr, ethAddr)
  953. } else if bjj != nil { // bjj filter
  954. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  955. nextIsAnd = true
  956. args = append(args, bjj, bjj)
  957. }
  958. // tokenID filter
  959. if tokenID != nil {
  960. if nextIsAnd {
  961. queryStr += "AND "
  962. } else {
  963. queryStr += "WHERE "
  964. }
  965. queryStr += "tx.token_id = ? "
  966. args = append(args, tokenID)
  967. nextIsAnd = true
  968. }
  969. // idx filter
  970. if idx != nil {
  971. if nextIsAnd {
  972. queryStr += "AND "
  973. } else {
  974. queryStr += "WHERE "
  975. }
  976. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  977. args = append(args, idx, idx)
  978. nextIsAnd = true
  979. }
  980. // batchNum filter
  981. if batchNum != nil {
  982. if nextIsAnd {
  983. queryStr += "AND "
  984. } else {
  985. queryStr += "WHERE "
  986. }
  987. queryStr += "tx.batch_num = ? "
  988. args = append(args, batchNum)
  989. nextIsAnd = true
  990. }
  991. // txType filter
  992. if txType != nil {
  993. if nextIsAnd {
  994. queryStr += "AND "
  995. } else {
  996. queryStr += "WHERE "
  997. }
  998. queryStr += "tx.type = ? "
  999. args = append(args, txType)
  1000. nextIsAnd = true
  1001. }
  1002. if fromItem != nil {
  1003. if nextIsAnd {
  1004. queryStr += "AND "
  1005. } else {
  1006. queryStr += "WHERE "
  1007. }
  1008. if order == OrderAsc {
  1009. queryStr += "tx.item_id >= ? "
  1010. } else {
  1011. queryStr += "tx.item_id <= ? "
  1012. }
  1013. args = append(args, fromItem)
  1014. nextIsAnd = true
  1015. }
  1016. if nextIsAnd {
  1017. queryStr += "AND "
  1018. } else {
  1019. queryStr += "WHERE "
  1020. }
  1021. queryStr += "tx.batch_num IS NOT NULL "
  1022. // pagination
  1023. queryStr += "ORDER BY tx.item_id "
  1024. if order == OrderAsc {
  1025. queryStr += " ASC "
  1026. } else {
  1027. queryStr += " DESC "
  1028. }
  1029. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1030. query = hdb.db.Rebind(queryStr)
  1031. // log.Debug(query)
  1032. txsPtrs := []*TxAPI{}
  1033. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  1034. return nil, 0, tracerr.Wrap(err)
  1035. }
  1036. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  1037. if len(txs) == 0 {
  1038. return txs, 0, nil
  1039. }
  1040. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  1041. }
  1042. // GetAllExits returns all exit from the DB
  1043. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  1044. var exits []*common.ExitInfo
  1045. err := meddler.QueryAll(
  1046. hdb.db, &exits,
  1047. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  1048. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  1049. exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
  1050. )
  1051. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
  1052. }
  1053. // GetExitAPI returns a exit from the DB
  1054. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  1055. exit := &ExitAPI{}
  1056. err := meddler.QueryRow(
  1057. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  1058. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1059. account.bjj, account.eth_addr,
  1060. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1061. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1062. token.token_id, token.item_id AS token_item_id,
  1063. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1064. token.decimals, token.usd, token.usd_update
  1065. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1066. INNER JOIN token ON account.token_id = token.token_id
  1067. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  1068. )
  1069. return exit, tracerr.Wrap(err)
  1070. }
  1071. // GetExitsAPI returns a list of exits from the DB and pagination info
  1072. func (hdb *HistoryDB) GetExitsAPI(
  1073. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
  1074. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  1075. fromItem, limit *uint, order string,
  1076. ) ([]ExitAPI, uint64, error) {
  1077. if ethAddr != nil && bjj != nil {
  1078. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1079. }
  1080. var query string
  1081. var args []interface{}
  1082. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1083. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1084. account.bjj, account.eth_addr,
  1085. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1086. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1087. token.token_id, token.item_id AS token_item_id,
  1088. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1089. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1090. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1091. INNER JOIN token ON account.token_id = token.token_id `
  1092. // Apply filters
  1093. nextIsAnd := false
  1094. // ethAddr filter
  1095. if ethAddr != nil {
  1096. queryStr += "WHERE account.eth_addr = ? "
  1097. nextIsAnd = true
  1098. args = append(args, ethAddr)
  1099. } else if bjj != nil { // bjj filter
  1100. queryStr += "WHERE account.bjj = ? "
  1101. nextIsAnd = true
  1102. args = append(args, bjj)
  1103. }
  1104. // tokenID filter
  1105. if tokenID != nil {
  1106. if nextIsAnd {
  1107. queryStr += "AND "
  1108. } else {
  1109. queryStr += "WHERE "
  1110. }
  1111. queryStr += "account.token_id = ? "
  1112. args = append(args, tokenID)
  1113. nextIsAnd = true
  1114. }
  1115. // idx filter
  1116. if idx != nil {
  1117. if nextIsAnd {
  1118. queryStr += "AND "
  1119. } else {
  1120. queryStr += "WHERE "
  1121. }
  1122. queryStr += "exit_tree.account_idx = ? "
  1123. args = append(args, idx)
  1124. nextIsAnd = true
  1125. }
  1126. // batchNum filter
  1127. if batchNum != nil {
  1128. if nextIsAnd {
  1129. queryStr += "AND "
  1130. } else {
  1131. queryStr += "WHERE "
  1132. }
  1133. queryStr += "exit_tree.batch_num = ? "
  1134. args = append(args, batchNum)
  1135. nextIsAnd = true
  1136. }
  1137. // onlyPendingWithdraws
  1138. if onlyPendingWithdraws != nil {
  1139. if *onlyPendingWithdraws {
  1140. if nextIsAnd {
  1141. queryStr += "AND "
  1142. } else {
  1143. queryStr += "WHERE "
  1144. }
  1145. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1146. nextIsAnd = true
  1147. }
  1148. }
  1149. if fromItem != nil {
  1150. if nextIsAnd {
  1151. queryStr += "AND "
  1152. } else {
  1153. queryStr += "WHERE "
  1154. }
  1155. if order == OrderAsc {
  1156. queryStr += "exit_tree.item_id >= ? "
  1157. } else {
  1158. queryStr += "exit_tree.item_id <= ? "
  1159. }
  1160. args = append(args, fromItem)
  1161. // nextIsAnd = true
  1162. }
  1163. // pagination
  1164. queryStr += "ORDER BY exit_tree.item_id "
  1165. if order == OrderAsc {
  1166. queryStr += " ASC "
  1167. } else {
  1168. queryStr += " DESC "
  1169. }
  1170. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1171. query = hdb.db.Rebind(queryStr)
  1172. // log.Debug(query)
  1173. exits := []*ExitAPI{}
  1174. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1175. return nil, 0, tracerr.Wrap(err)
  1176. }
  1177. if len(exits) == 0 {
  1178. return []ExitAPI{}, 0, nil
  1179. }
  1180. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1181. }
  1182. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1183. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1184. var txs []*common.L1Tx
  1185. err := meddler.QueryAll(
  1186. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  1187. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1188. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1189. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  1190. tx.deposit_amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.deposit_amount_success THEN tx.deposit_amount ELSE '\x' END) AS effective_deposit_amount,
  1191. tx.eth_block_num, tx.type, tx.batch_num
  1192. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  1193. )
  1194. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1195. }
  1196. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1197. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1198. var txs []*common.L1Tx
  1199. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  1200. // that returned txs will always have effective amounts
  1201. err := meddler.QueryAll(
  1202. hdb.db, &txs,
  1203. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1204. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1205. tx.amount, tx.amount AS effective_amount,
  1206. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  1207. tx.eth_block_num, tx.type, tx.batch_num
  1208. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  1209. )
  1210. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1211. }
  1212. // GetAllL2Txs returns all L2Txs from the DB
  1213. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1214. var txs []*common.L2Tx
  1215. err := meddler.QueryAll(
  1216. hdb.db, &txs,
  1217. `SELECT tx.id, tx.batch_num, tx.position,
  1218. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1219. tx.type, tx.eth_block_num
  1220. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  1221. )
  1222. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  1223. }
  1224. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1225. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1226. var txs []*common.L1Tx
  1227. err := meddler.QueryAll(
  1228. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  1229. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1230. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1231. tx.amount, NULL AS effective_amount,
  1232. tx.deposit_amount, NULL AS effective_deposit_amount,
  1233. tx.eth_block_num, tx.type, tx.batch_num
  1234. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  1235. ORDER BY position;`,
  1236. toForgeL1TxsNum,
  1237. )
  1238. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1239. }
  1240. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1241. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1242. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1243. row := hdb.db.QueryRow(
  1244. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  1245. toForgeL1TxsNum,
  1246. )
  1247. var lastL1TxsPosition int
  1248. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  1249. }
  1250. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1251. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1252. *common.WDelayerVariables, error) {
  1253. var rollup common.RollupVariables
  1254. var auction common.AuctionVariables
  1255. var wDelayer common.WDelayerVariables
  1256. if err := meddler.QueryRow(hdb.db, &rollup,
  1257. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1258. return nil, nil, nil, tracerr.Wrap(err)
  1259. }
  1260. if err := meddler.QueryRow(hdb.db, &auction,
  1261. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1262. return nil, nil, nil, tracerr.Wrap(err)
  1263. }
  1264. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1265. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1266. return nil, nil, nil, tracerr.Wrap(err)
  1267. }
  1268. return &rollup, &auction, &wDelayer, nil
  1269. }
  1270. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1271. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  1272. }
  1273. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1274. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  1275. }
  1276. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1277. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  1278. }
  1279. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1280. if len(bucketUpdates) == 0 {
  1281. return nil
  1282. }
  1283. return tracerr.Wrap(db.BulkInsert(
  1284. d,
  1285. `INSERT INTO bucket_update (
  1286. eth_block_num,
  1287. num_bucket,
  1288. block_stamp,
  1289. withdrawals
  1290. ) VALUES %s;`,
  1291. bucketUpdates[:],
  1292. ))
  1293. }
  1294. // GetAllBucketUpdates retrieves all the bucket updates
  1295. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1296. var bucketUpdates []*common.BucketUpdate
  1297. err := meddler.QueryAll(
  1298. hdb.db, &bucketUpdates,
  1299. `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
  1300. FROM bucket_update ORDER BY item_id;`,
  1301. )
  1302. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1303. }
  1304. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1305. if len(tokenExchanges) == 0 {
  1306. return nil
  1307. }
  1308. return tracerr.Wrap(db.BulkInsert(
  1309. d,
  1310. `INSERT INTO token_exchange (
  1311. eth_block_num,
  1312. eth_addr,
  1313. value_usd
  1314. ) VALUES %s;`,
  1315. tokenExchanges[:],
  1316. ))
  1317. }
  1318. // GetAllTokenExchanges retrieves all the token exchanges
  1319. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1320. var tokenExchanges []*common.TokenExchange
  1321. err := meddler.QueryAll(
  1322. hdb.db, &tokenExchanges,
  1323. "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
  1324. )
  1325. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1326. }
  1327. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1328. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1329. if len(escapeHatchWithdrawals) == 0 {
  1330. return nil
  1331. }
  1332. return tracerr.Wrap(db.BulkInsert(
  1333. d,
  1334. `INSERT INTO escape_hatch_withdrawal (
  1335. eth_block_num,
  1336. who_addr,
  1337. to_addr,
  1338. token_addr,
  1339. amount
  1340. ) VALUES %s;`,
  1341. escapeHatchWithdrawals[:],
  1342. ))
  1343. }
  1344. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1345. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1346. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1347. err := meddler.QueryAll(
  1348. hdb.db, &escapeHatchWithdrawals,
  1349. "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
  1350. )
  1351. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1352. tracerr.Wrap(err)
  1353. }
  1354. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1355. // contract variables. This initial state is stored linked to block 0, which
  1356. // always exist in the DB and is used to store initialization data that always
  1357. // exist in the smart contracts.
  1358. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1359. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1360. txn, err := hdb.db.Beginx()
  1361. if err != nil {
  1362. return tracerr.Wrap(err)
  1363. }
  1364. defer func() {
  1365. if err != nil {
  1366. db.Rollback(txn)
  1367. }
  1368. }()
  1369. // Force EthBlockNum to be 0 because it's the block used to link data
  1370. // that belongs to the creation of the smart contracts
  1371. rollup.EthBlockNum = 0
  1372. auction.EthBlockNum = 0
  1373. wDelayer.EthBlockNum = 0
  1374. auction.DefaultSlotSetBidSlotNum = 0
  1375. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1376. return tracerr.Wrap(err)
  1377. }
  1378. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1379. return tracerr.Wrap(err)
  1380. }
  1381. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1382. return tracerr.Wrap(err)
  1383. }
  1384. return tracerr.Wrap(txn.Commit())
  1385. }
  1386. // setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
  1387. // of the given l1UserTxs (with an UPDATE)
  1388. func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
  1389. if len(txs) == 0 {
  1390. return nil
  1391. }
  1392. // Effective amounts are stored as success flags in the DB, with true value by default
  1393. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1394. // updated to become false
  1395. type txUpdate struct {
  1396. ID common.TxID `db:"id"`
  1397. AmountSuccess bool `db:"amount_success"`
  1398. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1399. }
  1400. txUpdates := []txUpdate{}
  1401. equal := func(a *big.Int, b *big.Int) bool {
  1402. return a.Cmp(b) == 0
  1403. }
  1404. for i := range txs {
  1405. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1406. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1407. if !amountSuccess || !depositAmountSuccess {
  1408. txUpdates = append(txUpdates, txUpdate{
  1409. ID: txs[i].TxID,
  1410. AmountSuccess: amountSuccess,
  1411. DepositAmountSuccess: depositAmountSuccess,
  1412. })
  1413. }
  1414. }
  1415. const query string = `
  1416. UPDATE tx SET
  1417. amount_success = tx_update.amount_success,
  1418. deposit_amount_success = tx_update.deposit_amount_success
  1419. FROM (VALUES
  1420. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
  1421. (:id, :amount_success, :deposit_amount_success)
  1422. ) as tx_update (id, amount_success, deposit_amount_success)
  1423. WHERE tx.id = tx_update.id;
  1424. `
  1425. if len(txUpdates) > 0 {
  1426. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1427. return tracerr.Wrap(err)
  1428. }
  1429. }
  1430. return nil
  1431. }
  1432. // AddBlockSCData stores all the information of a block retrieved by the
  1433. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1434. // the pagination system of the API/DB depends on this. Within blocks, all
  1435. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1436. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1437. txn, err := hdb.db.Beginx()
  1438. if err != nil {
  1439. return tracerr.Wrap(err)
  1440. }
  1441. defer func() {
  1442. if err != nil {
  1443. db.Rollback(txn)
  1444. }
  1445. }()
  1446. // Add block
  1447. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1448. return tracerr.Wrap(err)
  1449. }
  1450. // Add Coordinators
  1451. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1452. return tracerr.Wrap(err)
  1453. }
  1454. // Add Bids
  1455. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1456. return tracerr.Wrap(err)
  1457. }
  1458. // Add Tokens
  1459. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1460. return tracerr.Wrap(err)
  1461. }
  1462. // Prepare user L1 txs to be added.
  1463. // They must be added before the batch that will forge them (which can be in the same block)
  1464. // and after the account that will be sent to (also can be in the same block).
  1465. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1466. // the batch that forges those txs is inserted
  1467. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1468. for i := range blockData.Rollup.L1UserTxs {
  1469. batchThatForgesIsInTheBlock := false
  1470. for _, batch := range blockData.Rollup.Batches {
  1471. if batch.Batch.ForgeL1TxsNum != nil &&
  1472. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1473. // Tx is forged in this block. It's guaranteed that:
  1474. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1475. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1476. batchThatForgesIsInTheBlock = true
  1477. addAtBatchNum := batch.Batch.BatchNum - 1
  1478. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1479. break
  1480. }
  1481. }
  1482. if !batchThatForgesIsInTheBlock {
  1483. // User artificial batchNum 0 to add txs that are not forge in this block
  1484. // after all the accounts of the block have been added
  1485. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1486. }
  1487. }
  1488. // Add Batches
  1489. for i := range blockData.Rollup.Batches {
  1490. batch := &blockData.Rollup.Batches[i]
  1491. // Add Batch: this will trigger an update on the DB
  1492. // that will set the batch num of forged L1 txs in this batch
  1493. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1494. return tracerr.Wrap(err)
  1495. }
  1496. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1497. // L1UserTxs that have been forged in this batch
  1498. if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
  1499. return tracerr.Wrap(err)
  1500. }
  1501. // Add accounts
  1502. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1503. return tracerr.Wrap(err)
  1504. }
  1505. // Add forged l1 coordinator Txs
  1506. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1507. return tracerr.Wrap(err)
  1508. }
  1509. // Add l2 Txs
  1510. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1511. return tracerr.Wrap(err)
  1512. }
  1513. // Add user L1 txs that will be forged in next batch
  1514. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1515. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1516. return tracerr.Wrap(err)
  1517. }
  1518. }
  1519. // Add exit tree
  1520. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1521. return tracerr.Wrap(err)
  1522. }
  1523. }
  1524. // Add user L1 txs that won't be forged in this block
  1525. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1526. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1527. return tracerr.Wrap(err)
  1528. }
  1529. }
  1530. // Set SC Vars if there was an update
  1531. if blockData.Rollup.Vars != nil {
  1532. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1533. return tracerr.Wrap(err)
  1534. }
  1535. }
  1536. if blockData.Auction.Vars != nil {
  1537. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1538. return tracerr.Wrap(err)
  1539. }
  1540. }
  1541. if blockData.WDelayer.Vars != nil {
  1542. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1543. return tracerr.Wrap(err)
  1544. }
  1545. }
  1546. // Update withdrawals in exit tree table
  1547. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1548. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1549. return tracerr.Wrap(err)
  1550. }
  1551. // Add Escape Hatch Withdrawals
  1552. if err := hdb.addEscapeHatchWithdrawals(txn,
  1553. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1554. return tracerr.Wrap(err)
  1555. }
  1556. // Add Buckets withdrawals updates
  1557. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1558. return tracerr.Wrap(err)
  1559. }
  1560. // Add Token exchange updates
  1561. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1562. return tracerr.Wrap(err)
  1563. }
  1564. return tracerr.Wrap(txn.Commit())
  1565. }
  1566. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1567. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1568. coordinator := &CoordinatorAPI{}
  1569. err := meddler.QueryRow(
  1570. hdb.db, coordinator,
  1571. "SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
  1572. bidderAddr,
  1573. )
  1574. return coordinator, tracerr.Wrap(err)
  1575. }
  1576. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1577. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1578. bidderAddr, forgerAddr *ethCommon.Address,
  1579. fromItem, limit *uint, order string,
  1580. ) ([]CoordinatorAPI, uint64, error) {
  1581. var query string
  1582. var args []interface{}
  1583. queryStr := `SELECT coordinator.*, COUNT(*) OVER() AS total_items
  1584. FROM coordinator INNER JOIN (
  1585. SELECT MAX(item_id) AS item_id FROM coordinator
  1586. GROUP BY bidder_addr
  1587. ) c ON coordinator.item_id = c.item_id `
  1588. // Apply filters
  1589. nextIsAnd := false
  1590. if bidderAddr != nil {
  1591. queryStr += "WHERE bidder_addr = ? "
  1592. nextIsAnd = true
  1593. args = append(args, bidderAddr)
  1594. }
  1595. if forgerAddr != nil {
  1596. if nextIsAnd {
  1597. queryStr += "AND "
  1598. } else {
  1599. queryStr += "WHERE "
  1600. }
  1601. queryStr += "forger_addr = ? "
  1602. nextIsAnd = true
  1603. args = append(args, forgerAddr)
  1604. }
  1605. if fromItem != nil {
  1606. if nextIsAnd {
  1607. queryStr += "AND "
  1608. } else {
  1609. queryStr += "WHERE "
  1610. }
  1611. if order == OrderAsc {
  1612. queryStr += "coordinator.item_id >= ? "
  1613. } else {
  1614. queryStr += "coordinator.item_id <= ? "
  1615. }
  1616. args = append(args, fromItem)
  1617. }
  1618. // pagination
  1619. queryStr += "ORDER BY coordinator.item_id "
  1620. if order == OrderAsc {
  1621. queryStr += " ASC "
  1622. } else {
  1623. queryStr += " DESC "
  1624. }
  1625. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1626. query = hdb.db.Rebind(queryStr)
  1627. coordinators := []*CoordinatorAPI{}
  1628. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1629. return nil, 0, tracerr.Wrap(err)
  1630. }
  1631. if len(coordinators) == 0 {
  1632. return []CoordinatorAPI{}, 0, nil
  1633. }
  1634. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1635. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1636. }
  1637. // AddAuctionVars insert auction vars into the DB
  1638. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1639. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1640. }
  1641. // GetAuctionVars returns auction variables
  1642. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1643. auctionVars := &common.AuctionVariables{}
  1644. err := meddler.QueryRow(
  1645. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1646. )
  1647. return auctionVars, tracerr.Wrap(err)
  1648. }
  1649. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1650. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1651. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1652. auctionVars := []*MinBidInfo{}
  1653. query := `
  1654. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1655. WHERE default_slot_set_bid_slot_num < $1
  1656. ORDER BY default_slot_set_bid_slot_num DESC
  1657. LIMIT $2;
  1658. `
  1659. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1660. if err != nil {
  1661. return nil, tracerr.Wrap(err)
  1662. }
  1663. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1664. }
  1665. // GetAccountAPI returns an account by its index
  1666. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1667. account := &AccountAPI{}
  1668. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1669. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1670. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1671. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1672. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1673. if err != nil {
  1674. return nil, tracerr.Wrap(err)
  1675. }
  1676. return account, nil
  1677. }
  1678. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1679. func (hdb *HistoryDB) GetAccountsAPI(
  1680. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1681. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1682. ) ([]AccountAPI, uint64, error) {
  1683. if ethAddr != nil && bjj != nil {
  1684. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1685. }
  1686. var query string
  1687. var args []interface{}
  1688. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1689. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1690. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1691. COUNT(*) OVER() AS total_items
  1692. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1693. // Apply filters
  1694. nextIsAnd := false
  1695. // ethAddr filter
  1696. if ethAddr != nil {
  1697. queryStr += "WHERE account.eth_addr = ? "
  1698. nextIsAnd = true
  1699. args = append(args, ethAddr)
  1700. } else if bjj != nil { // bjj filter
  1701. queryStr += "WHERE account.bjj = ? "
  1702. nextIsAnd = true
  1703. args = append(args, bjj)
  1704. }
  1705. // tokenID filter
  1706. if len(tokenIDs) > 0 {
  1707. if nextIsAnd {
  1708. queryStr += "AND "
  1709. } else {
  1710. queryStr += "WHERE "
  1711. }
  1712. queryStr += "account.token_id IN (?) "
  1713. args = append(args, tokenIDs)
  1714. nextIsAnd = true
  1715. }
  1716. if fromItem != nil {
  1717. if nextIsAnd {
  1718. queryStr += "AND "
  1719. } else {
  1720. queryStr += "WHERE "
  1721. }
  1722. if order == OrderAsc {
  1723. queryStr += "account.item_id >= ? "
  1724. } else {
  1725. queryStr += "account.item_id <= ? "
  1726. }
  1727. args = append(args, fromItem)
  1728. }
  1729. // pagination
  1730. queryStr += "ORDER BY account.item_id "
  1731. if order == OrderAsc {
  1732. queryStr += " ASC "
  1733. } else {
  1734. queryStr += " DESC "
  1735. }
  1736. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1737. query, argsQ, err := sqlx.In(queryStr, args...)
  1738. if err != nil {
  1739. return nil, 0, tracerr.Wrap(err)
  1740. }
  1741. query = hdb.db.Rebind(query)
  1742. accounts := []*AccountAPI{}
  1743. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1744. return nil, 0, tracerr.Wrap(err)
  1745. }
  1746. if len(accounts) == 0 {
  1747. return []AccountAPI{}, 0, nil
  1748. }
  1749. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1750. accounts[0].TotalItems - uint64(len(accounts)), nil
  1751. }
  1752. // GetMetrics returns metrics
  1753. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1754. metricsTotals := &MetricsTotals{}
  1755. metrics := &Metrics{}
  1756. err := meddler.QueryRow(
  1757. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1758. COALESCE (MIN(tx.batch_num), 0) as batch_num, COALESCE (MIN(block.timestamp),
  1759. NOW()) AS min_timestamp, COALESCE (MAX(block.timestamp), NOW()) AS max_timestamp
  1760. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1761. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1762. if err != nil {
  1763. return nil, tracerr.Wrap(err)
  1764. }
  1765. seconds := metricsTotals.MaxTimestamp.Sub(metricsTotals.MinTimestamp).Seconds()
  1766. // Avoid dividing by 0
  1767. if seconds == 0 {
  1768. seconds++
  1769. }
  1770. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions) / seconds
  1771. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1772. metrics.TransactionsPerBatch = float64(metricsTotals.TotalTransactions) /
  1773. float64(lastBatchNum-metricsTotals.FirstBatchNum+1)
  1774. } else {
  1775. metrics.TransactionsPerBatch = float64(0)
  1776. }
  1777. err = meddler.QueryRow(
  1778. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1779. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1780. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1781. if err != nil {
  1782. return nil, tracerr.Wrap(err)
  1783. }
  1784. if metricsTotals.TotalBatches > 0 {
  1785. metrics.BatchFrequency = seconds / float64(metricsTotals.TotalBatches)
  1786. } else {
  1787. metrics.BatchFrequency = 0
  1788. }
  1789. if metricsTotals.TotalTransactions > 0 {
  1790. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1791. } else {
  1792. metrics.AvgTransactionFee = 0
  1793. }
  1794. err = meddler.QueryRow(
  1795. hdb.db, metrics,
  1796. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1797. if err != nil {
  1798. return nil, tracerr.Wrap(err)
  1799. }
  1800. return metrics, nil
  1801. }
  1802. // GetAvgTxFee returns average transaction fee of the last 1h
  1803. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1804. metricsTotals := &MetricsTotals{}
  1805. err := meddler.QueryRow(
  1806. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1807. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1808. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1809. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1810. if err != nil {
  1811. return 0, tracerr.Wrap(err)
  1812. }
  1813. err = meddler.QueryRow(
  1814. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1815. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1816. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1817. if err != nil {
  1818. return 0, tracerr.Wrap(err)
  1819. }
  1820. var avgTransactionFee float64
  1821. if metricsTotals.TotalTransactions > 0 {
  1822. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1823. } else {
  1824. avgTransactionFee = 0
  1825. }
  1826. return avgTransactionFee, nil
  1827. }