canic_core/
guard.rs

1use crate::{
2    cdk::api::{is_controller, msg_caller},
3    ops::model::memory::state::{AppMode, AppStateOps},
4};
5use thiserror::Error as ThisError;
6
7///
8/// GuardError
9///
10/// The IC guard functions require a String to be returned, not an Error
11///
12
13#[derive(Debug, ThisError)]
14pub enum GuardError {
15    #[error("app is disabled")]
16    AppDisabled,
17
18    #[error("app is readonly")]
19    AppReadonly,
20}
21
22/// Guard for query calls; allows controllers and rejects when the app is disabled.
23pub fn guard_query() -> Result<(), String> {
24    if is_controller(&msg_caller()) {
25        return Ok(());
26    }
27
28    match AppStateOps::get_mode() {
29        AppMode::Enabled | AppMode::Readonly => Ok(()),
30        AppMode::Disabled => Err(GuardError::AppDisabled.to_string()),
31    }
32}
33
34/// Guard for update calls; allows controllers and blocks readonly/disabled states.
35pub fn guard_update() -> Result<(), String> {
36    if is_controller(&msg_caller()) {
37        return Ok(());
38    }
39
40    match AppStateOps::get_mode() {
41        AppMode::Enabled => Ok(()),
42        AppMode::Readonly => Err(GuardError::AppReadonly.to_string()),
43        AppMode::Disabled => Err(GuardError::AppDisabled.to_string()),
44    }
45}