|
| 1 | +use alloy::{ |
| 2 | + network::Network, |
| 3 | + primitives::Address, |
| 4 | + providers::{Provider, fillers::NonceManager}, |
| 5 | + transports::TransportResult, |
| 6 | +}; |
| 7 | +use async_trait::async_trait; |
| 8 | +use futures::lock::{Mutex, MutexGuard}; |
| 9 | +use std::collections::{BTreeSet, HashMap, hash_map::Entry}; |
| 10 | +use std::sync::Arc; |
| 11 | +use tracing::trace; |
| 12 | + |
| 13 | +/// A robust, in-memory nonce manager for a scalable transaction engine. |
| 14 | +#[derive(Clone, Debug, Default)] |
| 15 | +pub struct ZamaNonceManager { |
| 16 | + /// Nonce state for each account, shared across all tasks/threads using the nonce manager. |
| 17 | + accounts: Arc<Mutex<HashMap<Address, AccountState>>>, |
| 18 | +} |
| 19 | + |
| 20 | +/// Represents the complete nonce state for a single account. |
| 21 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 22 | +pub struct AccountState { |
| 23 | + /// The "high-water mark" nonce. Used only when no gaps are available. |
| 24 | + pub next_nonce: u64, |
| 25 | + /// Nonces that have been dispatched but not yet confirmed or rejected. |
| 26 | + pub locked_nonces: BTreeSet<u64>, |
| 27 | + /// Nonces that were previously locked but have been released, creating gaps. |
| 28 | + pub available_nonces: BTreeSet<u64>, |
| 29 | +} |
| 30 | + |
| 31 | +impl ZamaNonceManager { |
| 32 | + pub fn new() -> Self { |
| 33 | + Self::default() |
| 34 | + } |
| 35 | + |
| 36 | + /// The primary logic for acquiring and locking the next valid nonce. |
| 37 | + /// |
| 38 | + /// The logic prioritizes filling gaps from `available_nonces` before |
| 39 | + /// incrementing the main `next_nonce` counter. |
| 40 | + pub async fn get_increase_and_lock_nonce<P, N>( |
| 41 | + &self, |
| 42 | + provider: &P, |
| 43 | + address: Address, |
| 44 | + ) -> TransportResult<u64> |
| 45 | + where |
| 46 | + P: Provider<N>, |
| 47 | + N: Network, |
| 48 | + { |
| 49 | + let mut accounts_guard = self.accounts.lock().await; |
| 50 | + let account = |
| 51 | + Self::get_or_init_account_state(&mut accounts_guard, provider, address).await?; |
| 52 | + let nonce_to_use = |
| 53 | + if let Some(available_nonce) = account.available_nonces.iter().next().copied() { |
| 54 | + account.available_nonces.remove(&available_nonce); |
| 55 | + trace!(%address, nonce = available_nonce, "Reusing available nonce"); |
| 56 | + available_nonce |
| 57 | + } else { |
| 58 | + let next = account.next_nonce; |
| 59 | + account.next_nonce += 1; |
| 60 | + trace!(%address, nonce = next, "Using next sequential nonce"); |
| 61 | + next |
| 62 | + }; |
| 63 | + |
| 64 | + account.locked_nonces.insert(nonce_to_use); |
| 65 | + Ok(nonce_to_use) |
| 66 | + } |
| 67 | + |
| 68 | + /// Releases a locked nonce, making it available for reuse. |
| 69 | + pub async fn release_nonce(&self, address: Address, nonce: u64) { |
| 70 | + let mut accounts = self.accounts.lock().await; |
| 71 | + if let Some(account) = accounts.get_mut(&address) |
| 72 | + && account.locked_nonces.remove(&nonce) |
| 73 | + { |
| 74 | + account.available_nonces.insert(nonce); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + /// Confirms a nonce has been used on-chain, removing it permanently. |
| 79 | + pub async fn confirm_nonce(&self, address: Address, nonce: u64) { |
| 80 | + let mut accounts = self.accounts.lock().await; |
| 81 | + if let Some(account) = accounts.get_mut(&address) { |
| 82 | + account.locked_nonces.remove(&nonce); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /// Helper to retrieve or initialize the `AccountState` for an address. |
| 87 | + async fn get_or_init_account_state<'a, P, N>( |
| 88 | + accounts_guard: &'a mut MutexGuard<'_, HashMap<Address, AccountState>>, |
| 89 | + provider: &P, |
| 90 | + address: Address, |
| 91 | + ) -> TransportResult<&'a mut AccountState> |
| 92 | + where |
| 93 | + P: Provider<N>, |
| 94 | + N: Network, |
| 95 | + { |
| 96 | + let account = match accounts_guard.entry(address) { |
| 97 | + Entry::Occupied(entry) => entry.into_mut(), |
| 98 | + Entry::Vacant(entry) => { |
| 99 | + let initial_nonce = provider.get_transaction_count(address).await?; |
| 100 | + entry.insert(AccountState { |
| 101 | + next_nonce: initial_nonce, |
| 102 | + ..Default::default() |
| 103 | + }) |
| 104 | + } |
| 105 | + }; |
| 106 | + Ok(account) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +// Implements the `NonceManager` trait for seamless integration with Alloy's provider stack. |
| 111 | +#[async_trait] |
| 112 | +impl NonceManager for ZamaNonceManager { |
| 113 | + async fn get_next_nonce<P, N>(&self, provider: &P, address: Address) -> TransportResult<u64> |
| 114 | + where |
| 115 | + P: Provider<N>, |
| 116 | + N: Network, |
| 117 | + { |
| 118 | + self.get_increase_and_lock_nonce(provider, address).await |
| 119 | + } |
| 120 | +} |
0 commit comments