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.

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