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.

1941 lines
61 KiB

Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package historydb
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "math/big"
  7. "strings"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/db"
  11. "github.com/hermeznetwork/tracerr"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. "github.com/jmoiron/sqlx"
  14. //nolint:errcheck // driver for postgres DB
  15. _ "github.com/lib/pq"
  16. "github.com/russross/meddler"
  17. )
  18. const (
  19. // OrderAsc indicates ascending order when using pagination
  20. OrderAsc = "ASC"
  21. // OrderDesc indicates descending order when using pagination
  22. OrderDesc = "DESC"
  23. )
  24. // TODO(Edu): Document here how HistoryDB is kept consistent
  25. // HistoryDB persist the historic of the rollup
  26. type HistoryDB struct {
  27. db *sqlx.DB
  28. }
  29. // NewHistoryDB initialize the DB
  30. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  31. return &HistoryDB{db: db}
  32. }
  33. // DB returns a pointer to the L2DB.db. This method should be used only for
  34. // internal testing purposes.
  35. func (hdb *HistoryDB) DB() *sqlx.DB {
  36. return hdb.db
  37. }
  38. // AddBlock insert a block into the DB
  39. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  40. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  41. return tracerr.Wrap(meddler.Insert(d, "block", block))
  42. }
  43. // AddBlocks inserts blocks into the DB
  44. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  45. return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
  46. }
  47. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  48. return tracerr.Wrap(db.BulkInsert(
  49. d,
  50. `INSERT INTO block (
  51. eth_block_num,
  52. timestamp,
  53. hash
  54. ) VALUES %s;`,
  55. blocks[:],
  56. ))
  57. }
  58. // GetBlock retrieve a block from the DB, given a block number
  59. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  60. block := &common.Block{}
  61. err := meddler.QueryRow(
  62. hdb.db, block,
  63. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  64. )
  65. return block, tracerr.Wrap(err)
  66. }
  67. // GetAllBlocks retrieve all blocks from the DB
  68. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  69. var blocks []*common.Block
  70. err := meddler.QueryAll(
  71. hdb.db, &blocks,
  72. "SELECT * FROM block ORDER BY eth_block_num;",
  73. )
  74. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  75. }
  76. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  77. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  78. var blocks []*common.Block
  79. err := meddler.QueryAll(
  80. hdb.db, &blocks,
  81. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
  82. from, to,
  83. )
  84. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  85. }
  86. // GetLastBlock retrieve the block with the highest block number from the DB
  87. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  88. block := &common.Block{}
  89. err := meddler.QueryRow(
  90. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  91. )
  92. return block, tracerr.Wrap(err)
  93. }
  94. // AddBatch insert a Batch into the DB
  95. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  96. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  97. // Calculate total collected fees in USD
  98. // Get IDs of collected tokens for fees
  99. tokenIDs := []common.TokenID{}
  100. for id := range batch.CollectedFees {
  101. tokenIDs = append(tokenIDs, id)
  102. }
  103. // Get USD value of the tokens
  104. type tokenPrice struct {
  105. ID common.TokenID `meddler:"token_id"`
  106. USD *float64 `meddler:"usd"`
  107. Decimals int `meddler:"decimals"`
  108. }
  109. var tokenPrices []*tokenPrice
  110. if len(tokenIDs) > 0 {
  111. query, args, err := sqlx.In(
  112. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
  113. tokenIDs,
  114. )
  115. if err != nil {
  116. return tracerr.Wrap(err)
  117. }
  118. query = hdb.db.Rebind(query)
  119. if err := meddler.QueryAll(
  120. hdb.db, &tokenPrices, query, args...,
  121. ); err != nil {
  122. return tracerr.Wrap(err)
  123. }
  124. }
  125. // Calculate total collected
  126. var total float64
  127. for _, tokenPrice := range tokenPrices {
  128. if tokenPrice.USD == nil {
  129. continue
  130. }
  131. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  132. amount, _ := f.Float64()
  133. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  134. }
  135. batch.TotalFeesUSD = &total
  136. // Insert to DB
  137. return tracerr.Wrap(meddler.Insert(d, "batch", batch))
  138. }
  139. // AddBatches insert Bids into the DB
  140. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  141. return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
  142. }
  143. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  144. for i := 0; i < len(batches); i++ {
  145. if err := hdb.addBatch(d, &batches[i]); err != nil {
  146. return tracerr.Wrap(err)
  147. }
  148. }
  149. return nil
  150. }
  151. // GetBatchAPI return the batch with the given batchNum
  152. func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
  153. batch := &BatchAPI{}
  154. return batch, tracerr.Wrap(meddler.QueryRow(
  155. hdb.db, batch,
  156. `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
  157. batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
  158. batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
  159. block.timestamp, block.hash,
  160. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs
  161. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
  162. WHERE batch_num = $1;`, batchNum,
  163. ))
  164. }
  165. // GetBatchesAPI return the batches applying the given filters
  166. func (hdb *HistoryDB) GetBatchesAPI(
  167. minBatchNum, maxBatchNum, slotNum *uint,
  168. forgerAddr *ethCommon.Address,
  169. fromItem, limit *uint, order string,
  170. ) ([]BatchAPI, uint64, error) {
  171. var query string
  172. var args []interface{}
  173. queryStr := `SELECT batch.item_id, batch.batch_num, batch.eth_block_num,
  174. batch.forger_addr, batch.fees_collected, batch.total_fees_usd, batch.state_root,
  175. batch.num_accounts, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num,
  176. block.timestamp, block.hash,
  177. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs,
  178. count(*) OVER() AS total_items
  179. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
  180. // Apply filters
  181. nextIsAnd := false
  182. // minBatchNum filter
  183. if minBatchNum != nil {
  184. if nextIsAnd {
  185. queryStr += "AND "
  186. } else {
  187. queryStr += "WHERE "
  188. }
  189. queryStr += "batch.batch_num > ? "
  190. args = append(args, minBatchNum)
  191. nextIsAnd = true
  192. }
  193. // maxBatchNum filter
  194. if maxBatchNum != nil {
  195. if nextIsAnd {
  196. queryStr += "AND "
  197. } else {
  198. queryStr += "WHERE "
  199. }
  200. queryStr += "batch.batch_num < ? "
  201. args = append(args, maxBatchNum)
  202. nextIsAnd = true
  203. }
  204. // slotNum filter
  205. if slotNum != nil {
  206. if nextIsAnd {
  207. queryStr += "AND "
  208. } else {
  209. queryStr += "WHERE "
  210. }
  211. queryStr += "batch.slot_num = ? "
  212. args = append(args, slotNum)
  213. nextIsAnd = true
  214. }
  215. // forgerAddr filter
  216. if forgerAddr != nil {
  217. if nextIsAnd {
  218. queryStr += "AND "
  219. } else {
  220. queryStr += "WHERE "
  221. }
  222. queryStr += "batch.forger_addr = ? "
  223. args = append(args, forgerAddr)
  224. nextIsAnd = true
  225. }
  226. // pagination
  227. if fromItem != nil {
  228. if nextIsAnd {
  229. queryStr += "AND "
  230. } else {
  231. queryStr += "WHERE "
  232. }
  233. if order == OrderAsc {
  234. queryStr += "batch.item_id >= ? "
  235. } else {
  236. queryStr += "batch.item_id <= ? "
  237. }
  238. args = append(args, fromItem)
  239. }
  240. queryStr += "ORDER BY batch.item_id "
  241. if order == OrderAsc {
  242. queryStr += " ASC "
  243. } else {
  244. queryStr += " DESC "
  245. }
  246. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  247. query = hdb.db.Rebind(queryStr)
  248. // log.Debug(query)
  249. batchPtrs := []*BatchAPI{}
  250. if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
  251. return nil, 0, tracerr.Wrap(err)
  252. }
  253. batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
  254. if len(batches) == 0 {
  255. return batches, 0, nil
  256. }
  257. return batches, batches[0].TotalItems - uint64(len(batches)), nil
  258. }
  259. // GetAllBatches retrieve all batches from the DB
  260. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  261. var batches []*common.Batch
  262. err := meddler.QueryAll(
  263. hdb.db, &batches,
  264. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  265. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  266. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
  267. ORDER BY item_id;`,
  268. )
  269. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  270. }
  271. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  272. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  273. var batches []*common.Batch
  274. err := meddler.QueryAll(
  275. hdb.db, &batches,
  276. `SELECT batch_num, eth_block_num, forger_addr, fees_collected, fee_idxs_coordinator,
  277. state_root, num_accounts, last_idx, exit_root, forge_l1_txs_num, slot_num, total_fees_usd
  278. FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;`,
  279. from, to,
  280. )
  281. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  282. }
  283. // GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
  284. // batch within a slot
  285. func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
  286. row := hdb.db.QueryRow(
  287. `SELECT eth_block_num FROM batch
  288. WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
  289. )
  290. var blockNum int64
  291. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  292. }
  293. // GetLastBatchNum returns the BatchNum of the latest forged batch
  294. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  295. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  296. var batchNum common.BatchNum
  297. return batchNum, tracerr.Wrap(row.Scan(&batchNum))
  298. }
  299. // GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
  300. func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
  301. row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
  302. WHERE forge_l1_txs_num IS NOT NULL
  303. ORDER BY batch_num DESC LIMIT 1;`)
  304. var blockNum int64
  305. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  306. }
  307. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  308. // batches. If there's no batch in the DB (nil, nil) is returned.
  309. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  310. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  311. lastL1TxsNum := new(int64)
  312. return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
  313. }
  314. // Reorg deletes all the information that was added into the DB after the
  315. // lastValidBlock. If lastValidBlock is negative, all block information is
  316. // deleted.
  317. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  318. var err error
  319. if lastValidBlock < 0 {
  320. _, err = hdb.db.Exec("DELETE FROM block;")
  321. } else {
  322. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  323. }
  324. return tracerr.Wrap(err)
  325. }
  326. // AddBids insert Bids into the DB
  327. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  328. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  329. if len(bids) == 0 {
  330. return nil
  331. }
  332. // TODO: check the coordinator info
  333. return tracerr.Wrap(db.BulkInsert(
  334. d,
  335. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  336. bids[:],
  337. ))
  338. }
  339. // GetAllBids retrieve all bids from the DB
  340. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  341. var bids []*common.Bid
  342. err := meddler.QueryAll(
  343. hdb.db, &bids,
  344. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
  345. ORDER BY item_id;`,
  346. )
  347. return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
  348. }
  349. // GetBestBidAPI returns the best bid in specific slot by slotNum
  350. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  351. bid := &BidAPI{}
  352. err := meddler.QueryRow(
  353. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  354. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  355. INNER JOIN 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. // AddBucketUpdatesTest allows call to unexported method
  1277. // only for internal testing purposes
  1278. func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1279. return hdb.addBucketUpdates(d, bucketUpdates)
  1280. }
  1281. // GetAllBucketUpdates retrieves all the bucket updates
  1282. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1283. var bucketUpdates []*common.BucketUpdate
  1284. err := meddler.QueryAll(
  1285. hdb.db, &bucketUpdates,
  1286. `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
  1287. FROM bucket_update ORDER BY item_id;`,
  1288. )
  1289. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1290. }
  1291. // GetBucketUpdates retrieves latest values for each bucket
  1292. func (hdb *HistoryDB) GetBucketUpdates() ([]common.BucketUpdate, error) {
  1293. var bucketUpdates []*common.BucketUpdate
  1294. err := meddler.QueryAll(
  1295. hdb.db, &bucketUpdates,
  1296. `SELECT num_bucket, withdrawals FROM bucket_update
  1297. WHERE item_id in(SELECT max(item_id) FROM bucket_update
  1298. group by num_bucket)
  1299. ORDER BY num_bucket ASC;`,
  1300. )
  1301. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1302. }
  1303. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1304. if len(tokenExchanges) == 0 {
  1305. return nil
  1306. }
  1307. return tracerr.Wrap(db.BulkInsert(
  1308. d,
  1309. `INSERT INTO token_exchange (
  1310. eth_block_num,
  1311. eth_addr,
  1312. value_usd
  1313. ) VALUES %s;`,
  1314. tokenExchanges[:],
  1315. ))
  1316. }
  1317. // GetAllTokenExchanges retrieves all the token exchanges
  1318. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1319. var tokenExchanges []*common.TokenExchange
  1320. err := meddler.QueryAll(
  1321. hdb.db, &tokenExchanges,
  1322. "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
  1323. )
  1324. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1325. }
  1326. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1327. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1328. if len(escapeHatchWithdrawals) == 0 {
  1329. return nil
  1330. }
  1331. return tracerr.Wrap(db.BulkInsert(
  1332. d,
  1333. `INSERT INTO escape_hatch_withdrawal (
  1334. eth_block_num,
  1335. who_addr,
  1336. to_addr,
  1337. token_addr,
  1338. amount
  1339. ) VALUES %s;`,
  1340. escapeHatchWithdrawals[:],
  1341. ))
  1342. }
  1343. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1344. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1345. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1346. err := meddler.QueryAll(
  1347. hdb.db, &escapeHatchWithdrawals,
  1348. "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
  1349. )
  1350. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1351. tracerr.Wrap(err)
  1352. }
  1353. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1354. // contract variables. This initial state is stored linked to block 0, which
  1355. // always exist in the DB and is used to store initialization data that always
  1356. // exist in the smart contracts.
  1357. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1358. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1359. txn, err := hdb.db.Beginx()
  1360. if err != nil {
  1361. return tracerr.Wrap(err)
  1362. }
  1363. defer func() {
  1364. if err != nil {
  1365. db.Rollback(txn)
  1366. }
  1367. }()
  1368. // Force EthBlockNum to be 0 because it's the block used to link data
  1369. // that belongs to the creation of the smart contracts
  1370. rollup.EthBlockNum = 0
  1371. auction.EthBlockNum = 0
  1372. wDelayer.EthBlockNum = 0
  1373. auction.DefaultSlotSetBidSlotNum = 0
  1374. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1375. return tracerr.Wrap(err)
  1376. }
  1377. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1378. return tracerr.Wrap(err)
  1379. }
  1380. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1381. return tracerr.Wrap(err)
  1382. }
  1383. return tracerr.Wrap(txn.Commit())
  1384. }
  1385. // setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
  1386. // of the given l1UserTxs (with an UPDATE)
  1387. func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
  1388. if len(txs) == 0 {
  1389. return nil
  1390. }
  1391. // Effective amounts are stored as success flags in the DB, with true value by default
  1392. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1393. // updated to become false
  1394. type txUpdate struct {
  1395. ID common.TxID `db:"id"`
  1396. AmountSuccess bool `db:"amount_success"`
  1397. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1398. }
  1399. txUpdates := []txUpdate{}
  1400. equal := func(a *big.Int, b *big.Int) bool {
  1401. return a.Cmp(b) == 0
  1402. }
  1403. for i := range txs {
  1404. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1405. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1406. if !amountSuccess || !depositAmountSuccess {
  1407. txUpdates = append(txUpdates, txUpdate{
  1408. ID: txs[i].TxID,
  1409. AmountSuccess: amountSuccess,
  1410. DepositAmountSuccess: depositAmountSuccess,
  1411. })
  1412. }
  1413. }
  1414. const query string = `
  1415. UPDATE tx SET
  1416. amount_success = tx_update.amount_success,
  1417. deposit_amount_success = tx_update.deposit_amount_success
  1418. FROM (VALUES
  1419. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
  1420. (:id, :amount_success, :deposit_amount_success)
  1421. ) as tx_update (id, amount_success, deposit_amount_success)
  1422. WHERE tx.id = tx_update.id;
  1423. `
  1424. if len(txUpdates) > 0 {
  1425. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1426. return tracerr.Wrap(err)
  1427. }
  1428. }
  1429. return nil
  1430. }
  1431. // AddBlockSCData stores all the information of a block retrieved by the
  1432. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1433. // the pagination system of the API/DB depends on this. Within blocks, all
  1434. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1435. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1436. txn, err := hdb.db.Beginx()
  1437. if err != nil {
  1438. return tracerr.Wrap(err)
  1439. }
  1440. defer func() {
  1441. if err != nil {
  1442. db.Rollback(txn)
  1443. }
  1444. }()
  1445. // Add block
  1446. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1447. return tracerr.Wrap(err)
  1448. }
  1449. // Add Coordinators
  1450. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1451. return tracerr.Wrap(err)
  1452. }
  1453. // Add Bids
  1454. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1455. return tracerr.Wrap(err)
  1456. }
  1457. // Add Tokens
  1458. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1459. return tracerr.Wrap(err)
  1460. }
  1461. // Prepare user L1 txs to be added.
  1462. // They must be added before the batch that will forge them (which can be in the same block)
  1463. // and after the account that will be sent to (also can be in the same block).
  1464. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1465. // the batch that forges those txs is inserted
  1466. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1467. for i := range blockData.Rollup.L1UserTxs {
  1468. batchThatForgesIsInTheBlock := false
  1469. for _, batch := range blockData.Rollup.Batches {
  1470. if batch.Batch.ForgeL1TxsNum != nil &&
  1471. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1472. // Tx is forged in this block. It's guaranteed that:
  1473. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1474. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1475. batchThatForgesIsInTheBlock = true
  1476. addAtBatchNum := batch.Batch.BatchNum - 1
  1477. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1478. break
  1479. }
  1480. }
  1481. if !batchThatForgesIsInTheBlock {
  1482. // User artificial batchNum 0 to add txs that are not forge in this block
  1483. // after all the accounts of the block have been added
  1484. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1485. }
  1486. }
  1487. // Add Batches
  1488. for i := range blockData.Rollup.Batches {
  1489. batch := &blockData.Rollup.Batches[i]
  1490. // Add Batch: this will trigger an update on the DB
  1491. // that will set the batch num of forged L1 txs in this batch
  1492. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1493. return tracerr.Wrap(err)
  1494. }
  1495. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1496. // L1UserTxs that have been forged in this batch
  1497. if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
  1498. return tracerr.Wrap(err)
  1499. }
  1500. // Add accounts
  1501. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1502. return tracerr.Wrap(err)
  1503. }
  1504. // Add forged l1 coordinator Txs
  1505. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1506. return tracerr.Wrap(err)
  1507. }
  1508. // Add l2 Txs
  1509. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1510. return tracerr.Wrap(err)
  1511. }
  1512. // Add user L1 txs that will be forged in next batch
  1513. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1514. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1515. return tracerr.Wrap(err)
  1516. }
  1517. }
  1518. // Add exit tree
  1519. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1520. return tracerr.Wrap(err)
  1521. }
  1522. }
  1523. // Add user L1 txs that won't be forged in this block
  1524. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1525. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1526. return tracerr.Wrap(err)
  1527. }
  1528. }
  1529. // Set SC Vars if there was an update
  1530. if blockData.Rollup.Vars != nil {
  1531. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1532. return tracerr.Wrap(err)
  1533. }
  1534. }
  1535. if blockData.Auction.Vars != nil {
  1536. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1537. return tracerr.Wrap(err)
  1538. }
  1539. }
  1540. if blockData.WDelayer.Vars != nil {
  1541. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1542. return tracerr.Wrap(err)
  1543. }
  1544. }
  1545. // Update withdrawals in exit tree table
  1546. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1547. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1548. return tracerr.Wrap(err)
  1549. }
  1550. // Add Escape Hatch Withdrawals
  1551. if err := hdb.addEscapeHatchWithdrawals(txn,
  1552. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1553. return tracerr.Wrap(err)
  1554. }
  1555. // Add Buckets withdrawals updates
  1556. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1557. return tracerr.Wrap(err)
  1558. }
  1559. // Add Token exchange updates
  1560. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1561. return tracerr.Wrap(err)
  1562. }
  1563. return tracerr.Wrap(txn.Commit())
  1564. }
  1565. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1566. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1567. coordinator := &CoordinatorAPI{}
  1568. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1569. return coordinator, tracerr.Wrap(err)
  1570. }
  1571. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1572. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1573. bidderAddr, forgerAddr *ethCommon.Address,
  1574. fromItem, limit *uint, order string,
  1575. ) ([]CoordinatorAPI, uint64, error) {
  1576. var query string
  1577. var args []interface{}
  1578. queryStr := `SELECT coordinator.*,
  1579. COUNT(*) OVER() AS total_items
  1580. FROM coordinator `
  1581. // Apply filters
  1582. nextIsAnd := false
  1583. if bidderAddr != nil {
  1584. queryStr += "WHERE bidder_addr = ? "
  1585. nextIsAnd = true
  1586. args = append(args, bidderAddr)
  1587. }
  1588. if forgerAddr != nil {
  1589. if nextIsAnd {
  1590. queryStr += "AND "
  1591. } else {
  1592. queryStr += "WHERE "
  1593. }
  1594. queryStr += "forger_addr = ? "
  1595. nextIsAnd = true
  1596. args = append(args, forgerAddr)
  1597. }
  1598. if fromItem != nil {
  1599. if nextIsAnd {
  1600. queryStr += "AND "
  1601. } else {
  1602. queryStr += "WHERE "
  1603. }
  1604. if order == OrderAsc {
  1605. queryStr += "coordinator.item_id >= ? "
  1606. } else {
  1607. queryStr += "coordinator.item_id <= ? "
  1608. }
  1609. args = append(args, fromItem)
  1610. }
  1611. // pagination
  1612. queryStr += "ORDER BY coordinator.item_id "
  1613. if order == OrderAsc {
  1614. queryStr += " ASC "
  1615. } else {
  1616. queryStr += " DESC "
  1617. }
  1618. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1619. query = hdb.db.Rebind(queryStr)
  1620. coordinators := []*CoordinatorAPI{}
  1621. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1622. return nil, 0, tracerr.Wrap(err)
  1623. }
  1624. if len(coordinators) == 0 {
  1625. return []CoordinatorAPI{}, 0, nil
  1626. }
  1627. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1628. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1629. }
  1630. // AddAuctionVars insert auction vars into the DB
  1631. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1632. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1633. }
  1634. // GetAuctionVars returns auction variables
  1635. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1636. auctionVars := &common.AuctionVariables{}
  1637. err := meddler.QueryRow(
  1638. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1639. )
  1640. return auctionVars, tracerr.Wrap(err)
  1641. }
  1642. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1643. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1644. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1645. auctionVars := []*MinBidInfo{}
  1646. query := `
  1647. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1648. WHERE default_slot_set_bid_slot_num < $1
  1649. ORDER BY default_slot_set_bid_slot_num DESC
  1650. LIMIT $2;
  1651. `
  1652. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1653. if err != nil {
  1654. return nil, tracerr.Wrap(err)
  1655. }
  1656. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1657. }
  1658. // GetAccountAPI returns an account by its index
  1659. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1660. account := &AccountAPI{}
  1661. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1662. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1663. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1664. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1665. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1666. if err != nil {
  1667. return nil, tracerr.Wrap(err)
  1668. }
  1669. return account, nil
  1670. }
  1671. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1672. func (hdb *HistoryDB) GetAccountsAPI(
  1673. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1674. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1675. ) ([]AccountAPI, uint64, error) {
  1676. if ethAddr != nil && bjj != nil {
  1677. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1678. }
  1679. var query string
  1680. var args []interface{}
  1681. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1682. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1683. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1684. COUNT(*) OVER() AS total_items
  1685. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1686. // Apply filters
  1687. nextIsAnd := false
  1688. // ethAddr filter
  1689. if ethAddr != nil {
  1690. queryStr += "WHERE account.eth_addr = ? "
  1691. nextIsAnd = true
  1692. args = append(args, ethAddr)
  1693. } else if bjj != nil { // bjj filter
  1694. queryStr += "WHERE account.bjj = ? "
  1695. nextIsAnd = true
  1696. args = append(args, bjj)
  1697. }
  1698. // tokenID filter
  1699. if len(tokenIDs) > 0 {
  1700. if nextIsAnd {
  1701. queryStr += "AND "
  1702. } else {
  1703. queryStr += "WHERE "
  1704. }
  1705. queryStr += "account.token_id IN (?) "
  1706. args = append(args, tokenIDs)
  1707. nextIsAnd = true
  1708. }
  1709. if fromItem != nil {
  1710. if nextIsAnd {
  1711. queryStr += "AND "
  1712. } else {
  1713. queryStr += "WHERE "
  1714. }
  1715. if order == OrderAsc {
  1716. queryStr += "account.item_id >= ? "
  1717. } else {
  1718. queryStr += "account.item_id <= ? "
  1719. }
  1720. args = append(args, fromItem)
  1721. }
  1722. // pagination
  1723. queryStr += "ORDER BY account.item_id "
  1724. if order == OrderAsc {
  1725. queryStr += " ASC "
  1726. } else {
  1727. queryStr += " DESC "
  1728. }
  1729. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1730. query, argsQ, err := sqlx.In(queryStr, args...)
  1731. if err != nil {
  1732. return nil, 0, tracerr.Wrap(err)
  1733. }
  1734. query = hdb.db.Rebind(query)
  1735. accounts := []*AccountAPI{}
  1736. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1737. return nil, 0, tracerr.Wrap(err)
  1738. }
  1739. if len(accounts) == 0 {
  1740. return []AccountAPI{}, 0, nil
  1741. }
  1742. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1743. accounts[0].TotalItems - uint64(len(accounts)), nil
  1744. }
  1745. // GetMetrics returns metrics
  1746. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1747. metricsTotals := &MetricsTotals{}
  1748. metrics := &Metrics{}
  1749. err := meddler.QueryRow(
  1750. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1751. COALESCE (MIN(tx.batch_num), 0) as batch_num, COALESCE (MIN(block.timestamp),
  1752. NOW()) AS min_timestamp, COALESCE (MAX(block.timestamp), NOW()) AS max_timestamp
  1753. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1754. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1755. if err != nil {
  1756. return nil, tracerr.Wrap(err)
  1757. }
  1758. seconds := metricsTotals.MaxTimestamp.Sub(metricsTotals.MinTimestamp).Seconds()
  1759. // Avoid dividing by 0
  1760. if seconds == 0 {
  1761. seconds++
  1762. }
  1763. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions) / seconds
  1764. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1765. metrics.TransactionsPerBatch = float64(metricsTotals.TotalTransactions) /
  1766. float64(lastBatchNum-metricsTotals.FirstBatchNum+1)
  1767. } else {
  1768. metrics.TransactionsPerBatch = float64(0)
  1769. }
  1770. err = meddler.QueryRow(
  1771. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1772. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1773. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1774. if err != nil {
  1775. return nil, tracerr.Wrap(err)
  1776. }
  1777. if metricsTotals.TotalBatches > 0 {
  1778. metrics.BatchFrequency = seconds / float64(metricsTotals.TotalBatches)
  1779. } else {
  1780. metrics.BatchFrequency = 0
  1781. }
  1782. if metricsTotals.TotalTransactions > 0 {
  1783. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1784. } else {
  1785. metrics.AvgTransactionFee = 0
  1786. }
  1787. err = meddler.QueryRow(
  1788. hdb.db, metrics,
  1789. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1790. if err != nil {
  1791. return nil, tracerr.Wrap(err)
  1792. }
  1793. return metrics, nil
  1794. }
  1795. // GetAvgTxFee returns average transaction fee of the last 1h
  1796. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1797. metricsTotals := &MetricsTotals{}
  1798. err := meddler.QueryRow(
  1799. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1800. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1801. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1802. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1803. if err != nil {
  1804. return 0, tracerr.Wrap(err)
  1805. }
  1806. err = meddler.QueryRow(
  1807. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1808. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1809. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1810. if err != nil {
  1811. return 0, tracerr.Wrap(err)
  1812. }
  1813. var avgTransactionFee float64
  1814. if metricsTotals.TotalTransactions > 0 {
  1815. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1816. } else {
  1817. avgTransactionFee = 0
  1818. }
  1819. return avgTransactionFee, nil
  1820. }