junobuild_shared/ic/api.rs
1use candid::Principal;
2
3#[cfg(target_arch = "wasm32")]
4use ic_cdk::api::{
5 canister_self, debug_print, is_controller as ic_is_controller, msg_caller, time as ic_time,
6};
7
8/// Returns the **principal** of the current module.
9///
10/// This is a shorthand for [`ic_cdk::api::canister_self`],
11/// kept for readability and to align with the concise naming convention
12/// used our helpers.
13///
14/// # Example
15/// ```ignore
16/// let current_module = ic::api::id();
17/// ```
18#[cfg(target_arch = "wasm32")]
19pub fn id() -> Principal {
20 canister_self()
21}
22
23#[cfg(not(target_arch = "wasm32"))]
24pub fn id() -> Principal {
25 Principal::from_text("ck4tp-3iaaa-aaaal-ab7da-cai").unwrap()
26}
27
28/// Returns the **principal** of the caller that invoked the current module.
29///
30/// This is a shorthand for [`ic_cdk::api::msg_caller`],
31/// kept for readability and to align with the concise naming convention
32/// used our helpers.
33///
34/// # Example
35/// ```ignore
36/// let user = ic::api::caller();
37/// ```
38#[cfg(target_arch = "wasm32")]
39pub fn caller() -> Principal {
40 msg_caller()
41}
42
43#[cfg(not(target_arch = "wasm32"))]
44pub fn caller() -> Principal {
45 Principal::from_text("bphsl-fvy2d-emlkg-wuhfe-fylew-25w4a-vpdm3-ajsos-ao4x5-sxn5j-jqe").unwrap()
46}
47
48/// Prints a debug message to the Juno runtime logs.
49///
50/// This is a shorthand for [`ic_cdk::api::debug_print`],
51/// kept for readability and to align with the concise naming convention
52/// used in our helpers.
53///
54/// In the Juno Console, these messages appear in the logs of the current module.
55///
56/// # Example
57/// ```ignore
58/// ic::api::print("Satellite started successfully");
59/// ```
60#[cfg(target_arch = "wasm32")]
61pub fn print<S: AsRef<str>>(s: S) {
62 debug_print(s)
63}
64
65#[cfg(not(target_arch = "wasm32"))]
66pub fn print<S: AsRef<str>>(_s: S) {
67 // Noop
68}
69
70/// Returns the current timestamp in nanoseconds since the UNIX epoch.
71///
72/// This is a shorthand for [`ic_cdk::api::time`] useful for
73/// test in wasm32 environment.
74///
75/// # Example
76/// ```ignore
77/// let now = ic::api::time();
78/// ```
79#[cfg(target_arch = "wasm32")]
80pub fn time() -> u64 {
81 ic_time()
82}
83
84#[cfg(not(target_arch = "wasm32"))]
85pub fn time() -> u64 {
86 use std::time::{SystemTime, UNIX_EPOCH};
87 SystemTime::now()
88 .duration_since(UNIX_EPOCH)
89 .unwrap()
90 .as_nanos() as u64
91}
92
93#[cfg(target_arch = "wasm32")]
94pub fn is_canister_controller(principal: &Principal) -> bool {
95 ic_is_controller(principal)
96}
97
98#[cfg(not(target_arch = "wasm32"))]
99pub fn is_canister_controller(principal: &Principal) -> bool {
100 // For tests, return true for specific test principals or implement mock logic
101 // This is a simple mock - adjust based on your needs
102 *principal == Principal::from_text("ck4tp-3iaaa-aaaal-ab7da-cai").unwrap()
103}