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.

1904 lines
60 KiB

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