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.

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