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.

1866 lines
58 KiB

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