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.

1970 lines
62 KiB

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