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.

1922 lines
60 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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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 coordinator ON bid.bidder_addr = coordinator.bidder_addr
  356. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  357. )
  358. return *bid, tracerr.Wrap(err)
  359. }
  360. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  361. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  362. bidCoord := &common.BidCoordinator{}
  363. err := meddler.QueryRow(
  364. hdb.db, bidCoord,
  365. `SELECT (
  366. SELECT default_slot_set_bid
  367. FROM auction_vars
  368. WHERE default_slot_set_bid_slot_num <= $1
  369. ORDER BY eth_block_num DESC LIMIT 1
  370. ),
  371. bid.slot_num, bid.bid_value, bid.bidder_addr,
  372. coordinator.forger_addr, coordinator.url
  373. FROM bid
  374. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  375. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  376. slotNum)
  377. return bidCoord, tracerr.Wrap(err)
  378. }
  379. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  380. func (hdb *HistoryDB) GetBestBidsAPI(
  381. minSlotNum, maxSlotNum *int64,
  382. bidderAddr *ethCommon.Address,
  383. limit *uint, order string,
  384. ) ([]BidAPI, uint64, error) {
  385. var query string
  386. var args []interface{}
  387. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  388. COUNT(*) OVER() AS total_items FROM (
  389. SELECT slot_num, MAX(item_id) as maxitem
  390. FROM bid GROUP BY slot_num
  391. )
  392. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  393. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  394. INNER JOIN coordinator ON b.bidder_addr = coordinator.bidder_addr
  395. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  396. args = append(args, minSlotNum)
  397. args = append(args, maxSlotNum)
  398. // Apply filters
  399. if bidderAddr != nil {
  400. queryStr += " AND b.bidder_addr = ? "
  401. args = append(args, bidderAddr)
  402. }
  403. queryStr += " ORDER BY b.slot_num "
  404. if order == OrderAsc {
  405. queryStr += "ASC "
  406. } else {
  407. queryStr += "DESC "
  408. }
  409. if limit != nil {
  410. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  411. }
  412. query = hdb.db.Rebind(queryStr)
  413. bidPtrs := []*BidAPI{}
  414. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  415. return nil, 0, tracerr.Wrap(err)
  416. }
  417. // log.Debug(query)
  418. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  419. if len(bids) == 0 {
  420. return bids, 0, nil
  421. }
  422. return bids, bids[0].TotalItems - uint64(len(bids)), nil
  423. }
  424. // GetBidsAPI return the bids applying the given filters
  425. func (hdb *HistoryDB) GetBidsAPI(
  426. slotNum *int64, forgerAddr *ethCommon.Address,
  427. fromItem, limit *uint, order string,
  428. ) ([]BidAPI, uint64, error) {
  429. var query string
  430. var args []interface{}
  431. queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  432. COUNT(*) OVER() AS total_items
  433. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  434. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
  435. // Apply filters
  436. nextIsAnd := false
  437. // slotNum filter
  438. if slotNum != nil {
  439. if nextIsAnd {
  440. queryStr += "AND "
  441. } else {
  442. queryStr += "WHERE "
  443. }
  444. queryStr += "bid.slot_num = ? "
  445. args = append(args, slotNum)
  446. nextIsAnd = true
  447. }
  448. // slotNum filter
  449. if forgerAddr != nil {
  450. if nextIsAnd {
  451. queryStr += "AND "
  452. } else {
  453. queryStr += "WHERE "
  454. }
  455. queryStr += "bid.bidder_addr = ? "
  456. args = append(args, forgerAddr)
  457. nextIsAnd = true
  458. }
  459. if fromItem != nil {
  460. if nextIsAnd {
  461. queryStr += "AND "
  462. } else {
  463. queryStr += "WHERE "
  464. }
  465. if order == OrderAsc {
  466. queryStr += "bid.item_id >= ? "
  467. } else {
  468. queryStr += "bid.item_id <= ? "
  469. }
  470. args = append(args, fromItem)
  471. }
  472. // pagination
  473. queryStr += "ORDER BY bid.item_id "
  474. if order == OrderAsc {
  475. queryStr += "ASC "
  476. } else {
  477. queryStr += "DESC "
  478. }
  479. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  480. query, argsQ, err := sqlx.In(queryStr, args...)
  481. if err != nil {
  482. return nil, 0, tracerr.Wrap(err)
  483. }
  484. query = hdb.db.Rebind(query)
  485. bids := []*BidAPI{}
  486. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  487. return nil, 0, tracerr.Wrap(err)
  488. }
  489. if len(bids) == 0 {
  490. return []BidAPI{}, 0, nil
  491. }
  492. return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
  493. }
  494. // AddCoordinators insert Coordinators into the DB
  495. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  496. return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
  497. }
  498. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  499. if len(coordinators) == 0 {
  500. return nil
  501. }
  502. return tracerr.Wrap(db.BulkInsert(
  503. d,
  504. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  505. coordinators[:],
  506. ))
  507. }
  508. // AddExitTree insert Exit tree into the DB
  509. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  510. return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
  511. }
  512. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  513. if len(exitTree) == 0 {
  514. return nil
  515. }
  516. return tracerr.Wrap(db.BulkInsert(
  517. d,
  518. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  519. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  520. exitTree[:],
  521. ))
  522. }
  523. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  524. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  525. if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
  526. return nil
  527. }
  528. type withdrawal struct {
  529. BatchNum int64 `db:"batch_num"`
  530. AccountIdx int64 `db:"account_idx"`
  531. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  532. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  533. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  534. Owner *ethCommon.Address `db:"owner"`
  535. Token *ethCommon.Address `db:"token"`
  536. }
  537. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  538. for i := range rollupWithdrawals {
  539. info := &rollupWithdrawals[i]
  540. withdrawals[i] = withdrawal{
  541. BatchNum: int64(info.NumExitRoot),
  542. AccountIdx: int64(info.Idx),
  543. }
  544. if info.InstantWithdraw {
  545. withdrawals[i].InstantWithdrawn = &blockNum
  546. } else {
  547. withdrawals[i].DelayedWithdrawRequest = &blockNum
  548. withdrawals[i].Owner = &info.Owner
  549. withdrawals[i].Token = &info.Token
  550. }
  551. }
  552. for i := range wDelayerWithdrawals {
  553. info := &wDelayerWithdrawals[i]
  554. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  555. DelayedWithdrawn: &blockNum,
  556. Owner: &info.Owner,
  557. Token: &info.Token,
  558. }
  559. }
  560. // In VALUES we set an initial row of NULLs to set the types of each
  561. // variable passed as argument
  562. const query string = `
  563. UPDATE exit_tree e SET
  564. instant_withdrawn = d.instant_withdrawn,
  565. delayed_withdraw_request = CASE
  566. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  567. ELSE d.delayed_withdraw_request
  568. END,
  569. delayed_withdrawn = d.delayed_withdrawn,
  570. owner = d.owner,
  571. token = d.token
  572. FROM (VALUES
  573. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  574. (:batch_num,
  575. :account_idx,
  576. :instant_withdrawn,
  577. :delayed_withdraw_request,
  578. :delayed_withdrawn,
  579. :owner,
  580. :token)
  581. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  582. WHERE
  583. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  584. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
  585. `
  586. if len(withdrawals) > 0 {
  587. if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
  588. return tracerr.Wrap(err)
  589. }
  590. }
  591. return nil
  592. }
  593. // AddToken insert a token into the DB
  594. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  595. return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
  596. }
  597. // AddTokens insert tokens into the DB
  598. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  599. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  600. if len(tokens) == 0 {
  601. return nil
  602. }
  603. // Sanitize name and symbol
  604. for i, token := range tokens {
  605. token.Name = strings.ToValidUTF8(token.Name, " ")
  606. token.Symbol = strings.ToValidUTF8(token.Symbol, " ")
  607. tokens[i] = token
  608. }
  609. return tracerr.Wrap(db.BulkInsert(
  610. d,
  611. `INSERT INTO token (
  612. token_id,
  613. eth_block_num,
  614. eth_addr,
  615. name,
  616. symbol,
  617. decimals
  618. ) VALUES %s;`,
  619. tokens[:],
  620. ))
  621. }
  622. // UpdateTokenValue updates the USD value of a token
  623. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  624. // Sanitize symbol
  625. tokenSymbol = strings.ToValidUTF8(tokenSymbol, " ")
  626. _, err := hdb.db.Exec(
  627. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  628. value, tokenSymbol,
  629. )
  630. return tracerr.Wrap(err)
  631. }
  632. // GetToken returns a token from the DB given a TokenID
  633. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  634. token := &TokenWithUSD{}
  635. err := meddler.QueryRow(
  636. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  637. )
  638. return token, tracerr.Wrap(err)
  639. }
  640. // GetAllTokens returns all tokens from the DB
  641. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  642. var tokens []*TokenWithUSD
  643. err := meddler.QueryAll(
  644. hdb.db, &tokens,
  645. "SELECT * FROM token ORDER BY token_id;",
  646. )
  647. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
  648. }
  649. // GetTokens returns a list of tokens from the DB
  650. func (hdb *HistoryDB) GetTokens(
  651. ids []common.TokenID, symbols []string, name string, fromItem,
  652. limit *uint, order string,
  653. ) ([]TokenWithUSD, uint64, error) {
  654. var query string
  655. var args []interface{}
  656. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  657. // Apply filters
  658. nextIsAnd := false
  659. if len(ids) > 0 {
  660. queryStr += "WHERE token_id IN (?) "
  661. nextIsAnd = true
  662. args = append(args, ids)
  663. }
  664. if len(symbols) > 0 {
  665. if nextIsAnd {
  666. queryStr += "AND "
  667. } else {
  668. queryStr += "WHERE "
  669. }
  670. queryStr += "symbol IN (?) "
  671. args = append(args, symbols)
  672. nextIsAnd = true
  673. }
  674. if name != "" {
  675. if nextIsAnd {
  676. queryStr += "AND "
  677. } else {
  678. queryStr += "WHERE "
  679. }
  680. queryStr += "name ~ ? "
  681. args = append(args, name)
  682. nextIsAnd = true
  683. }
  684. if fromItem != nil {
  685. if nextIsAnd {
  686. queryStr += "AND "
  687. } else {
  688. queryStr += "WHERE "
  689. }
  690. if order == OrderAsc {
  691. queryStr += "item_id >= ? "
  692. } else {
  693. queryStr += "item_id <= ? "
  694. }
  695. args = append(args, fromItem)
  696. }
  697. // pagination
  698. queryStr += "ORDER BY item_id "
  699. if order == OrderAsc {
  700. queryStr += "ASC "
  701. } else {
  702. queryStr += "DESC "
  703. }
  704. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  705. query, argsQ, err := sqlx.In(queryStr, args...)
  706. if err != nil {
  707. return nil, 0, tracerr.Wrap(err)
  708. }
  709. query = hdb.db.Rebind(query)
  710. tokens := []*TokenWithUSD{}
  711. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  712. return nil, 0, tracerr.Wrap(err)
  713. }
  714. if len(tokens) == 0 {
  715. return []TokenWithUSD{}, 0, nil
  716. }
  717. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  718. }
  719. // GetTokenSymbols returns all the token symbols from the DB
  720. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  721. var tokenSymbols []string
  722. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  723. if err != nil {
  724. return nil, tracerr.Wrap(err)
  725. }
  726. defer db.RowsClose(rows)
  727. sym := new(string)
  728. for rows.Next() {
  729. err = rows.Scan(sym)
  730. if err != nil {
  731. return nil, tracerr.Wrap(err)
  732. }
  733. tokenSymbols = append(tokenSymbols, *sym)
  734. }
  735. return tokenSymbols, nil
  736. }
  737. // AddAccounts insert accounts into the DB
  738. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  739. return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
  740. }
  741. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  742. if len(accounts) == 0 {
  743. return nil
  744. }
  745. return tracerr.Wrap(db.BulkInsert(
  746. d,
  747. `INSERT INTO account (
  748. idx,
  749. token_id,
  750. batch_num,
  751. bjj,
  752. eth_addr
  753. ) VALUES %s;`,
  754. accounts[:],
  755. ))
  756. }
  757. // GetAllAccounts returns a list of accounts from the DB
  758. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  759. var accs []*common.Account
  760. err := meddler.QueryAll(
  761. hdb.db, &accs,
  762. "SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
  763. )
  764. return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
  765. }
  766. // AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  767. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  768. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  769. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  770. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
  771. return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
  772. }
  773. // addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  774. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  775. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  776. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  777. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  778. if len(l1txs) == 0 {
  779. return nil
  780. }
  781. txs := []txWrite{}
  782. for i := 0; i < len(l1txs); i++ {
  783. af := new(big.Float).SetInt(l1txs[i].Amount)
  784. amountFloat, _ := af.Float64()
  785. laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
  786. depositAmountFloat, _ := laf.Float64()
  787. txs = append(txs, txWrite{
  788. // Generic
  789. IsL1: true,
  790. TxID: l1txs[i].TxID,
  791. Type: l1txs[i].Type,
  792. Position: l1txs[i].Position,
  793. FromIdx: &l1txs[i].FromIdx,
  794. ToIdx: l1txs[i].ToIdx,
  795. Amount: l1txs[i].Amount,
  796. AmountFloat: amountFloat,
  797. TokenID: l1txs[i].TokenID,
  798. BatchNum: l1txs[i].BatchNum,
  799. EthBlockNum: l1txs[i].EthBlockNum,
  800. // L1
  801. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  802. UserOrigin: &l1txs[i].UserOrigin,
  803. FromEthAddr: &l1txs[i].FromEthAddr,
  804. FromBJJ: &l1txs[i].FromBJJ,
  805. DepositAmount: l1txs[i].DepositAmount,
  806. DepositAmountFloat: &depositAmountFloat,
  807. })
  808. }
  809. return tracerr.Wrap(hdb.addTxs(d, txs))
  810. }
  811. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  812. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
  813. return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
  814. }
  815. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  816. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  817. txs := []txWrite{}
  818. for i := 0; i < len(l2txs); i++ {
  819. f := new(big.Float).SetInt(l2txs[i].Amount)
  820. amountFloat, _ := f.Float64()
  821. txs = append(txs, txWrite{
  822. // Generic
  823. IsL1: false,
  824. TxID: l2txs[i].TxID,
  825. Type: l2txs[i].Type,
  826. Position: l2txs[i].Position,
  827. FromIdx: &l2txs[i].FromIdx,
  828. ToIdx: l2txs[i].ToIdx,
  829. Amount: l2txs[i].Amount,
  830. AmountFloat: amountFloat,
  831. BatchNum: &l2txs[i].BatchNum,
  832. EthBlockNum: l2txs[i].EthBlockNum,
  833. // L2
  834. Fee: &l2txs[i].Fee,
  835. Nonce: &l2txs[i].Nonce,
  836. })
  837. }
  838. return tracerr.Wrap(hdb.addTxs(d, txs))
  839. }
  840. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  841. if len(txs) == 0 {
  842. return nil
  843. }
  844. return tracerr.Wrap(db.BulkInsert(
  845. d,
  846. `INSERT INTO tx (
  847. is_l1,
  848. id,
  849. type,
  850. position,
  851. from_idx,
  852. to_idx,
  853. amount,
  854. amount_f,
  855. token_id,
  856. batch_num,
  857. eth_block_num,
  858. to_forge_l1_txs_num,
  859. user_origin,
  860. from_eth_addr,
  861. from_bjj,
  862. deposit_amount,
  863. deposit_amount_f,
  864. fee,
  865. nonce
  866. ) VALUES %s;`,
  867. txs[:],
  868. ))
  869. }
  870. // // GetTxs returns a list of txs from the DB
  871. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  872. // var txs []*common.Tx
  873. // err := meddler.QueryAll(
  874. // hdb.db, &txs,
  875. // `SELECT * FROM tx
  876. // ORDER BY (batch_num, position) ASC`,
  877. // )
  878. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  879. // }
  880. // GetHistoryTx returns a tx from the DB given a TxID
  881. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  882. // Warning: amount_success and deposit_amount_success have true as default for
  883. // performance reasons. The expected default value is false (when txs are unforged)
  884. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  885. tx := &TxAPI{}
  886. err := meddler.QueryRow(
  887. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  888. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  889. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  890. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  891. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  892. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  893. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  894. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  895. token.usd_update, block.timestamp
  896. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  897. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  898. WHERE tx.id = $1;`, txID,
  899. )
  900. return tx, tracerr.Wrap(err)
  901. }
  902. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  903. // and pagination info
  904. func (hdb *HistoryDB) GetHistoryTxs(
  905. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
  906. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  907. fromItem, limit *uint, order string,
  908. ) ([]TxAPI, uint64, error) {
  909. // Warning: amount_success and deposit_amount_success have true as default for
  910. // performance reasons. The expected default value is false (when txs are unforged)
  911. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  912. if ethAddr != nil && bjj != nil {
  913. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  914. }
  915. var query string
  916. var args []interface{}
  917. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  918. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  919. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  920. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  921. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  922. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  923. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  924. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  925. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  926. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  927. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  928. // Apply filters
  929. nextIsAnd := false
  930. // ethAddr filter
  931. if ethAddr != nil {
  932. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  933. nextIsAnd = true
  934. args = append(args, ethAddr, ethAddr)
  935. } else if bjj != nil { // bjj filter
  936. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  937. nextIsAnd = true
  938. args = append(args, bjj, bjj)
  939. }
  940. // tokenID filter
  941. if tokenID != nil {
  942. if nextIsAnd {
  943. queryStr += "AND "
  944. } else {
  945. queryStr += "WHERE "
  946. }
  947. queryStr += "tx.token_id = ? "
  948. args = append(args, tokenID)
  949. nextIsAnd = true
  950. }
  951. // idx filter
  952. if idx != nil {
  953. if nextIsAnd {
  954. queryStr += "AND "
  955. } else {
  956. queryStr += "WHERE "
  957. }
  958. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  959. args = append(args, idx, idx)
  960. nextIsAnd = true
  961. }
  962. // batchNum filter
  963. if batchNum != nil {
  964. if nextIsAnd {
  965. queryStr += "AND "
  966. } else {
  967. queryStr += "WHERE "
  968. }
  969. queryStr += "tx.batch_num = ? "
  970. args = append(args, batchNum)
  971. nextIsAnd = true
  972. }
  973. // txType filter
  974. if txType != nil {
  975. if nextIsAnd {
  976. queryStr += "AND "
  977. } else {
  978. queryStr += "WHERE "
  979. }
  980. queryStr += "tx.type = ? "
  981. args = append(args, txType)
  982. nextIsAnd = true
  983. }
  984. if fromItem != nil {
  985. if nextIsAnd {
  986. queryStr += "AND "
  987. } else {
  988. queryStr += "WHERE "
  989. }
  990. if order == OrderAsc {
  991. queryStr += "tx.item_id >= ? "
  992. } else {
  993. queryStr += "tx.item_id <= ? "
  994. }
  995. args = append(args, fromItem)
  996. nextIsAnd = true
  997. }
  998. if nextIsAnd {
  999. queryStr += "AND "
  1000. } else {
  1001. queryStr += "WHERE "
  1002. }
  1003. queryStr += "tx.batch_num IS NOT NULL "
  1004. // pagination
  1005. queryStr += "ORDER BY tx.item_id "
  1006. if order == OrderAsc {
  1007. queryStr += " ASC "
  1008. } else {
  1009. queryStr += " DESC "
  1010. }
  1011. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1012. query = hdb.db.Rebind(queryStr)
  1013. // log.Debug(query)
  1014. txsPtrs := []*TxAPI{}
  1015. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  1016. return nil, 0, tracerr.Wrap(err)
  1017. }
  1018. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  1019. if len(txs) == 0 {
  1020. return txs, 0, nil
  1021. }
  1022. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  1023. }
  1024. // GetAllExits returns all exit from the DB
  1025. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  1026. var exits []*common.ExitInfo
  1027. err := meddler.QueryAll(
  1028. hdb.db, &exits,
  1029. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  1030. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  1031. exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
  1032. )
  1033. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
  1034. }
  1035. // GetExitAPI returns a exit from the DB
  1036. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  1037. exit := &ExitAPI{}
  1038. err := meddler.QueryRow(
  1039. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  1040. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1041. account.bjj, account.eth_addr,
  1042. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1043. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1044. token.token_id, token.item_id AS token_item_id,
  1045. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1046. token.decimals, token.usd, token.usd_update
  1047. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1048. INNER JOIN token ON account.token_id = token.token_id
  1049. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  1050. )
  1051. return exit, tracerr.Wrap(err)
  1052. }
  1053. // GetExitsAPI returns a list of exits from the DB and pagination info
  1054. func (hdb *HistoryDB) GetExitsAPI(
  1055. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
  1056. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  1057. fromItem, limit *uint, order string,
  1058. ) ([]ExitAPI, uint64, error) {
  1059. if ethAddr != nil && bjj != nil {
  1060. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1061. }
  1062. var query string
  1063. var args []interface{}
  1064. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1065. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1066. account.bjj, account.eth_addr,
  1067. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1068. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1069. token.token_id, token.item_id AS token_item_id,
  1070. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1071. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1072. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1073. INNER JOIN token ON account.token_id = token.token_id `
  1074. // Apply filters
  1075. nextIsAnd := false
  1076. // ethAddr filter
  1077. if ethAddr != nil {
  1078. queryStr += "WHERE account.eth_addr = ? "
  1079. nextIsAnd = true
  1080. args = append(args, ethAddr)
  1081. } else if bjj != nil { // bjj filter
  1082. queryStr += "WHERE account.bjj = ? "
  1083. nextIsAnd = true
  1084. args = append(args, bjj)
  1085. }
  1086. // tokenID filter
  1087. if tokenID != nil {
  1088. if nextIsAnd {
  1089. queryStr += "AND "
  1090. } else {
  1091. queryStr += "WHERE "
  1092. }
  1093. queryStr += "account.token_id = ? "
  1094. args = append(args, tokenID)
  1095. nextIsAnd = true
  1096. }
  1097. // idx filter
  1098. if idx != nil {
  1099. if nextIsAnd {
  1100. queryStr += "AND "
  1101. } else {
  1102. queryStr += "WHERE "
  1103. }
  1104. queryStr += "exit_tree.account_idx = ? "
  1105. args = append(args, idx)
  1106. nextIsAnd = true
  1107. }
  1108. // batchNum filter
  1109. if batchNum != nil {
  1110. if nextIsAnd {
  1111. queryStr += "AND "
  1112. } else {
  1113. queryStr += "WHERE "
  1114. }
  1115. queryStr += "exit_tree.batch_num = ? "
  1116. args = append(args, batchNum)
  1117. nextIsAnd = true
  1118. }
  1119. // onlyPendingWithdraws
  1120. if onlyPendingWithdraws != nil {
  1121. if *onlyPendingWithdraws {
  1122. if nextIsAnd {
  1123. queryStr += "AND "
  1124. } else {
  1125. queryStr += "WHERE "
  1126. }
  1127. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1128. nextIsAnd = true
  1129. }
  1130. }
  1131. if fromItem != nil {
  1132. if nextIsAnd {
  1133. queryStr += "AND "
  1134. } else {
  1135. queryStr += "WHERE "
  1136. }
  1137. if order == OrderAsc {
  1138. queryStr += "exit_tree.item_id >= ? "
  1139. } else {
  1140. queryStr += "exit_tree.item_id <= ? "
  1141. }
  1142. args = append(args, fromItem)
  1143. // nextIsAnd = true
  1144. }
  1145. // pagination
  1146. queryStr += "ORDER BY exit_tree.item_id "
  1147. if order == OrderAsc {
  1148. queryStr += " ASC "
  1149. } else {
  1150. queryStr += " DESC "
  1151. }
  1152. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1153. query = hdb.db.Rebind(queryStr)
  1154. // log.Debug(query)
  1155. exits := []*ExitAPI{}
  1156. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1157. return nil, 0, tracerr.Wrap(err)
  1158. }
  1159. if len(exits) == 0 {
  1160. return []ExitAPI{}, 0, nil
  1161. }
  1162. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1163. }
  1164. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1165. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1166. var txs []*common.L1Tx
  1167. err := meddler.QueryAll(
  1168. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  1169. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1170. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1171. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  1172. 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,
  1173. tx.eth_block_num, tx.type, tx.batch_num
  1174. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  1175. )
  1176. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1177. }
  1178. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1179. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1180. var txs []*common.L1Tx
  1181. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  1182. // that returned txs will always have effective amounts
  1183. err := meddler.QueryAll(
  1184. hdb.db, &txs,
  1185. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1186. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1187. tx.amount, tx.amount AS effective_amount,
  1188. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  1189. tx.eth_block_num, tx.type, tx.batch_num
  1190. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  1191. )
  1192. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1193. }
  1194. // GetAllL2Txs returns all L2Txs from the DB
  1195. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1196. var txs []*common.L2Tx
  1197. err := meddler.QueryAll(
  1198. hdb.db, &txs,
  1199. `SELECT tx.id, tx.batch_num, tx.position,
  1200. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1201. tx.type, tx.eth_block_num
  1202. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  1203. )
  1204. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  1205. }
  1206. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1207. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1208. var txs []*common.L1Tx
  1209. err := meddler.QueryAll(
  1210. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  1211. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1212. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1213. tx.amount, NULL AS effective_amount,
  1214. tx.deposit_amount, NULL AS effective_deposit_amount,
  1215. tx.eth_block_num, tx.type, tx.batch_num
  1216. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  1217. ORDER BY position;`,
  1218. toForgeL1TxsNum,
  1219. )
  1220. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1221. }
  1222. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1223. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1224. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1225. row := hdb.db.QueryRow(
  1226. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  1227. toForgeL1TxsNum,
  1228. )
  1229. var lastL1TxsPosition int
  1230. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  1231. }
  1232. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1233. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1234. *common.WDelayerVariables, error) {
  1235. var rollup common.RollupVariables
  1236. var auction common.AuctionVariables
  1237. var wDelayer common.WDelayerVariables
  1238. if err := meddler.QueryRow(hdb.db, &rollup,
  1239. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1240. return nil, nil, nil, tracerr.Wrap(err)
  1241. }
  1242. if err := meddler.QueryRow(hdb.db, &auction,
  1243. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1244. return nil, nil, nil, tracerr.Wrap(err)
  1245. }
  1246. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1247. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1248. return nil, nil, nil, tracerr.Wrap(err)
  1249. }
  1250. return &rollup, &auction, &wDelayer, nil
  1251. }
  1252. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1253. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  1254. }
  1255. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1256. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  1257. }
  1258. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1259. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  1260. }
  1261. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1262. if len(bucketUpdates) == 0 {
  1263. return nil
  1264. }
  1265. return tracerr.Wrap(db.BulkInsert(
  1266. d,
  1267. `INSERT INTO bucket_update (
  1268. eth_block_num,
  1269. num_bucket,
  1270. block_stamp,
  1271. withdrawals
  1272. ) VALUES %s;`,
  1273. bucketUpdates[:],
  1274. ))
  1275. }
  1276. // GetAllBucketUpdates retrieves all the bucket updates
  1277. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1278. var bucketUpdates []*common.BucketUpdate
  1279. err := meddler.QueryAll(
  1280. hdb.db, &bucketUpdates,
  1281. `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
  1282. FROM bucket_update ORDER BY item_id;`,
  1283. )
  1284. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1285. }
  1286. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1287. if len(tokenExchanges) == 0 {
  1288. return nil
  1289. }
  1290. return tracerr.Wrap(db.BulkInsert(
  1291. d,
  1292. `INSERT INTO token_exchange (
  1293. eth_block_num,
  1294. eth_addr,
  1295. value_usd
  1296. ) VALUES %s;`,
  1297. tokenExchanges[:],
  1298. ))
  1299. }
  1300. // GetAllTokenExchanges retrieves all the token exchanges
  1301. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1302. var tokenExchanges []*common.TokenExchange
  1303. err := meddler.QueryAll(
  1304. hdb.db, &tokenExchanges,
  1305. "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
  1306. )
  1307. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1308. }
  1309. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1310. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1311. if len(escapeHatchWithdrawals) == 0 {
  1312. return nil
  1313. }
  1314. return tracerr.Wrap(db.BulkInsert(
  1315. d,
  1316. `INSERT INTO escape_hatch_withdrawal (
  1317. eth_block_num,
  1318. who_addr,
  1319. to_addr,
  1320. token_addr,
  1321. amount
  1322. ) VALUES %s;`,
  1323. escapeHatchWithdrawals[:],
  1324. ))
  1325. }
  1326. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1327. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1328. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1329. err := meddler.QueryAll(
  1330. hdb.db, &escapeHatchWithdrawals,
  1331. "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
  1332. )
  1333. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1334. tracerr.Wrap(err)
  1335. }
  1336. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1337. // contract variables. This initial state is stored linked to block 0, which
  1338. // always exist in the DB and is used to store initialization data that always
  1339. // exist in the smart contracts.
  1340. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1341. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1342. txn, err := hdb.db.Beginx()
  1343. if err != nil {
  1344. return tracerr.Wrap(err)
  1345. }
  1346. defer func() {
  1347. if err != nil {
  1348. db.Rollback(txn)
  1349. }
  1350. }()
  1351. // Force EthBlockNum to be 0 because it's the block used to link data
  1352. // that belongs to the creation of the smart contracts
  1353. rollup.EthBlockNum = 0
  1354. auction.EthBlockNum = 0
  1355. wDelayer.EthBlockNum = 0
  1356. auction.DefaultSlotSetBidSlotNum = 0
  1357. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1358. return tracerr.Wrap(err)
  1359. }
  1360. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1361. return tracerr.Wrap(err)
  1362. }
  1363. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1364. return tracerr.Wrap(err)
  1365. }
  1366. return tracerr.Wrap(txn.Commit())
  1367. }
  1368. // setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
  1369. // of the given l1UserTxs (with an UPDATE)
  1370. func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
  1371. if len(txs) == 0 {
  1372. return nil
  1373. }
  1374. // Effective amounts are stored as success flags in the DB, with true value by default
  1375. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1376. // updated to become false
  1377. type txUpdate struct {
  1378. ID common.TxID `db:"id"`
  1379. AmountSuccess bool `db:"amount_success"`
  1380. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1381. }
  1382. txUpdates := []txUpdate{}
  1383. equal := func(a *big.Int, b *big.Int) bool {
  1384. return a.Cmp(b) == 0
  1385. }
  1386. for i := range txs {
  1387. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1388. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1389. if !amountSuccess || !depositAmountSuccess {
  1390. txUpdates = append(txUpdates, txUpdate{
  1391. ID: txs[i].TxID,
  1392. AmountSuccess: amountSuccess,
  1393. DepositAmountSuccess: depositAmountSuccess,
  1394. })
  1395. }
  1396. }
  1397. const query string = `
  1398. UPDATE tx SET
  1399. amount_success = tx_update.amount_success,
  1400. deposit_amount_success = tx_update.deposit_amount_success
  1401. FROM (VALUES
  1402. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
  1403. (:id, :amount_success, :deposit_amount_success)
  1404. ) as tx_update (id, amount_success, deposit_amount_success)
  1405. WHERE tx.id = tx_update.id;
  1406. `
  1407. if len(txUpdates) > 0 {
  1408. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1409. return tracerr.Wrap(err)
  1410. }
  1411. }
  1412. return nil
  1413. }
  1414. // AddBlockSCData stores all the information of a block retrieved by the
  1415. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1416. // the pagination system of the API/DB depends on this. Within blocks, all
  1417. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1418. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1419. txn, err := hdb.db.Beginx()
  1420. if err != nil {
  1421. return tracerr.Wrap(err)
  1422. }
  1423. defer func() {
  1424. if err != nil {
  1425. db.Rollback(txn)
  1426. }
  1427. }()
  1428. // Add block
  1429. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1430. return tracerr.Wrap(err)
  1431. }
  1432. // Add Coordinators
  1433. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1434. return tracerr.Wrap(err)
  1435. }
  1436. // Add Bids
  1437. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1438. return tracerr.Wrap(err)
  1439. }
  1440. // Add Tokens
  1441. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1442. return tracerr.Wrap(err)
  1443. }
  1444. // Prepare user L1 txs to be added.
  1445. // They must be added before the batch that will forge them (which can be in the same block)
  1446. // and after the account that will be sent to (also can be in the same block).
  1447. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1448. // the batch that forges those txs is inserted
  1449. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1450. for i := range blockData.Rollup.L1UserTxs {
  1451. batchThatForgesIsInTheBlock := false
  1452. for _, batch := range blockData.Rollup.Batches {
  1453. if batch.Batch.ForgeL1TxsNum != nil &&
  1454. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1455. // Tx is forged in this block. It's guaranteed that:
  1456. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1457. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1458. batchThatForgesIsInTheBlock = true
  1459. addAtBatchNum := batch.Batch.BatchNum - 1
  1460. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1461. break
  1462. }
  1463. }
  1464. if !batchThatForgesIsInTheBlock {
  1465. // User artificial batchNum 0 to add txs that are not forge in this block
  1466. // after all the accounts of the block have been added
  1467. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1468. }
  1469. }
  1470. // Add Batches
  1471. for i := range blockData.Rollup.Batches {
  1472. batch := &blockData.Rollup.Batches[i]
  1473. // Add Batch: this will trigger an update on the DB
  1474. // that will set the batch num of forged L1 txs in this batch
  1475. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1476. return tracerr.Wrap(err)
  1477. }
  1478. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1479. // L1UserTxs that have been forged in this batch
  1480. if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
  1481. return tracerr.Wrap(err)
  1482. }
  1483. // Add accounts
  1484. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1485. return tracerr.Wrap(err)
  1486. }
  1487. // Add forged l1 coordinator Txs
  1488. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1489. return tracerr.Wrap(err)
  1490. }
  1491. // Add l2 Txs
  1492. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1493. return tracerr.Wrap(err)
  1494. }
  1495. // Add user L1 txs that will be forged in next batch
  1496. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1497. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1498. return tracerr.Wrap(err)
  1499. }
  1500. }
  1501. // Add exit tree
  1502. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1503. return tracerr.Wrap(err)
  1504. }
  1505. }
  1506. // Add user L1 txs that won't be forged in this block
  1507. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1508. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1509. return tracerr.Wrap(err)
  1510. }
  1511. }
  1512. // Set SC Vars if there was an update
  1513. if blockData.Rollup.Vars != nil {
  1514. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1515. return tracerr.Wrap(err)
  1516. }
  1517. }
  1518. if blockData.Auction.Vars != nil {
  1519. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1520. return tracerr.Wrap(err)
  1521. }
  1522. }
  1523. if blockData.WDelayer.Vars != nil {
  1524. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1525. return tracerr.Wrap(err)
  1526. }
  1527. }
  1528. // Update withdrawals in exit tree table
  1529. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1530. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1531. return tracerr.Wrap(err)
  1532. }
  1533. // Add Escape Hatch Withdrawals
  1534. if err := hdb.addEscapeHatchWithdrawals(txn,
  1535. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1536. return tracerr.Wrap(err)
  1537. }
  1538. // Add Buckets withdrawals updates
  1539. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1540. return tracerr.Wrap(err)
  1541. }
  1542. // Add Token exchange updates
  1543. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1544. return tracerr.Wrap(err)
  1545. }
  1546. return tracerr.Wrap(txn.Commit())
  1547. }
  1548. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1549. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1550. coordinator := &CoordinatorAPI{}
  1551. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1552. return coordinator, tracerr.Wrap(err)
  1553. }
  1554. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1555. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1556. bidderAddr, forgerAddr *ethCommon.Address,
  1557. fromItem, limit *uint, order string,
  1558. ) ([]CoordinatorAPI, uint64, error) {
  1559. var query string
  1560. var args []interface{}
  1561. queryStr := `SELECT coordinator.*,
  1562. COUNT(*) OVER() AS total_items
  1563. FROM coordinator `
  1564. // Apply filters
  1565. nextIsAnd := false
  1566. if bidderAddr != nil {
  1567. queryStr += "WHERE bidder_addr = ? "
  1568. nextIsAnd = true
  1569. args = append(args, bidderAddr)
  1570. }
  1571. if forgerAddr != nil {
  1572. if nextIsAnd {
  1573. queryStr += "AND "
  1574. } else {
  1575. queryStr += "WHERE "
  1576. }
  1577. queryStr += "forger_addr = ? "
  1578. nextIsAnd = true
  1579. args = append(args, forgerAddr)
  1580. }
  1581. if fromItem != nil {
  1582. if nextIsAnd {
  1583. queryStr += "AND "
  1584. } else {
  1585. queryStr += "WHERE "
  1586. }
  1587. if order == OrderAsc {
  1588. queryStr += "coordinator.item_id >= ? "
  1589. } else {
  1590. queryStr += "coordinator.item_id <= ? "
  1591. }
  1592. args = append(args, fromItem)
  1593. }
  1594. // pagination
  1595. queryStr += "ORDER BY coordinator.item_id "
  1596. if order == OrderAsc {
  1597. queryStr += " ASC "
  1598. } else {
  1599. queryStr += " DESC "
  1600. }
  1601. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1602. query = hdb.db.Rebind(queryStr)
  1603. coordinators := []*CoordinatorAPI{}
  1604. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1605. return nil, 0, tracerr.Wrap(err)
  1606. }
  1607. if len(coordinators) == 0 {
  1608. return []CoordinatorAPI{}, 0, nil
  1609. }
  1610. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1611. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1612. }
  1613. // AddAuctionVars insert auction vars into the DB
  1614. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1615. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1616. }
  1617. // GetAuctionVars returns auction variables
  1618. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1619. auctionVars := &common.AuctionVariables{}
  1620. err := meddler.QueryRow(
  1621. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1622. )
  1623. return auctionVars, tracerr.Wrap(err)
  1624. }
  1625. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1626. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1627. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1628. auctionVars := []*MinBidInfo{}
  1629. query := `
  1630. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1631. WHERE default_slot_set_bid_slot_num < $1
  1632. ORDER BY default_slot_set_bid_slot_num DESC
  1633. LIMIT $2;
  1634. `
  1635. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1636. if err != nil {
  1637. return nil, tracerr.Wrap(err)
  1638. }
  1639. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1640. }
  1641. // GetAccountAPI returns an account by its index
  1642. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1643. account := &AccountAPI{}
  1644. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1645. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1646. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1647. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1648. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1649. if err != nil {
  1650. return nil, tracerr.Wrap(err)
  1651. }
  1652. return account, nil
  1653. }
  1654. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1655. func (hdb *HistoryDB) GetAccountsAPI(
  1656. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1657. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1658. ) ([]AccountAPI, uint64, error) {
  1659. if ethAddr != nil && bjj != nil {
  1660. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1661. }
  1662. var query string
  1663. var args []interface{}
  1664. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1665. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1666. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1667. COUNT(*) OVER() AS total_items
  1668. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1669. // Apply filters
  1670. nextIsAnd := false
  1671. // ethAddr filter
  1672. if ethAddr != nil {
  1673. queryStr += "WHERE account.eth_addr = ? "
  1674. nextIsAnd = true
  1675. args = append(args, ethAddr)
  1676. } else if bjj != nil { // bjj filter
  1677. queryStr += "WHERE account.bjj = ? "
  1678. nextIsAnd = true
  1679. args = append(args, bjj)
  1680. }
  1681. // tokenID filter
  1682. if len(tokenIDs) > 0 {
  1683. if nextIsAnd {
  1684. queryStr += "AND "
  1685. } else {
  1686. queryStr += "WHERE "
  1687. }
  1688. queryStr += "account.token_id IN (?) "
  1689. args = append(args, tokenIDs)
  1690. nextIsAnd = true
  1691. }
  1692. if fromItem != nil {
  1693. if nextIsAnd {
  1694. queryStr += "AND "
  1695. } else {
  1696. queryStr += "WHERE "
  1697. }
  1698. if order == OrderAsc {
  1699. queryStr += "account.item_id >= ? "
  1700. } else {
  1701. queryStr += "account.item_id <= ? "
  1702. }
  1703. args = append(args, fromItem)
  1704. }
  1705. // pagination
  1706. queryStr += "ORDER BY account.item_id "
  1707. if order == OrderAsc {
  1708. queryStr += " ASC "
  1709. } else {
  1710. queryStr += " DESC "
  1711. }
  1712. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1713. query, argsQ, err := sqlx.In(queryStr, args...)
  1714. if err != nil {
  1715. return nil, 0, tracerr.Wrap(err)
  1716. }
  1717. query = hdb.db.Rebind(query)
  1718. accounts := []*AccountAPI{}
  1719. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1720. return nil, 0, tracerr.Wrap(err)
  1721. }
  1722. if len(accounts) == 0 {
  1723. return []AccountAPI{}, 0, nil
  1724. }
  1725. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1726. accounts[0].TotalItems - uint64(len(accounts)), nil
  1727. }
  1728. // GetMetrics returns metrics
  1729. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1730. metricsTotals := &MetricsTotals{}
  1731. metrics := &Metrics{}
  1732. err := meddler.QueryRow(
  1733. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1734. COALESCE (MIN(tx.batch_num), 0) as batch_num, COALESCE (MIN(block.timestamp),
  1735. NOW()) AS min_timestamp, COALESCE (MAX(block.timestamp), NOW()) AS max_timestamp
  1736. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1737. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1738. if err != nil {
  1739. return nil, tracerr.Wrap(err)
  1740. }
  1741. seconds := metricsTotals.MaxTimestamp.Sub(metricsTotals.MinTimestamp).Seconds()
  1742. // Avoid dividing by 0
  1743. if seconds == 0 {
  1744. seconds++
  1745. }
  1746. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions) / seconds
  1747. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1748. metrics.TransactionsPerBatch = float64(metricsTotals.TotalTransactions) /
  1749. float64(lastBatchNum-metricsTotals.FirstBatchNum+1)
  1750. } else {
  1751. metrics.TransactionsPerBatch = float64(0)
  1752. }
  1753. err = meddler.QueryRow(
  1754. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1755. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1756. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1757. if err != nil {
  1758. return nil, tracerr.Wrap(err)
  1759. }
  1760. if metricsTotals.TotalBatches > 0 {
  1761. metrics.BatchFrequency = seconds / float64(metricsTotals.TotalBatches)
  1762. } else {
  1763. metrics.BatchFrequency = 0
  1764. }
  1765. if metricsTotals.TotalTransactions > 0 {
  1766. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1767. } else {
  1768. metrics.AvgTransactionFee = 0
  1769. }
  1770. err = meddler.QueryRow(
  1771. hdb.db, metrics,
  1772. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1773. if err != nil {
  1774. return nil, tracerr.Wrap(err)
  1775. }
  1776. return metrics, nil
  1777. }
  1778. // GetAvgTxFee returns average transaction fee of the last 1h
  1779. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1780. metricsTotals := &MetricsTotals{}
  1781. err := meddler.QueryRow(
  1782. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1783. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1784. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1785. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1786. if err != nil {
  1787. return 0, tracerr.Wrap(err)
  1788. }
  1789. err = meddler.QueryRow(
  1790. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1791. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1792. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1793. if err != nil {
  1794. return 0, tracerr.Wrap(err)
  1795. }
  1796. var avgTransactionFee float64
  1797. if metricsTotals.TotalTransactions > 0 {
  1798. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1799. } else {
  1800. avgTransactionFee = 0
  1801. }
  1802. return avgTransactionFee, nil
  1803. }