Skip to main content

defuse_core/nonce/
mod.rs

1mod expirable;
2mod salted;
3mod versioned;
4
5pub use self::{
6    expirable::ExpirableNonce, salted::Salt, salted::SaltedNonce, versioned::VersionedNonce,
7};
8
9use borsh::{BorshDeserialize, BorshSerialize};
10use defuse_bitmap::{BitMap256, U248, U256};
11use defuse_map_utils::{IterableMap, Map};
12
13use crate::{DefuseError, Result};
14
15pub type Nonce = U256;
16pub type NoncePrefix = U248;
17
18/// See [permit2 nonce schema](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#nonce-schema)
19#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
20#[cfg_attr(feature = "borsh-schema", derive(::borsh::BorshSchema))]
21#[derive(Debug, Clone, Default, BorshSerialize, BorshDeserialize)]
22pub struct Nonces<T: Map<K = U248, V = U256>>(BitMap256<T>);
23
24impl<T> Nonces<T>
25where
26    T: Map<K = U248, V = U256>,
27{
28    #[inline]
29    pub const fn new(bitmap: T) -> Self {
30        Self(BitMap256::new(bitmap))
31    }
32
33    #[inline]
34    pub fn is_used(&self, n: Nonce) -> bool {
35        self.0.get_bit(n)
36    }
37
38    #[inline]
39    pub fn commit(&mut self, n: Nonce) -> Result<()> {
40        if self.0.set_bit(n) {
41            return Err(DefuseError::NonceUsed);
42        }
43
44        Ok(())
45    }
46
47    #[inline]
48    pub fn cleanup_by_prefix(&mut self, prefix: NoncePrefix) -> bool {
49        self.0.cleanup_by_prefix(prefix)
50    }
51
52    #[inline]
53    pub fn iter(&self) -> impl Iterator<Item = Nonce> + '_
54    where
55        T: IterableMap,
56    {
57        self.0.as_iter()
58    }
59}