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.

1971 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].UserOrigin {
  807. if l1txs[i].Type != common.TxTypeCreateAccountDeposit &&
  808. l1txs[i].Type != common.TxTypeCreateAccountDepositTransfer {
  809. effectiveFromIdx = &l1txs[i].FromIdx
  810. }
  811. } else {
  812. effectiveFromIdx = &l1txs[i].EffectiveFromIdx
  813. }
  814. txs = append(txs, txWrite{
  815. // Generic
  816. IsL1: true,
  817. TxID: l1txs[i].TxID,
  818. Type: l1txs[i].Type,
  819. Position: l1txs[i].Position,
  820. FromIdx: &l1txs[i].FromIdx,
  821. EffectiveFromIdx: effectiveFromIdx,
  822. ToIdx: l1txs[i].ToIdx,
  823. Amount: l1txs[i].Amount,
  824. AmountFloat: amountFloat,
  825. TokenID: l1txs[i].TokenID,
  826. BatchNum: l1txs[i].BatchNum,
  827. EthBlockNum: l1txs[i].EthBlockNum,
  828. // L1
  829. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  830. UserOrigin: &l1txs[i].UserOrigin,
  831. FromEthAddr: &l1txs[i].FromEthAddr,
  832. FromBJJ: &l1txs[i].FromBJJ,
  833. DepositAmount: l1txs[i].DepositAmount,
  834. DepositAmountFloat: &depositAmountFloat,
  835. })
  836. }
  837. return tracerr.Wrap(hdb.addTxs(d, txs))
  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(l2txs []common.L2Tx) error {
  841. return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
  842. }
  843. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  844. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  845. txs := []txWrite{}
  846. for i := 0; i < len(l2txs); i++ {
  847. f := new(big.Float).SetInt(l2txs[i].Amount)
  848. amountFloat, _ := f.Float64()
  849. txs = append(txs, txWrite{
  850. // Generic
  851. IsL1: false,
  852. TxID: l2txs[i].TxID,
  853. Type: l2txs[i].Type,
  854. Position: l2txs[i].Position,
  855. FromIdx: &l2txs[i].FromIdx,
  856. EffectiveFromIdx: &l2txs[i].FromIdx,
  857. ToIdx: l2txs[i].ToIdx,
  858. TokenID: l2txs[i].TokenID,
  859. Amount: l2txs[i].Amount,
  860. AmountFloat: amountFloat,
  861. BatchNum: &l2txs[i].BatchNum,
  862. EthBlockNum: l2txs[i].EthBlockNum,
  863. // L2
  864. Fee: &l2txs[i].Fee,
  865. Nonce: &l2txs[i].Nonce,
  866. })
  867. }
  868. return tracerr.Wrap(hdb.addTxs(d, txs))
  869. }
  870. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  871. if len(txs) == 0 {
  872. return nil
  873. }
  874. return tracerr.Wrap(db.BulkInsert(
  875. d,
  876. `INSERT INTO tx (
  877. is_l1,
  878. id,
  879. type,
  880. position,
  881. from_idx,
  882. effective_from_idx,
  883. to_idx,
  884. amount,
  885. amount_f,
  886. token_id,
  887. batch_num,
  888. eth_block_num,
  889. to_forge_l1_txs_num,
  890. user_origin,
  891. from_eth_addr,
  892. from_bjj,
  893. deposit_amount,
  894. deposit_amount_f,
  895. fee,
  896. nonce
  897. ) VALUES %s;`,
  898. txs[:],
  899. ))
  900. }
  901. // GetHistoryTx returns a tx from the DB given a TxID
  902. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  903. // Warning: amount_success and deposit_amount_success have true as default for
  904. // performance reasons. The expected default value is false (when txs are unforged)
  905. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  906. tx := &TxAPI{}
  907. err := meddler.QueryRow(
  908. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  909. hez_idx(tx.effective_from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  910. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  911. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  912. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  913. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  914. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  915. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  916. token.usd_update, block.timestamp
  917. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  918. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  919. WHERE tx.id = $1;`, txID,
  920. )
  921. return tx, tracerr.Wrap(err)
  922. }
  923. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  924. // and pagination info
  925. func (hdb *HistoryDB) GetHistoryTxs(
  926. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
  927. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  928. fromItem, limit *uint, order string,
  929. ) ([]TxAPI, uint64, error) {
  930. // Warning: amount_success and deposit_amount_success have true as default for
  931. // performance reasons. The expected default value is false (when txs are unforged)
  932. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  933. if ethAddr != nil && bjj != nil {
  934. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  935. }
  936. var query string
  937. var args []interface{}
  938. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  939. hez_idx(tx.effective_from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  940. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  941. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  942. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  943. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  944. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  945. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  946. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  947. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  948. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  949. // Apply filters
  950. nextIsAnd := false
  951. // ethAddr filter
  952. if ethAddr != nil {
  953. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  954. nextIsAnd = true
  955. args = append(args, ethAddr, ethAddr)
  956. } else if bjj != nil { // bjj filter
  957. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  958. nextIsAnd = true
  959. args = append(args, bjj, bjj)
  960. }
  961. // tokenID filter
  962. if tokenID != nil {
  963. if nextIsAnd {
  964. queryStr += "AND "
  965. } else {
  966. queryStr += "WHERE "
  967. }
  968. queryStr += "tx.token_id = ? "
  969. args = append(args, tokenID)
  970. nextIsAnd = true
  971. }
  972. // idx filter
  973. if idx != nil {
  974. if nextIsAnd {
  975. queryStr += "AND "
  976. } else {
  977. queryStr += "WHERE "
  978. }
  979. queryStr += "(tx.effective_from_idx = ? OR tx.to_idx = ?) "
  980. args = append(args, idx, idx)
  981. nextIsAnd = true
  982. }
  983. // batchNum filter
  984. if batchNum != nil {
  985. if nextIsAnd {
  986. queryStr += "AND "
  987. } else {
  988. queryStr += "WHERE "
  989. }
  990. queryStr += "tx.batch_num = ? "
  991. args = append(args, batchNum)
  992. nextIsAnd = true
  993. }
  994. // txType filter
  995. if txType != nil {
  996. if nextIsAnd {
  997. queryStr += "AND "
  998. } else {
  999. queryStr += "WHERE "
  1000. }
  1001. queryStr += "tx.type = ? "
  1002. args = append(args, txType)
  1003. nextIsAnd = true
  1004. }
  1005. if fromItem != nil {
  1006. if nextIsAnd {
  1007. queryStr += "AND "
  1008. } else {
  1009. queryStr += "WHERE "
  1010. }
  1011. if order == OrderAsc {
  1012. queryStr += "tx.item_id >= ? "
  1013. } else {
  1014. queryStr += "tx.item_id <= ? "
  1015. }
  1016. args = append(args, fromItem)
  1017. nextIsAnd = true
  1018. }
  1019. if nextIsAnd {
  1020. queryStr += "AND "
  1021. } else {
  1022. queryStr += "WHERE "
  1023. }
  1024. queryStr += "tx.batch_num IS NOT NULL "
  1025. // pagination
  1026. queryStr += "ORDER BY tx.item_id "
  1027. if order == OrderAsc {
  1028. queryStr += " ASC "
  1029. } else {
  1030. queryStr += " DESC "
  1031. }
  1032. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1033. query = hdb.db.Rebind(queryStr)
  1034. // log.Debug(query)
  1035. txsPtrs := []*TxAPI{}
  1036. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  1037. return nil, 0, tracerr.Wrap(err)
  1038. }
  1039. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  1040. if len(txs) == 0 {
  1041. return txs, 0, nil
  1042. }
  1043. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  1044. }
  1045. // GetAllExits returns all exit from the DB
  1046. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  1047. var exits []*common.ExitInfo
  1048. err := meddler.QueryAll(
  1049. hdb.db, &exits,
  1050. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  1051. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  1052. exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
  1053. )
  1054. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
  1055. }
  1056. // GetExitAPI returns a exit from the DB
  1057. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  1058. exit := &ExitAPI{}
  1059. err := meddler.QueryRow(
  1060. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  1061. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1062. account.bjj, account.eth_addr,
  1063. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1064. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1065. token.token_id, token.item_id AS token_item_id,
  1066. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1067. token.decimals, token.usd, token.usd_update
  1068. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1069. INNER JOIN token ON account.token_id = token.token_id
  1070. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  1071. )
  1072. return exit, tracerr.Wrap(err)
  1073. }
  1074. // GetExitsAPI returns a list of exits from the DB and pagination info
  1075. func (hdb *HistoryDB) GetExitsAPI(
  1076. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
  1077. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  1078. fromItem, limit *uint, order string,
  1079. ) ([]ExitAPI, uint64, error) {
  1080. if ethAddr != nil && bjj != nil {
  1081. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1082. }
  1083. var query string
  1084. var args []interface{}
  1085. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1086. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1087. account.bjj, account.eth_addr,
  1088. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1089. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1090. token.token_id, token.item_id AS token_item_id,
  1091. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1092. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1093. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1094. INNER JOIN token ON account.token_id = token.token_id `
  1095. // Apply filters
  1096. nextIsAnd := false
  1097. // ethAddr filter
  1098. if ethAddr != nil {
  1099. queryStr += "WHERE account.eth_addr = ? "
  1100. nextIsAnd = true
  1101. args = append(args, ethAddr)
  1102. } else if bjj != nil { // bjj filter
  1103. queryStr += "WHERE account.bjj = ? "
  1104. nextIsAnd = true
  1105. args = append(args, bjj)
  1106. }
  1107. // tokenID filter
  1108. if tokenID != nil {
  1109. if nextIsAnd {
  1110. queryStr += "AND "
  1111. } else {
  1112. queryStr += "WHERE "
  1113. }
  1114. queryStr += "account.token_id = ? "
  1115. args = append(args, tokenID)
  1116. nextIsAnd = true
  1117. }
  1118. // idx filter
  1119. if idx != nil {
  1120. if nextIsAnd {
  1121. queryStr += "AND "
  1122. } else {
  1123. queryStr += "WHERE "
  1124. }
  1125. queryStr += "exit_tree.account_idx = ? "
  1126. args = append(args, idx)
  1127. nextIsAnd = true
  1128. }
  1129. // batchNum filter
  1130. if batchNum != nil {
  1131. if nextIsAnd {
  1132. queryStr += "AND "
  1133. } else {
  1134. queryStr += "WHERE "
  1135. }
  1136. queryStr += "exit_tree.batch_num = ? "
  1137. args = append(args, batchNum)
  1138. nextIsAnd = true
  1139. }
  1140. // onlyPendingWithdraws
  1141. if onlyPendingWithdraws != nil {
  1142. if *onlyPendingWithdraws {
  1143. if nextIsAnd {
  1144. queryStr += "AND "
  1145. } else {
  1146. queryStr += "WHERE "
  1147. }
  1148. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1149. nextIsAnd = true
  1150. }
  1151. }
  1152. if fromItem != nil {
  1153. if nextIsAnd {
  1154. queryStr += "AND "
  1155. } else {
  1156. queryStr += "WHERE "
  1157. }
  1158. if order == OrderAsc {
  1159. queryStr += "exit_tree.item_id >= ? "
  1160. } else {
  1161. queryStr += "exit_tree.item_id <= ? "
  1162. }
  1163. args = append(args, fromItem)
  1164. // nextIsAnd = true
  1165. }
  1166. // pagination
  1167. queryStr += "ORDER BY exit_tree.item_id "
  1168. if order == OrderAsc {
  1169. queryStr += " ASC "
  1170. } else {
  1171. queryStr += " DESC "
  1172. }
  1173. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1174. query = hdb.db.Rebind(queryStr)
  1175. // log.Debug(query)
  1176. exits := []*ExitAPI{}
  1177. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1178. return nil, 0, tracerr.Wrap(err)
  1179. }
  1180. if len(exits) == 0 {
  1181. return []ExitAPI{}, 0, nil
  1182. }
  1183. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1184. }
  1185. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1186. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1187. var txs []*common.L1Tx
  1188. err := meddler.QueryAll(
  1189. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  1190. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1191. tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1192. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  1193. 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,
  1194. tx.eth_block_num, tx.type, tx.batch_num
  1195. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  1196. )
  1197. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1198. }
  1199. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1200. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1201. var txs []*common.L1Tx
  1202. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  1203. // that returned txs will always have effective amounts
  1204. err := meddler.QueryAll(
  1205. hdb.db, &txs,
  1206. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1207. tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1208. tx.amount, tx.amount AS effective_amount,
  1209. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  1210. tx.eth_block_num, tx.type, tx.batch_num
  1211. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  1212. )
  1213. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1214. }
  1215. // GetAllL2Txs returns all L2Txs from the DB
  1216. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1217. var txs []*common.L2Tx
  1218. err := meddler.QueryAll(
  1219. hdb.db, &txs,
  1220. `SELECT tx.id, tx.batch_num, tx.position,
  1221. tx.from_idx, tx.to_idx, tx.amount, tx.token_id,
  1222. tx.fee, tx.nonce, tx.type, tx.eth_block_num
  1223. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  1224. )
  1225. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  1226. }
  1227. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1228. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1229. var txs []*common.L1Tx
  1230. err := meddler.QueryAll(
  1231. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  1232. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1233. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1234. tx.amount, NULL AS effective_amount,
  1235. tx.deposit_amount, NULL AS effective_deposit_amount,
  1236. tx.eth_block_num, tx.type, tx.batch_num
  1237. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  1238. ORDER BY position;`,
  1239. toForgeL1TxsNum,
  1240. )
  1241. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1242. }
  1243. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1244. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1245. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1246. row := hdb.db.QueryRow(
  1247. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  1248. toForgeL1TxsNum,
  1249. )
  1250. var lastL1TxsPosition int
  1251. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  1252. }
  1253. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1254. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1255. *common.WDelayerVariables, error) {
  1256. var rollup common.RollupVariables
  1257. var auction common.AuctionVariables
  1258. var wDelayer common.WDelayerVariables
  1259. if err := meddler.QueryRow(hdb.db, &rollup,
  1260. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1261. return nil, nil, nil, tracerr.Wrap(err)
  1262. }
  1263. if err := meddler.QueryRow(hdb.db, &auction,
  1264. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1265. return nil, nil, nil, tracerr.Wrap(err)
  1266. }
  1267. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1268. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1269. return nil, nil, nil, tracerr.Wrap(err)
  1270. }
  1271. return &rollup, &auction, &wDelayer, nil
  1272. }
  1273. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1274. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  1275. }
  1276. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1277. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  1278. }
  1279. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1280. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  1281. }
  1282. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1283. if len(bucketUpdates) == 0 {
  1284. return nil
  1285. }
  1286. return tracerr.Wrap(db.BulkInsert(
  1287. d,
  1288. `INSERT INTO bucket_update (
  1289. eth_block_num,
  1290. num_bucket,
  1291. block_stamp,
  1292. withdrawals
  1293. ) VALUES %s;`,
  1294. bucketUpdates[:],
  1295. ))
  1296. }
  1297. // AddBucketUpdatesTest allows call to unexported method
  1298. // only for internal testing purposes
  1299. func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1300. return hdb.addBucketUpdates(d, bucketUpdates)
  1301. }
  1302. // GetAllBucketUpdates retrieves all the bucket updates
  1303. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1304. var bucketUpdates []*common.BucketUpdate
  1305. err := meddler.QueryAll(
  1306. hdb.db, &bucketUpdates,
  1307. `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
  1308. FROM bucket_update ORDER BY item_id;`,
  1309. )
  1310. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1311. }
  1312. // GetBucketUpdates retrieves latest values for each bucket
  1313. func (hdb *HistoryDB) GetBucketUpdates() ([]BucketUpdateAPI, error) {
  1314. var bucketUpdates []*BucketUpdateAPI
  1315. err := meddler.QueryAll(
  1316. hdb.db, &bucketUpdates,
  1317. `SELECT num_bucket, withdrawals FROM bucket_update
  1318. WHERE item_id in(SELECT max(item_id) FROM bucket_update
  1319. group by num_bucket)
  1320. ORDER BY num_bucket ASC;`,
  1321. )
  1322. return db.SlicePtrsToSlice(bucketUpdates).([]BucketUpdateAPI), tracerr.Wrap(err)
  1323. }
  1324. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1325. if len(tokenExchanges) == 0 {
  1326. return nil
  1327. }
  1328. return tracerr.Wrap(db.BulkInsert(
  1329. d,
  1330. `INSERT INTO token_exchange (
  1331. eth_block_num,
  1332. eth_addr,
  1333. value_usd
  1334. ) VALUES %s;`,
  1335. tokenExchanges[:],
  1336. ))
  1337. }
  1338. // GetAllTokenExchanges retrieves all the token exchanges
  1339. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1340. var tokenExchanges []*common.TokenExchange
  1341. err := meddler.QueryAll(
  1342. hdb.db, &tokenExchanges,
  1343. "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
  1344. )
  1345. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1346. }
  1347. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1348. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1349. if len(escapeHatchWithdrawals) == 0 {
  1350. return nil
  1351. }
  1352. return tracerr.Wrap(db.BulkInsert(
  1353. d,
  1354. `INSERT INTO escape_hatch_withdrawal (
  1355. eth_block_num,
  1356. who_addr,
  1357. to_addr,
  1358. token_addr,
  1359. amount
  1360. ) VALUES %s;`,
  1361. escapeHatchWithdrawals[:],
  1362. ))
  1363. }
  1364. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1365. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1366. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1367. err := meddler.QueryAll(
  1368. hdb.db, &escapeHatchWithdrawals,
  1369. "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
  1370. )
  1371. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1372. tracerr.Wrap(err)
  1373. }
  1374. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1375. // contract variables. This initial state is stored linked to block 0, which
  1376. // always exist in the DB and is used to store initialization data that always
  1377. // exist in the smart contracts.
  1378. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1379. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1380. txn, err := hdb.db.Beginx()
  1381. if err != nil {
  1382. return tracerr.Wrap(err)
  1383. }
  1384. defer func() {
  1385. if err != nil {
  1386. db.Rollback(txn)
  1387. }
  1388. }()
  1389. // Force EthBlockNum to be 0 because it's the block used to link data
  1390. // that belongs to the creation of the smart contracts
  1391. rollup.EthBlockNum = 0
  1392. auction.EthBlockNum = 0
  1393. wDelayer.EthBlockNum = 0
  1394. auction.DefaultSlotSetBidSlotNum = 0
  1395. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1396. return tracerr.Wrap(err)
  1397. }
  1398. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1399. return tracerr.Wrap(err)
  1400. }
  1401. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1402. return tracerr.Wrap(err)
  1403. }
  1404. return tracerr.Wrap(txn.Commit())
  1405. }
  1406. // setExtraInfoForgedL1UserTxs sets the EffectiveAmount, EffectiveDepositAmount
  1407. // and EffectiveFromIdx of the given l1UserTxs (with an UPDATE)
  1408. func (hdb *HistoryDB) setExtraInfoForgedL1UserTxs(d sqlx.Ext, txs []common.L1Tx) error {
  1409. if len(txs) == 0 {
  1410. return nil
  1411. }
  1412. // Effective amounts are stored as success flags in the DB, with true value by default
  1413. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1414. // updated to become false. At the same time, all the txs that contain
  1415. // accounts (FromIdx == 0) are updated to set the EffectiveFromIdx.
  1416. type txUpdate struct {
  1417. ID common.TxID `db:"id"`
  1418. AmountSuccess bool `db:"amount_success"`
  1419. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1420. EffectiveFromIdx common.Idx `db:"effective_from_idx"`
  1421. }
  1422. txUpdates := []txUpdate{}
  1423. equal := func(a *big.Int, b *big.Int) bool {
  1424. return a.Cmp(b) == 0
  1425. }
  1426. for i := range txs {
  1427. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1428. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1429. if !amountSuccess || !depositAmountSuccess || txs[i].FromIdx == 0 {
  1430. txUpdates = append(txUpdates, txUpdate{
  1431. ID: txs[i].TxID,
  1432. AmountSuccess: amountSuccess,
  1433. DepositAmountSuccess: depositAmountSuccess,
  1434. EffectiveFromIdx: txs[i].EffectiveFromIdx,
  1435. })
  1436. }
  1437. }
  1438. const query string = `
  1439. UPDATE tx SET
  1440. amount_success = tx_update.amount_success,
  1441. deposit_amount_success = tx_update.deposit_amount_success,
  1442. effective_from_idx = tx_update.effective_from_idx
  1443. FROM (VALUES
  1444. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL, NULL::::BIGINT),
  1445. (:id, :amount_success, :deposit_amount_success, :effective_from_idx)
  1446. ) as tx_update (id, amount_success, deposit_amount_success, effective_from_idx)
  1447. WHERE tx.id = tx_update.id;
  1448. `
  1449. if len(txUpdates) > 0 {
  1450. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1451. return tracerr.Wrap(err)
  1452. }
  1453. }
  1454. return nil
  1455. }
  1456. // AddBlockSCData stores all the information of a block retrieved by the
  1457. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1458. // the pagination system of the API/DB depends on this. Within blocks, all
  1459. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1460. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1461. txn, err := hdb.db.Beginx()
  1462. if err != nil {
  1463. return tracerr.Wrap(err)
  1464. }
  1465. defer func() {
  1466. if err != nil {
  1467. db.Rollback(txn)
  1468. }
  1469. }()
  1470. // Add block
  1471. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1472. return tracerr.Wrap(err)
  1473. }
  1474. // Add Coordinators
  1475. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1476. return tracerr.Wrap(err)
  1477. }
  1478. // Add Bids
  1479. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1480. return tracerr.Wrap(err)
  1481. }
  1482. // Add Tokens
  1483. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1484. return tracerr.Wrap(err)
  1485. }
  1486. // Prepare user L1 txs to be added.
  1487. // They must be added before the batch that will forge them (which can be in the same block)
  1488. // and after the account that will be sent to (also can be in the same block).
  1489. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1490. // the batch that forges those txs is inserted
  1491. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1492. for i := range blockData.Rollup.L1UserTxs {
  1493. batchThatForgesIsInTheBlock := false
  1494. for _, batch := range blockData.Rollup.Batches {
  1495. if batch.Batch.ForgeL1TxsNum != nil &&
  1496. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1497. // Tx is forged in this block. It's guaranteed that:
  1498. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1499. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1500. batchThatForgesIsInTheBlock = true
  1501. addAtBatchNum := batch.Batch.BatchNum - 1
  1502. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1503. break
  1504. }
  1505. }
  1506. if !batchThatForgesIsInTheBlock {
  1507. // User artificial batchNum 0 to add txs that are not forge in this block
  1508. // after all the accounts of the block have been added
  1509. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1510. }
  1511. }
  1512. // Add Batches
  1513. for i := range blockData.Rollup.Batches {
  1514. batch := &blockData.Rollup.Batches[i]
  1515. // Add Batch: this will trigger an update on the DB
  1516. // that will set the batch num of forged L1 txs in this batch
  1517. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1518. return tracerr.Wrap(err)
  1519. }
  1520. // Add accounts
  1521. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1522. return tracerr.Wrap(err)
  1523. }
  1524. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1525. // L1UserTxs that have been forged in this batch
  1526. if err = hdb.setExtraInfoForgedL1UserTxs(txn, batch.L1UserTxs); err != nil {
  1527. return tracerr.Wrap(err)
  1528. }
  1529. // Add forged l1 coordinator Txs
  1530. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1531. return tracerr.Wrap(err)
  1532. }
  1533. // Add l2 Txs
  1534. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1535. return tracerr.Wrap(err)
  1536. }
  1537. // Add user L1 txs that will be forged in next batch
  1538. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1539. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1540. return tracerr.Wrap(err)
  1541. }
  1542. }
  1543. // Add exit tree
  1544. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1545. return tracerr.Wrap(err)
  1546. }
  1547. }
  1548. // Add user L1 txs that won't be forged in this block
  1549. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1550. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1551. return tracerr.Wrap(err)
  1552. }
  1553. }
  1554. // Set SC Vars if there was an update
  1555. if blockData.Rollup.Vars != nil {
  1556. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1557. return tracerr.Wrap(err)
  1558. }
  1559. }
  1560. if blockData.Auction.Vars != nil {
  1561. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1562. return tracerr.Wrap(err)
  1563. }
  1564. }
  1565. if blockData.WDelayer.Vars != nil {
  1566. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1567. return tracerr.Wrap(err)
  1568. }
  1569. }
  1570. // Update withdrawals in exit tree table
  1571. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1572. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1573. return tracerr.Wrap(err)
  1574. }
  1575. // Add Escape Hatch Withdrawals
  1576. if err := hdb.addEscapeHatchWithdrawals(txn,
  1577. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1578. return tracerr.Wrap(err)
  1579. }
  1580. // Add Buckets withdrawals updates
  1581. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1582. return tracerr.Wrap(err)
  1583. }
  1584. // Add Token exchange updates
  1585. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1586. return tracerr.Wrap(err)
  1587. }
  1588. return tracerr.Wrap(txn.Commit())
  1589. }
  1590. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1591. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1592. coordinator := &CoordinatorAPI{}
  1593. err := meddler.QueryRow(
  1594. hdb.db, coordinator,
  1595. "SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
  1596. bidderAddr,
  1597. )
  1598. return coordinator, tracerr.Wrap(err)
  1599. }
  1600. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1601. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1602. bidderAddr, forgerAddr *ethCommon.Address,
  1603. fromItem, limit *uint, order string,
  1604. ) ([]CoordinatorAPI, uint64, error) {
  1605. var query string
  1606. var args []interface{}
  1607. queryStr := `SELECT coordinator.*, COUNT(*) OVER() AS total_items
  1608. FROM coordinator INNER JOIN (
  1609. SELECT MAX(item_id) AS item_id FROM coordinator
  1610. GROUP BY bidder_addr
  1611. ) c ON coordinator.item_id = c.item_id `
  1612. // Apply filters
  1613. nextIsAnd := false
  1614. if bidderAddr != nil {
  1615. queryStr += "WHERE bidder_addr = ? "
  1616. nextIsAnd = true
  1617. args = append(args, bidderAddr)
  1618. }
  1619. if forgerAddr != nil {
  1620. if nextIsAnd {
  1621. queryStr += "AND "
  1622. } else {
  1623. queryStr += "WHERE "
  1624. }
  1625. queryStr += "forger_addr = ? "
  1626. nextIsAnd = true
  1627. args = append(args, forgerAddr)
  1628. }
  1629. if fromItem != nil {
  1630. if nextIsAnd {
  1631. queryStr += "AND "
  1632. } else {
  1633. queryStr += "WHERE "
  1634. }
  1635. if order == OrderAsc {
  1636. queryStr += "coordinator.item_id >= ? "
  1637. } else {
  1638. queryStr += "coordinator.item_id <= ? "
  1639. }
  1640. args = append(args, fromItem)
  1641. }
  1642. // pagination
  1643. queryStr += "ORDER BY coordinator.item_id "
  1644. if order == OrderAsc {
  1645. queryStr += " ASC "
  1646. } else {
  1647. queryStr += " DESC "
  1648. }
  1649. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1650. query = hdb.db.Rebind(queryStr)
  1651. coordinators := []*CoordinatorAPI{}
  1652. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1653. return nil, 0, tracerr.Wrap(err)
  1654. }
  1655. if len(coordinators) == 0 {
  1656. return []CoordinatorAPI{}, 0, nil
  1657. }
  1658. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1659. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1660. }
  1661. // AddAuctionVars insert auction vars into the DB
  1662. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1663. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1664. }
  1665. // GetAuctionVars returns auction variables
  1666. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1667. auctionVars := &common.AuctionVariables{}
  1668. err := meddler.QueryRow(
  1669. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1670. )
  1671. return auctionVars, tracerr.Wrap(err)
  1672. }
  1673. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1674. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1675. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1676. auctionVars := []*MinBidInfo{}
  1677. query := `
  1678. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1679. WHERE default_slot_set_bid_slot_num < $1
  1680. ORDER BY default_slot_set_bid_slot_num DESC
  1681. LIMIT $2;
  1682. `
  1683. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1684. if err != nil {
  1685. return nil, tracerr.Wrap(err)
  1686. }
  1687. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1688. }
  1689. // GetAccountAPI returns an account by its index
  1690. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1691. account := &AccountAPI{}
  1692. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1693. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1694. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1695. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1696. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1697. if err != nil {
  1698. return nil, tracerr.Wrap(err)
  1699. }
  1700. return account, nil
  1701. }
  1702. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1703. func (hdb *HistoryDB) GetAccountsAPI(
  1704. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1705. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1706. ) ([]AccountAPI, uint64, error) {
  1707. if ethAddr != nil && bjj != nil {
  1708. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1709. }
  1710. var query string
  1711. var args []interface{}
  1712. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1713. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1714. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1715. COUNT(*) OVER() AS total_items
  1716. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1717. // Apply filters
  1718. nextIsAnd := false
  1719. // ethAddr filter
  1720. if ethAddr != nil {
  1721. queryStr += "WHERE account.eth_addr = ? "
  1722. nextIsAnd = true
  1723. args = append(args, ethAddr)
  1724. } else if bjj != nil { // bjj filter
  1725. queryStr += "WHERE account.bjj = ? "
  1726. nextIsAnd = true
  1727. args = append(args, bjj)
  1728. }
  1729. // tokenID filter
  1730. if len(tokenIDs) > 0 {
  1731. if nextIsAnd {
  1732. queryStr += "AND "
  1733. } else {
  1734. queryStr += "WHERE "
  1735. }
  1736. queryStr += "account.token_id IN (?) "
  1737. args = append(args, tokenIDs)
  1738. nextIsAnd = true
  1739. }
  1740. if fromItem != nil {
  1741. if nextIsAnd {
  1742. queryStr += "AND "
  1743. } else {
  1744. queryStr += "WHERE "
  1745. }
  1746. if order == OrderAsc {
  1747. queryStr += "account.item_id >= ? "
  1748. } else {
  1749. queryStr += "account.item_id <= ? "
  1750. }
  1751. args = append(args, fromItem)
  1752. }
  1753. // pagination
  1754. queryStr += "ORDER BY account.item_id "
  1755. if order == OrderAsc {
  1756. queryStr += " ASC "
  1757. } else {
  1758. queryStr += " DESC "
  1759. }
  1760. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1761. query, argsQ, err := sqlx.In(queryStr, args...)
  1762. if err != nil {
  1763. return nil, 0, tracerr.Wrap(err)
  1764. }
  1765. query = hdb.db.Rebind(query)
  1766. accounts := []*AccountAPI{}
  1767. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1768. return nil, 0, tracerr.Wrap(err)
  1769. }
  1770. if len(accounts) == 0 {
  1771. return []AccountAPI{}, 0, nil
  1772. }
  1773. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1774. accounts[0].TotalItems - uint64(len(accounts)), nil
  1775. }
  1776. // GetMetrics returns metrics
  1777. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1778. metricsTotals := &MetricsTotals{}
  1779. metrics := &Metrics{}
  1780. err := meddler.QueryRow(
  1781. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1782. COALESCE (MIN(tx.batch_num), 0) as batch_num, COALESCE (MIN(block.timestamp),
  1783. NOW()) AS min_timestamp, COALESCE (MAX(block.timestamp), NOW()) AS max_timestamp
  1784. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1785. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1786. if err != nil {
  1787. return nil, tracerr.Wrap(err)
  1788. }
  1789. seconds := metricsTotals.MaxTimestamp.Sub(metricsTotals.MinTimestamp).Seconds()
  1790. // Avoid dividing by 0
  1791. if seconds == 0 {
  1792. seconds++
  1793. }
  1794. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions) / seconds
  1795. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1796. metrics.TransactionsPerBatch = float64(metricsTotals.TotalTransactions) /
  1797. float64(lastBatchNum-metricsTotals.FirstBatchNum+1)
  1798. } else {
  1799. metrics.TransactionsPerBatch = float64(0)
  1800. }
  1801. err = meddler.QueryRow(
  1802. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1803. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1804. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1805. if err != nil {
  1806. return nil, tracerr.Wrap(err)
  1807. }
  1808. if metricsTotals.TotalBatches > 0 {
  1809. metrics.BatchFrequency = seconds / float64(metricsTotals.TotalBatches)
  1810. } else {
  1811. metrics.BatchFrequency = 0
  1812. }
  1813. if metricsTotals.TotalTransactions > 0 {
  1814. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1815. } else {
  1816. metrics.AvgTransactionFee = 0
  1817. }
  1818. err = meddler.QueryRow(
  1819. hdb.db, metrics,
  1820. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1821. if err != nil {
  1822. return nil, tracerr.Wrap(err)
  1823. }
  1824. return metrics, nil
  1825. }
  1826. // GetAvgTxFee returns average transaction fee of the last 1h
  1827. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1828. metricsTotals := &MetricsTotals{}
  1829. err := meddler.QueryRow(
  1830. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1831. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1832. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1833. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1834. if err != nil {
  1835. return 0, tracerr.Wrap(err)
  1836. }
  1837. err = meddler.QueryRow(
  1838. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1839. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1840. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1841. if err != nil {
  1842. return 0, tracerr.Wrap(err)
  1843. }
  1844. var avgTransactionFee float64
  1845. if metricsTotals.TotalTransactions > 0 {
  1846. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1847. } else {
  1848. avgTransactionFee = 0
  1849. }
  1850. return avgTransactionFee, nil
  1851. }