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.

1965 lines
62 KiB

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