Skip to content

Commit

Permalink
feat(mempool): add pending queue to tx queue
Browse files Browse the repository at this point in the history
  • Loading branch information
MohammadNassar1 committed Aug 27, 2024
1 parent 381eed6 commit f5c541a
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions crates/mempool/src/transaction_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,39 @@ use starknet_api::core::{ContractAddress, Nonce};

use crate::mempool::TransactionReference;

// A queue holding the transaction that with nonces that match account nonces.
// Note: the derived comparison functionality considers the order guaranteed by the data structures
// used.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct TransactionQueue {
// Priority queue of transactions with associated priority.
gas_price_threshold: u128,
// Transactions with gas price above gas price threshold (sorted by tip).
priority_queue: BTreeSet<PriorityTransaction>,
// Transactions with gas price below gas price threshold (sorted by price).
pending_queue: BTreeSet<PendingTransaction>,
// Set of account addresses for efficient existence checks.
address_to_tx: HashMap<ContractAddress, TransactionReference>,
}

impl TransactionQueue {
/// Adds a transaction to the mempool, ensuring unique keys.
/// Panics: if given a duplicate tx.
// TODO(Mohammad): Add test for two transactions from the same address, expecting specific
// assert.
pub fn insert(&mut self, tx_reference: TransactionReference) {
assert_eq!(
self.address_to_tx.insert(tx_reference.sender_address, tx_reference.clone()),
None,
"Only a single transaction from the same contract class can be in the mempool at a \
time."
);

let new_tx_successfully_inserted =
if tx_reference.get_l2_gas_price() < self.gas_price_threshold {
self.pending_queue.insert(tx_reference.into())
} else {
self.priority_queue.insert(tx_reference.into())
};
assert!(
self.priority_queue.insert(tx_reference.into()),
new_tx_successfully_inserted,
"Keys should be unique; duplicates are checked prior."
);
}
Expand Down Expand Up @@ -57,10 +66,12 @@ impl TransactionQueue {
/// Removes the transaction of the given account address from the queue.
/// This is well-defined, since there is at most one transaction per address in the queue.
pub fn remove(&mut self, address: ContractAddress) -> bool {
if let Some(tx) = self.address_to_tx.remove(&address) {
return self.priority_queue.remove(&tx.into());
}
false
let Some(tx_reference) = self.address_to_tx.remove(&address) else {
return false;
};

self.priority_queue.remove(&tx_reference.clone().into())
|| self.pending_queue.remove(&tx_reference.into())
}

pub fn has_ready_txs(&self) -> bool {
Expand Down

0 comments on commit f5c541a

Please sign in to comment.