Skip to content

Commit 872c9a0

Browse files
committed
replace cached with moka for caching
1 parent d0a7d2a commit 872c9a0

6 files changed

Lines changed: 82 additions & 168 deletions

File tree

Cargo.lock

Lines changed: 4 additions & 82 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/balance-overrides/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@ alloy-sol-types = { workspace = true }
1818
alloy-transport = { workspace = true }
1919
anyhow = { workspace = true }
2020
async-trait = { workspace = true }
21-
cached = { workspace = true, features = ["default"] }
2221
clap = { workspace = true }
2322
configs = { workspace = true }
2423
contracts = { workspace = true }
2524
ethrpc = { workspace = true }
25+
moka = { workspace = true, features = ["sync"] }
2626
serde = { workspace = true }
2727
thiserror = { workspace = true }
2828
tokio = { workspace = true }

crates/balance-overrides/src/approval/mod.rs

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use {
2-
crate::detector::{DetectionError, SimulationError, extract_sload_slots, mapping_slot_hash},
2+
crate::{
3+
cache::Cache,
4+
detector::{DetectionError, SimulationError, extract_sload_slots, mapping_slot_hash},
5+
},
36
alloy_eips::BlockId,
47
alloy_primitives::{Address, B256, TxKind, U256, keccak256, map::AddressMap},
58
alloy_provider::ext::DebugApi,
@@ -11,10 +14,9 @@ use {
1114
},
1215
alloy_sol_types::SolCall,
1316
alloy_transport::TransportErrorKind,
14-
cached::{Cached, SizedCache},
1517
contracts::ERC20,
1618
ethrpc::Web3,
17-
std::{iter, sync::Mutex, time::Duration},
19+
std::{iter, time::Duration},
1820
};
1921

2022
/// These are the solady magic bytes for user allowances
@@ -184,8 +186,6 @@ impl ApprovalStrategy {
184186
}
185187
}
186188

187-
type Cache = SizedCache<(Address, Option<(Address, Address)>), Option<ApprovalStrategy>>;
188-
189189
/// Heuristic approval override detector with integrated caching.
190190
///
191191
/// Owns the Web3 handle, detection parameters, and the per-token strategy
@@ -197,7 +197,7 @@ pub(crate) struct Detector {
197197
web3: Web3,
198198
probing_depth: u8,
199199
verification_timeout: Duration,
200-
pub(crate) cache: Mutex<Cache>,
200+
pub(crate) cache: Cache<(Address, Option<(Address, Address)>), Option<ApprovalStrategy>>,
201201
}
202202

203203
impl Detector {
@@ -211,7 +211,7 @@ impl Detector {
211211
web3,
212212
probing_depth,
213213
verification_timeout,
214-
cache: Mutex::new(SizedCache::with_size(cache_size)),
214+
cache: Cache::new(u64::try_from(cache_size).expect("cache_size must be non-negative")),
215215
}
216216
}
217217

