Skip to content

Commit b6d9604

Browse files
committed
refactor: improvements to nonce cache from review
1 parent 5abe94d commit b6d9604

File tree

1 file changed

+25
-32
lines changed

1 file changed

+25
-32
lines changed

stackslib/src/core/nonce_cache.rs

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (C) 2024 Stacks Open Internet Foundation
1+
// Copyright (C) 2025 Stacks Open Internet Foundation
22
//
33
// This program is free software: you can redistribute it and/or modify
44
// it under the terms of the GNU General Public License as published by
@@ -67,38 +67,31 @@ impl NonceCache {
6767
C: ClarityConnection,
6868
{
6969
// Check in-memory cache
70-
match self.cache.get(address) {
71-
Some(nonce) => nonce,
72-
None => {
73-
// Check sqlite cache
74-
let opt_nonce = match db_get_nonce(mempool_db, address) {
75-
Ok(opt_nonce) => opt_nonce,
76-
Err(e) => {
77-
warn!("error retrieving nonce from mempool db: {}", e);
78-
None
79-
}
80-
};
81-
match opt_nonce {
82-
Some(nonce) => {
83-
// Insert into in-memory cache, but it is not dirty,
84-
// since we just got it from the database.
85-
let evicted = self.cache.insert_clean(address.clone(), nonce);
86-
if evicted.is_some() {
87-
// If we evicted something, we need to flush the cache.
88-
self.flush_with_evicted(mempool_db, evicted);
89-
}
90-
nonce
91-
}
92-
None => {
93-
let nonce =
94-
StacksChainState::get_nonce(clarity_tx, &address.clone().into());
95-
96-
self.set(address.clone(), nonce, mempool_db);
97-
nonce
98-
}
99-
}
70+
if let Some(cached_nonce) = self.cache.get(address) {
71+
return cached_nonce;
72+
};
73+
74+
// Check sqlite cache
75+
let db_nonce_opt = db_get_nonce(mempool_db, address).unwrap_or_else(|e| {
76+
warn!("error retrieving nonce from mempool db: {e}");
77+
None
78+
});
79+
if let Some(db_nonce) = db_nonce_opt {
80+
// Insert into in-memory cache, but it is not dirty,
81+
// since we just got it from the database.
82+
let evicted = self.cache.insert_clean(address.clone(), db_nonce);
83+
if evicted.is_some() {
84+
// If we evicted something, we need to flush the cache.
85+
self.flush_with_evicted(mempool_db, evicted);
10086
}
87+
return db_nonce;
10188
}
89+
90+
// Check the chainstate
91+
let nonce = StacksChainState::get_nonce(clarity_tx, &address.clone().into());
92+
93+
self.set(address.clone(), nonce, mempool_db);
94+
nonce
10295
}
10396

10497
/// Set the nonce for `address` to `value` in the in-memory cache.
@@ -164,7 +157,7 @@ impl NonceCache {
164157
Ok(())
165158
}
166159

167-
/// Flush the in-memory cache the the DB.
160+
/// Flush the in-memory cache to the DB.
168161
/// Do not return until successful.
169162
pub fn flush(&mut self, conn: &mut DBConn) {
170163
self.flush_with_evicted(conn, None)

0 commit comments

Comments
 (0)