delta_domain_sdk/views/
domain.rs

1use base_sdk::{
2    core::Nonce,
3    vaults::{
4        OwnerId,
5        Vault,
6    },
7};
8use domain_runtime::{
9    ports::DbQueriesPort,
10    storage::{
11        DomainVaultColumnFamily,
12        FinalizedVaultColumnFamily,
13        NonceColumnFamily,
14    },
15};
16use snafu::{
17    ResultExt,
18    Snafu,
19};
20use storage::{
21    column_family::StorageQuery,
22    database::StorageError,
23};
24
25/// Errors occurring in the [DomainStateView]
26#[derive(Debug, Snafu)]
27pub enum Error {
28    /// Error when reading from storage
29    #[snafu(display("Error while reading from storage: {source}"))]
30    Storage {
31        /// The underlying storage error
32        source: StorageError,
33    },
34}
35
36/// Helper to access the domain state view of the vaults on this shard
37#[derive(Debug, Clone)]
38pub struct DomainStateView<Db> {
39    pub(crate) db: Db,
40}
41
42impl<Db> DomainStateView<Db> {
43    pub(crate) const fn new(db: Db) -> Self {
44        Self { db }
45    }
46}
47
48impl<Db> DomainStateView<Db>
49where
50    Db: DbQueriesPort,
51{
52    /// Get the domain state view of the [Vault] of `owner`.
53    ///
54    /// The domain state view is potentially the ahead of the finalized state.
55    /// All verifiables applied to the domain are already visible on the vault.
56    ///
57    /// # Parameters
58    ///
59    /// * `owner` - The ID of the vault owner
60    ///
61    /// # Returns
62    ///
63    /// * `Ok(Some(vault))` - If the vault exists (in domain view or finalized state)
64    /// * `Ok(None)` - If no vault exists for the given owner (not even in finalized state)
65    /// * `Err(error)` - If a storage error occurred
66    pub fn get_vault(&self, owner: &OwnerId) -> Result<Option<Vault>, Error> {
67        StorageQuery::<DomainVaultColumnFamily>::get_value(&self.db, owner)
68            .context(StorageSnafu)?
69            .map_or_else(
70                || StorageQuery::<FinalizedVaultColumnFamily>::get_value(&self.db, owner),
71                |v| Ok(Some(v)),
72            )
73            .context(StorageSnafu)
74    }
75
76    /// Get the next nonce for the local vault at `owner`.
77    ///
78    /// The next verifiable to debit the vault of `owner` must use the returned
79    /// nonce in order to be valid.
80    ///
81    /// # Parameters
82    ///
83    /// * `owner` - The ID of the vault owner
84    pub fn next_nonce(&self, owner: &OwnerId) -> Result<Nonce, Error> {
85        let nonce_opt =
86            StorageQuery::<NonceColumnFamily>::get_value(&self.db, owner).context(StorageSnafu)?;
87        Ok(nonce_opt.unwrap_or_default() + 1)
88    }
89}