Skip to main content

walletkit/adapters/store/
memory.rs

1//! In-memory `StateStore`: a versioned map of `scope -> nonce state` plus persisted
2//! handles. Non-durable, so recovery is single-run — the durable backends are
3//! the feature-gated `redb` and `postgres` stores.
4
5use crate::core::deps::{StateStore, StateStoreError, Versioned};
6use crate::core::wallet::{FenceToken, HandleId, NonceScope, NonceState, TxHandle};
7use alloy_primitives::Address;
8use async_trait::async_trait;
9use parking_lot::Mutex;
10use std::collections::HashMap;
11
12/// The non-durable [`StateStore`]: keeps nonce state and
13/// handles in memory. Recovery is single-run only; use redb/Postgres to survive a restart.
14#[derive(Default)]
15pub struct InMemoryStateStore {
16    nonces: Mutex<HashMap<NonceScope, (Versioned<NonceState>, FenceToken)>>,
17    handles: Mutex<HashMap<HandleId, TxHandle>>,
18}
19
20#[async_trait]
21impl StateStore for InMemoryStateStore {
22    async fn load_nonce_state(
23        &self,
24        scope: NonceScope,
25    ) -> Result<Versioned<NonceState>, StateStoreError> {
26        Ok(self
27            .nonces
28            .lock()
29            .get(&scope)
30            .map(|(v, _)| v.clone())
31            .unwrap_or_default())
32    }
33
34    async fn cas_nonce_state(
35        &self,
36        scope: NonceScope,
37        expected_version: u64,
38        state: &NonceState,
39        fence: FenceToken,
40    ) -> Result<bool, StateStoreError> {
41        let mut nonces = self.nonces.lock();
42        let (cur_version, cur_fence) = nonces
43            .get(&scope)
44            .map_or((0, FenceToken::SINGLE_WRITER), |(v, f)| (v.version, *f));
45        if fence < cur_fence {
46            return Err(StateStoreError::Fenced);
47        }
48        if cur_version != expected_version {
49            return Ok(false);
50        }
51        // Past the guard, `fence >= cur_fence`, so it is already the new high-water mark.
52        let entry = (
53            Versioned {
54                value: state.clone(),
55                version: expected_version + 1,
56            },
57            fence,
58        );
59        nonces.insert(scope, entry);
60        Ok(true)
61    }
62
63    async fn put_handle(&self, handle: &TxHandle) -> Result<(), StateStoreError> {
64        self.handles.lock().insert(handle.id, handle.clone());
65        Ok(())
66    }
67
68    async fn pending_handles(&self, account: Address) -> Result<Vec<TxHandle>, StateStoreError> {
69        Ok(self
70            .handles
71            .lock()
72            .values()
73            .filter(|h| h.account == account && !h.status.is_terminal())
74            .cloned()
75            .collect())
76    }
77
78    async fn handle(&self, id: HandleId) -> Result<Option<TxHandle>, StateStoreError> {
79        Ok(self.handles.lock().get(&id).cloned())
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use std::sync::Arc;
87
88    // Held to the same backend-agnostic contract as redb/Postgres.
89    #[tokio::test]
90    async fn in_memory_store_passes_conformance() {
91        crate::testutils::state_store_conformance(Arc::new(InMemoryStateStore::default())).await;
92    }
93}