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.

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