Skip to content

Commit

Permalink
feat(mempool): impl mempool state
Browse files Browse the repository at this point in the history
  • Loading branch information
MohammadNassar1 committed Jul 18, 2024
1 parent df1cff6 commit 9774833
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
23 changes: 23 additions & 0 deletions crates/mempool/src/mempool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::collections::HashMap;

use starknet_api::core::{ContractAddress, Nonce};
use starknet_api::transaction::{Tip, TransactionHash};
use starknet_mempool_types::errors::MempoolError;
use starknet_mempool_types::mempool_types::{
Account, AccountState, MempoolInput, MempoolResult, ThinTransaction,
};
Expand All @@ -20,6 +21,8 @@ pub struct Mempool {
tx_pool: TransactionPool,
// Transactions eligible for sequencing.
tx_queue: TransactionQueue,
// Represents the current state of the mempool during batch processing.
mempool_state: HashMap<ContractAddress, AccountState>,
}

impl Mempool {
Expand Down Expand Up @@ -54,13 +57,24 @@ impl Mempool {
eligible_txs.push(tx);
}

for tx in &eligible_txs {
self.mempool_state.entry(tx.sender_address).and_modify(|account| {
account.nonce = tx.nonce;
});
}

for tx in &eligible_txs {
self.mempool_state.entry(tx.sender_address).or_default().nonce = tx.nonce;
}

Ok(eligible_txs)
}

/// Adds a new transaction to the mempool.
/// TODO: support fee escalation and transactions with future nonces.
/// TODO: check Account nonce and balance.
pub fn add_tx(&mut self, input: MempoolInput) -> MempoolResult<()> {
self.is_duplicated_tx(&input.tx)?;
self.insert_tx(input)
}

Expand Down Expand Up @@ -100,6 +114,15 @@ impl Mempool {
Ok(())
}

fn is_duplicated_tx(&self, tx: &ThinTransaction) -> MempoolResult<()> {
if let Some(AccountState { nonce }) = self.mempool_state.get(&tx.sender_address) {
if *nonce >= tx.nonce {
return Err(MempoolError::DuplicateTransaction { tx_hash: tx.tx_hash });
}
}
Ok(())
}

#[cfg(test)]
pub(crate) fn _tx_pool(&self) -> &TransactionPool {
&self.tx_pool
Expand Down
2 changes: 1 addition & 1 deletion crates/mempool/src/mempool_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl MempoolState {
impl From<MempoolState> for Mempool {
fn from(mempool_state: MempoolState) -> Mempool {
let MempoolState { tx_pool, tx_queue } = mempool_state;
Mempool { tx_pool, tx_queue }
Mempool { tx_pool, tx_queue, ..Default::default() }
}
}

Expand Down

0 comments on commit 9774833

Please sign in to comment.