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.

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