defuse_core/nonce/
mod.rs

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