@@ -231,19 +231,18 @@ impl Detector {
231231
tracing::trace!(?token, "attempting to auto-detect approval slot");
232232

233233
{
234-
let mut cache = self.cache.lock().unwrap();
235-
if let Some(strategy) = cache.cache_get(&(token, None)) {
234+
if let Some(strategy_opt) = self.cache.get(&(token, None)) {
236235
tracing::trace!(?token, "cache hit (strategy valid for all pairs)");
237-
return strategy.clone();
236+
return strategy_opt;
238237
}
239-
if let Some(strategy) = cache.cache_get(&(token, Some((owner, spender)))) {
238+
if let Some(strategy_opt) = self.cache.get(&(token, Some((owner, spender)))) {
240239
tracing::trace!(
241240
?token,
242241
?owner,
243242
?spender,
244243
"cache hit (pair-specific strategy)"
245244
);
246-
return strategy.clone();
245+
return strategy_opt;
247246
}
248247
}
249248

@@ -256,15 +255,9 @@ impl Detector {
256255
token,
257256
(!strategy.is_valid_for_all_pairs()).then_some((owner, spender)),
258257
);
259-
self.cache
260-
.lock()
261-
.unwrap()
262-
.cache_set(cache_key, Some(strategy.clone()));
258+
self.cache.insert(cache_key, Some(strategy.clone()));
263259
} else {
264-
self.cache
265-
.lock()
266-
.unwrap()
267-
.cache_set((token, Some((owner, spender))), None);
260+
self.cache.insert((token, Some((owner, spender))), None);
268261
}
269262
} else {
270263
tracing::warn!(?token, ?result, "error auto-detecting approval strategy");

crates/balance-overrides/src/balance/mod.rs

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
pub(crate) mod aave;
22

33
use {
4-
crate::detector::{DetectionError, SimulationError, extract_sload_slots, mapping_slot_hash},
4+
crate::{
5+
cache::Cache,
6+
detector::{DetectionError, SimulationError, extract_sload_slots, mapping_slot_hash},
7+
},
58
alloy_eips::BlockId,
69
alloy_primitives::{Address, B256, TxKind, U256, keccak256, map::AddressMap},
710
alloy_provider::ext::DebugApi,
@@ -13,10 +16,9 @@ use {
1316
},
1417
alloy_sol_types::SolCall,
1518
alloy_transport::TransportErrorKind,
16-
cached::{Cached, SizedCache},
1719
contracts::ERC20,
1820
ethrpc::Web3,
19-
std::{collections::HashMap, iter, sync::Mutex, time::Duration},
21+
std::{collections::HashMap, iter, time::Duration},
2022
};
2123

2224
/// These are the solady magic bytes for user balances
@@ -228,8 +230,6 @@ impl PartialEq for Strategy {
228230

229231
impl Eq for Strategy {}
230232

231-
type Cache = SizedCache<(Address, Option<Address>), Option<Strategy>>;
232-
233233
/// Heuristic balance override detector with integrated caching.
234234
///
235235
/// Owns the Web3 handle, detection parameters, and the per-token strategy
@@ -239,7 +239,7 @@ pub(crate) struct Detector {
239239
web3: Web3,
240240
probing_depth: u8,
241241
verification_timeout: Duration,
242-
pub(crate) cache: Mutex<Cache>,
242+
pub(crate) cache: Cache<(Address, Option<Address>), Option<Strategy>>,
243243
}
244244

245245
impl Detector {
@@ -253,7 +253,7 @@ impl Detector {
253253
web3,
254254
probing_depth,
255255
verification_timeout,
256-
cache: Mutex::new(SizedCache::with_size(cache_size)),
256+
cache: Cache::new(u64::try_from(cache_size).expect("cache_size must be non-negative")),
257257
}
258258
}
259259

@@ -263,14 +263,13 @@ impl Detector {
263263
tracing::trace!(?token, "attempting to auto-detect balance slot");
264264

265265
{
266-
let mut cache = self.cache.lock().unwrap();
267-
if let Some(strategy) = cache.cache_get(&(token, None)) {
266+
if let Some(strategy_opt) = self.cache.get(&(token, None)) {
268267
tracing::trace!(?token, "cache hit (strategy valid for all holders)");
269-
return strategy.clone();
268+
return strategy_opt;
270269
}
271-
if let Some(strategy) = cache.cache_get(&(token, Some(holder))) {
270+
if let Some(strategy_opt) = self.cache.get(&(token, Some(holder))) {
272271
tracing::trace!(?token, ?holder, "cache hit (holder-specific strategy)");
273-
return strategy.clone();
272+
return strategy_opt;
274273
}
275274
}
276275

@@ -283,17 +282,11 @@ impl Detector {
283282
(!strategy.can_be_applied_to_any_holder()).then_some(holder),
284283
);
285284
tracing::debug!(?token, ?strategy, "caching auto-detected balance strategy");
286-
self.cache
287-
.lock()
288-
.unwrap()
289-
.cache_set(cache_key, Some(strategy.clone()));
285+
self.cache.insert(cache_key, Some(strategy.clone()));
290286
}
291287
Err(DetectionError::NotFound) => {
292288
tracing::debug!(?token, "caching token as unsupported");
293-
self.cache
294-
.lock()
295-
.unwrap()
296-
.cache_set((token, Some(holder)), None);
289+
self.cache.insert((token, Some(holder)), None);
297290
}
298291
Err(err) => {
299292
tracing::warn!(
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/// Note: cloning shares the underlying cache instance.
2+
#[derive(Clone)]
3+
pub(crate) struct Cache<K, V> {
4+
data: moka::sync::Cache<K, V>,
5+
}
6+
7+
impl<K, V> Cache<K, V>
8+
where
9+
K: std::hash::Hash + Eq + Send + Sync + 'static,
10+
V: Clone + Send + Sync + 'static,
11+
{
12+
pub(crate) fn new(max_capacity: u64) -> Self {
13+
let data = moka::sync::Cache::builder()
14+
.max_capacity(max_capacity)
15+
.build();
16+
Self { data }
17+
}
18+
19+
pub(crate) fn get(&self, key: &K) -> Option<V> {
20+
self.data.get(key)
21+
}
22+
23+
pub(crate) fn insert(&self, key: K, value: V) {
24+
self.data.insert(key, value)
25+
}
26+
}

0 commit comments

Comments
 (0)