ic_cdk/api.rs
1//! System API bindings.
2//!
3//! This module provides Rust ergonomic bindings to the system APIs.
4//!
5//! Some APIs require more advanced handling and are organized into separate modules:
6//! * For the inter-canister calls API, see the [`call`](mod@crate::call) module.
7//! * For the stable memory management API, see the .
8//! * The basic bindings are provided in this module including [`stable_size`], [`stable_grow`], [`stable_read`] and [`stable_write`].
9//! * The [`stable`](crate::stable) module provides more advanced functionalities, e.g. support for `std::io` traits.
10//!
11//! APIs that are only available for `wasm32` are not included.
12//! As a result, system APIs with a numeric postfix (indicating the data bit width) are bound to names without the postfix.
13//! For example, `ic0::msg_cycles_available128` is bound to [`msg_cycles_available`], while `ic0::msg_cycles_available` has no binding.
14//!
15//! Functions that provide bindings for a single system API method share the same name as the system API.
16//! For example, `ic0::msg_reject_code` is bound to [`msg_reject_code`].
17//!
18//! Functions that wrap multiple system API methods are named using the common prefix of the wrapped methods.
19//! For example, [`msg_arg_data`] wraps both `ic0::msg_arg_data_size` and `ic0::msg_arg_data_copy`.
20
21use candid::Principal;
22use std::{convert::TryFrom, num::NonZeroU64};
23
24#[deprecated(
25 since = "0.18.0",
26 note = "The `api::call` module is deprecated. Individual items within this module have their own deprecation notices with specific migration guidance."
27)]
28pub mod call;
29#[deprecated(
30 since = "0.18.0",
31 note = "The `api::management_canister` module is deprecated. Please use the `management_canister` and `bitcoin_canister` modules at the crate root."
32)]
33pub mod management_canister;
34#[deprecated(
35 since = "0.18.0",
36 note = "The `api::stable` module has been moved to `stable` (crate root)."
37)]
38pub mod stable;
39
40/// Gets the message argument data.
41pub fn msg_arg_data() -> Vec<u8> {
42 // SAFETY: `ic0.msg_arg_data`_size is always safe to call.
43 let len = unsafe { ic0::msg_arg_data_size() };
44 let mut buf = vec![0u8; len];
45 // SAFETY:
46 // `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.msg_arg_data_copy` with a 0-offset.
47 unsafe {
48 ic0::msg_arg_data_copy(buf.as_mut_ptr() as usize, 0, len);
49 }
50 buf
51}
52
53/// Gets the identity of the caller, which may be a canister id or a user id.
54///
55/// During canister installation or upgrade, this is the id of the user or canister requesting the installation or upgrade.
56/// During a system task (heartbeat or global timer), this is the id of the management canister.
57pub fn msg_caller() -> Principal {
58 // SAFETY: `ic0.msg_caller_size` is always safe to call.
59 let len = unsafe { ic0::msg_caller_size() };
60 let mut buf = vec![0u8; len];
61 // SAFETY: `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.msg_caller_copy` with a 0-offset.
62 unsafe {
63 ic0::msg_caller_copy(buf.as_mut_ptr() as usize, 0, len);
64 }
65 // Trust that the system always returns a valid principal.
66 Principal::try_from(&buf).unwrap()
67}
68
69/// Returns the reject code, if the current function is invoked as a reject callback.
70pub fn msg_reject_code() -> u32 {
71 // SAFETY: `ic0.msg_reject_code` is always safe to call.
72 unsafe { ic0::msg_reject_code() }
73}
74
75/// Gets the reject message.
76///
77/// This function can only be called in the reject callback.
78///
79/// Traps if there is no reject message (i.e. if reject_code is 0).
80pub fn msg_reject_msg() -> String {
81 // SAFETY: `ic0.msg_reject_msg_size` is always safe to call.
82 let len = unsafe { ic0::msg_reject_msg_size() };
83 let mut buf = vec![0u8; len];
84 // SAFETY: `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.msg_reject_msg_copy` with a 0-offset.
85 unsafe {
86 ic0::msg_reject_msg_copy(buf.as_mut_ptr() as usize, 0, len);
87 }
88 String::from_utf8_lossy(&buf).into_owned()
89}
90
91/// Gets the deadline, in nanoseconds since 1970-01-01, after which the caller might stop waiting for a response.
92///
93/// For calls to update methods with best-effort responses and their callbacks,
94/// the deadline is computed based on the time the call was made,
95/// and the `timeout_seconds` parameter provided by the caller.
96/// In such cases, the deadline value will be converted to `NonZeroU64` and wrapped in `Some`.
97/// To get the deadline value as a `u64`, call `get()` on the `NonZeroU64` value.
98///
99/// ```rust,no_run
100/// use ic_cdk::api::msg_deadline;
101/// if let Some(deadline) = msg_deadline() {
102/// let deadline_value : u64 = deadline.get();
103/// }
104/// ```
105///
106/// For other calls (ingress messages and all calls to query and composite query methods,
107/// including calls in replicated mode), a `None` is returned.
108/// Please note that the raw `msg_deadline` system API returns 0 in such cases.
109/// This function is a wrapper around the raw system API that provides more semantic information through the return type.
110pub fn msg_deadline() -> Option<NonZeroU64> {
111 // SAFETY: `ic0.msg_deadline` is always safe to call.
112 let nano_seconds = unsafe { ic0::msg_deadline() };
113 match nano_seconds {
114 0 => None,
115 _ => Some(NonZeroU64::new(nano_seconds).unwrap()),
116 }
117}
118
119/// Replies to the sender with the data.
120pub fn msg_reply<T: AsRef<[u8]>>(data: T) {
121 let buf = data.as_ref();
122 if !buf.is_empty() {
123 // SAFETY: `buf`, being &[u8], is a readable sequence of bytes, and therefore valid to pass to `ic0.msg_reply`.
124 unsafe { ic0::msg_reply_data_append(buf.as_ptr() as usize, buf.len()) }
125 };
126 // SAFETY: `ic0.msg_reply` is always safe to call.
127 unsafe { ic0::msg_reply() };
128}
129
130/// Rejects the call with a diagnostic message.
131pub fn msg_reject<T: AsRef<str>>(message: T) {
132 let buf = message.as_ref();
133 // SAFETY: `buf`, being &str, is a readable sequence of UTF8 bytes and therefore can be passed to `ic0.msg_reject`.
134 unsafe {
135 ic0::msg_reject(buf.as_ptr() as usize, buf.len());
136 }
137}
138
139/// Gets the number of cycles transferred by the caller of the current call, still available in this message.
140pub fn msg_cycles_available() -> u128 {
141 let mut dst = 0u128;
142 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.msg_cycles_available128`.
143 unsafe {
144 ic0::msg_cycles_available128(&mut dst as *mut u128 as usize);
145 }
146 dst
147}
148
149/// Gets the amount of cycles that came back with the response as a refund
150///
151/// This function can only be used in a callback handler (reply or reject).
152/// The refund has already been added to the canister balance automatically.
153pub fn msg_cycles_refunded() -> u128 {
154 let mut dst = 0u128;
155 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.msg_cycles_refunded128`.
156 unsafe {
157 ic0::msg_cycles_refunded128(&mut dst as *mut u128 as usize);
158 }
159 dst
160}
161
162/// Moves cycles from the call to the canister balance.
163///
164/// The actual amount moved will be returned.
165pub fn msg_cycles_accept(max_amount: u128) -> u128 {
166 let high = (max_amount >> 64) as u64;
167 let low = (max_amount & u64::MAX as u128) as u64;
168 let mut dst = 0u128;
169 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.msg_cycles_accept128`.
170 unsafe {
171 ic0::msg_cycles_accept128(high, low, &mut dst as *mut u128 as usize);
172 }
173 dst
174}
175
176/// Burns cycles from the canister.
177///
178/// Returns the amount of cycles that were actually burned.
179pub fn cycles_burn(amount: u128) -> u128 {
180 let amount_high = (amount >> 64) as u64;
181 let amount_low = (amount & u64::MAX as u128) as u64;
182 let mut dst = 0u128;
183 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cycles_burn128`.
184 unsafe { ic0::cycles_burn128(amount_high, amount_low, &mut dst as *mut u128 as usize) }
185 dst
186}
187
188/// Gets canister's own identity.
189pub fn canister_self() -> Principal {
190 // SAFETY: `ic0.canister_self_size` is always safe to call.
191 let len = unsafe { ic0::canister_self_size() };
192 let mut buf = vec![0u8; len];
193 // SAFETY: `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.canister_self_copy` with a 0-offset.
194 unsafe {
195 ic0::canister_self_copy(buf.as_mut_ptr() as usize, 0, len);
196 }
197 // Trust that the system always returns a valid principal.
198 Principal::try_from(&buf).unwrap()
199}
200
201/// Gets the current cycle balance of the canister.
202pub fn canister_cycle_balance() -> u128 {
203 let mut dst = 0u128;
204 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.canister_cycle_balance128`.
205 unsafe { ic0::canister_cycle_balance128(&mut dst as *mut u128 as usize) }
206 dst
207}
208
209/// Gets the current amount of cycles that is available for spending in calls and execution.
210pub fn canister_liquid_cycle_balance() -> u128 {
211 let mut dst = 0u128;
212 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.canister_liquid_cycle_balance128`.
213 unsafe { ic0::canister_liquid_cycle_balance128(&mut dst as *mut u128 as usize) }
214 dst
215}
216
217/// Gets the status of the canister.
218///
219/// The status is one of the following:
220///.- 1: Running
221///.- 2: Stopping
222///.- 3: Stopped
223pub fn canister_status() -> CanisterStatusCode {
224 // SAFETY: `ic0.canister_status` is always safe to call.
225 unsafe { ic0::canister_status() }.into()
226}
227
228/// The status of a canister.
229///
230/// See [Canister status](https://internetcomputer.org/docs/current/references/ic-interface-spec/#system-api-canister-status).
231#[derive(Debug, PartialEq, Eq, Clone, Copy)]
232#[repr(u32)]
233pub enum CanisterStatusCode {
234 /// Running.
235 Running = 1,
236 /// Stopping.
237 Stopping = 2,
238 /// Stopped.
239 Stopped = 3,
240 /// A status code that is not recognized by this library.
241 Unrecognized(u32),
242}
243
244impl From<u32> for CanisterStatusCode {
245 fn from(value: u32) -> Self {
246 match value {
247 1 => Self::Running,
248 2 => Self::Stopping,
249 3 => Self::Stopped,
250 _ => Self::Unrecognized(value),
251 }
252 }
253}
254
255impl From<CanisterStatusCode> for u32 {
256 fn from(value: CanisterStatusCode) -> Self {
257 match value {
258 CanisterStatusCode::Running => 1,
259 CanisterStatusCode::Stopping => 2,
260 CanisterStatusCode::Stopped => 3,
261 CanisterStatusCode::Unrecognized(value) => value,
262 }
263 }
264}
265
266impl PartialEq<u32> for CanisterStatusCode {
267 fn eq(&self, other: &u32) -> bool {
268 let self_as_u32: u32 = (*self).into();
269 self_as_u32 == *other
270 }
271}
272
273/// Gets the canister version.
274///
275/// See [Canister version](https://internetcomputer.org/docs/current/references/ic-interface-spec/#system-api-canister-version).
276pub fn canister_version() -> u64 {
277 // SAFETY: `ic0.canister_version` is always safe to call.
278 unsafe { ic0::canister_version() }
279}
280
281/// Gets the ID of the subnet on which the canister is running.
282pub fn subnet_self() -> Principal {
283 // SAFETY: `ic0.subnet_self_size` is always safe to call.
284 let len = unsafe { ic0::subnet_self_size() };
285 let mut buf = vec![0u8; len];
286 // SAFETY: `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.subnet_self_copy` with a 0-offset.
287 unsafe {
288 ic0::subnet_self_copy(buf.as_mut_ptr() as usize, 0, len);
289 }
290 // Trust that the system always returns a valid principal.
291 Principal::try_from(&buf).unwrap()
292}
293
294/// Gets the name of the method to be inspected.
295///
296/// This function is only available in the `canister_inspect_message` context.
297pub fn msg_method_name() -> String {
298 // SAFETY: `ic0.msg_method_name_size` is always safe to call.
299 let len: u32 = unsafe { ic0::msg_method_name_size() as u32 };
300 let mut buf = vec![0u8; len as usize];
301 // SAFETY: `buf` is a mutable reference to a `len`-byte buffer, it is safe to be passed to `ic0.msg_method_name_copy` with a 0-offset.
302 unsafe {
303 ic0::msg_method_name_copy(buf.as_mut_ptr() as usize, 0, len as usize);
304 }
305 String::from_utf8_lossy(&buf).into_owned()
306}
307
308/// Accepts the message in `canister_inspect_message`.
309///
310/// This function is only available in the `canister_inspect_message` context.
311/// This function traps if invoked twice.
312pub fn accept_message() {
313 // SAFETY: `ic0.accept_message` is always safe to call.
314 unsafe { ic0::accept_message() }
315}
316
317/// Gets the current size of the stable memory (in WebAssembly pages).
318///
319/// One WebAssembly page is 64KiB.
320pub fn stable_size() -> u64 {
321 // SAFETY: `ic0.stable64_size` is always safe to call.
322 unsafe { ic0::stable64_size() }
323}
324
325/// Attempts to grow the stable memory by `new_pages` many pages containing zeroes.
326///
327/// One WebAssembly page is 64KiB.
328///
329/// If successful, returns the previous size of the memory (in pages).
330/// Otherwise, returns `u64::MAX`.
331pub fn stable_grow(new_pages: u64) -> u64 {
332 // SAFETY: `ic0.stable64_grow` is always safe to call.
333 unsafe { ic0::stable64_grow(new_pages) }
334}
335
336/// Writes data to the stable memory location specified by an offset.
337///
338/// # Warning
339/// This will panic if `offset + buf.len()` exceeds the current size of stable memory.
340/// Call [`stable_grow`] to request more stable memory if needed.
341pub fn stable_write(offset: u64, buf: &[u8]) {
342 // SAFETY: `buf`, being &[u8], is a readable sequence of bytes, and therefore valid to pass to `ic0.stable64_write`.
343 unsafe {
344 ic0::stable64_write(offset, buf.as_ptr() as u64, buf.len() as u64);
345 }
346}
347
348/// Reads data from the stable memory location specified by an offset.
349///
350/// # Warning
351/// This will panic if `offset + buf.len()` exceeds the current size of stable memory.
352pub fn stable_read(offset: u64, buf: &mut [u8]) {
353 // SAFETY: `buf`, being &mut [u8], is a writable sequence of bytes, and therefore valid to pass to ic0.stable64_read.
354 unsafe {
355 ic0::stable64_read(buf.as_ptr() as u64, offset, buf.len() as u64);
356 }
357}
358
359/// Sets the certified data of this canister.
360///
361/// Canisters can store up to 32 bytes of data that is certified by
362/// the system on a regular basis. One can call [data_certificate]
363/// function from a query call to get a certificate authenticating the
364/// value set by calling this function.
365///
366/// This function can only be called from the following contexts:
367///. - "canister_init", "canister_pre_upgrade" and "canister_post_upgrade"
368/// hooks.
369///. - "canister_update" calls.
370///. - reply or reject callbacks.
371///
372/// # Panics
373///
374///.- This function traps if data.len() > 32.
375///.- This function traps if it's called from an illegal context
376/// (e.g., from a query call).
377pub fn certified_data_set<T: AsRef<[u8]>>(data: T) {
378 let buf = data.as_ref();
379 // SAFETY: `buf` is a slice ref, its pointer and length are valid to pass to ic0.certified_data_set.
380 unsafe { ic0::certified_data_set(buf.as_ptr() as usize, buf.len()) }
381}
382
383/// When called from a query call, returns the data certificate authenticating
384/// certified_data set by this canister.
385///
386/// Returns `None` if called not from a query call.
387pub fn data_certificate() -> Option<Vec<u8>> {
388 // SAFETY: ic0.data_certificate_present is always safe to call.
389 if unsafe { ic0::data_certificate_present() } == 0 {
390 return None;
391 }
392 // SAFETY: ic0.data_certificate_size is always safe to call.
393 let n = unsafe { ic0::data_certificate_size() };
394 let mut buf = vec![0u8; n];
395 // SAFETY: Because `buf` is mutable and allocated to `n` bytes, it is valid to receive from ic0.data_certificate_bytes with no offset
396 unsafe {
397 ic0::data_certificate_copy(buf.as_mut_ptr() as usize, 0, n);
398 }
399 Some(buf)
400}
401
402/// Gets current timestamp, in nanoseconds since the epoch (1970-01-01)
403pub fn time() -> u64 {
404 // SAFETY: ic0.time is always safe to call.
405 unsafe { ic0::time() }
406}
407
408/// Sets global timer.
409///
410/// The canister can set a global timer to make the system
411/// schedule a call to the exported `canister_global_timer`
412/// Wasm method after the specified time.
413/// The time must be provided as nanoseconds since 1970-01-01.
414///
415/// The function returns the previous value of the timer.
416/// If no timer is set before invoking the function, then the function returns zero.
417///
418/// Passing zero as an argument to the function deactivates the timer and thus
419/// prevents the system from scheduling calls to the canister's `canister_global_timer` Wasm method.
420pub fn global_timer_set(timestamp: u64) -> u64 {
421 // SAFETY: ic0.global_timer_set is always safe to call.
422 unsafe { ic0::global_timer_set(timestamp) }
423}
424
425/// Gets the value of specified performance counter.
426///
427/// See [`PerformanceCounterType`] for available counter types.
428#[inline]
429pub fn performance_counter(counter_type: impl Into<PerformanceCounterType>) -> u64 {
430 let counter_type: u32 = counter_type.into().into();
431 // SAFETY: ic0.performance_counter is always safe to call.
432 unsafe { ic0::performance_counter(counter_type) }
433}
434
435/// The type of performance counter.
436#[derive(Debug, PartialEq, Eq, Clone, Copy)]
437#[repr(u32)]
438pub enum PerformanceCounterType {
439 /// Current execution instruction counter.
440 ///
441 /// The number of WebAssembly instructions the canister has executed
442 /// since the beginning of the current Message execution.
443 InstructionCounter,
444 /// Call context instruction counter
445 ///
446 /// The number of WebAssembly instructions the canister has executed
447 /// within the call context of the current Message execution
448 /// since Call context creation.
449 /// The counter monotonically increases across all message executions
450 /// in the call context until the corresponding call context is removed.
451 CallContextInstructionCounter,
452 /// A performance counter type that is not recognized by this library.
453 Unrecognized(u32),
454}
455
456impl From<u32> for PerformanceCounterType {
457 fn from(value: u32) -> Self {
458 match value {
459 0 => Self::InstructionCounter,
460 1 => Self::CallContextInstructionCounter,
461 _ => Self::Unrecognized(value),
462 }
463 }
464}
465
466impl From<PerformanceCounterType> for u32 {
467 fn from(value: PerformanceCounterType) -> Self {
468 match value {
469 PerformanceCounterType::InstructionCounter => 0,
470 PerformanceCounterType::CallContextInstructionCounter => 1,
471 PerformanceCounterType::Unrecognized(value) => value,
472 }
473 }
474}
475
476impl PartialEq<u32> for PerformanceCounterType {
477 fn eq(&self, other: &u32) -> bool {
478 let self_as_u32: u32 = (*self).into();
479 self_as_u32 == *other
480 }
481}
482
483/// Returns the number of instructions that the canister executed since the last [entry
484/// point](https://internetcomputer.org/docs/current/references/ic-interface-spec/#entry-points).
485#[inline]
486pub fn instruction_counter() -> u64 {
487 performance_counter(0)
488}
489
490/// Returns the number of WebAssembly instructions the canister has executed
491/// within the call context of the current Message execution since
492/// Call context creation.
493///
494/// The counter monotonically increases across all message executions
495/// in the call context until the corresponding call context is removed.
496#[inline]
497pub fn call_context_instruction_counter() -> u64 {
498 performance_counter(1)
499}
500
501/// Determines if a Principal is a controller of the canister.
502pub fn is_controller(principal: &Principal) -> bool {
503 let slice = principal.as_slice();
504 // SAFETY: `principal.as_bytes()`, being `&[u8]`, is a readable sequence of bytes and therefore safe to pass to `ic0.is_controller`.
505 unsafe { ic0::is_controller(slice.as_ptr() as usize, slice.len()) != 0 }
506}
507
508/// Checks if in replicated execution.
509///
510/// The canister can check whether it is currently running in replicated or non replicated execution.
511pub fn in_replicated_execution() -> bool {
512 // SAFETY: `ic0.in_replicated_execution` is always safe to call.
513 match unsafe { ic0::in_replicated_execution() } {
514 0 => false,
515 1 => true,
516 _ => unreachable!(),
517 }
518}
519
520/// Gets the amount of cycles that a canister needs to be above the freezing threshold in order to successfully make an inter-canister call.
521pub fn cost_call(method_name_size: u64, payload_size: u64) -> u128 {
522 let mut dst = 0u128;
523 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_call`.
524 unsafe {
525 ic0::cost_call(
526 method_name_size,
527 payload_size,
528 &mut dst as *mut u128 as usize,
529 )
530 }
531 dst
532}
533
534/// Gets the cycle cost of the Management canister method [`creating_canister`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-create_canister).
535///
536/// # Note
537///
538/// [`create_canister`](crate::management_canister::create_canister) and
539/// [`create_canister_with_extra_cycles`](crate::management_canister::create_canister_with_extra_cycles)
540/// invoke this function inside and attach the required cycles to the call.
541pub fn cost_create_canister() -> u128 {
542 let mut dst = 0u128;
543 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_create_canister`.
544 unsafe { ic0::cost_create_canister(&mut dst as *mut u128 as usize) }
545 dst
546}
547
548/// Gets the cycle cost of the Management canister method [`http_request`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-http_request).
549///
550/// # Note
551///
552/// [`http_request`](crate::management_canister::http_request) and [`http_request_with_closure`](crate::management_canister::http_request_with_closure)
553/// invoke this function inside and attach the required cycles to the call.
554pub fn cost_http_request(request_size: u64, max_res_bytes: u64) -> u128 {
555 let mut dst = 0u128;
556 // SAFETY: `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_http_request`.
557 unsafe { ic0::cost_http_request(request_size, max_res_bytes, &mut dst as *mut u128 as usize) }
558 dst
559}
560
561/// The error type for [`cost_sign_with_ecdsa`] and [`cost_sign_with_schnorr`].
562#[derive(thiserror::Error, Debug, Clone)]
563pub enum SignCostError {
564 /// The ECDSA/vetKD curve or Schnorr algorithm is invalid.
565 #[error("invalid curve or algorithm")]
566 InvalidCurveOrAlgorithm,
567
568 /// The key name is invalid for the provided curve or algorithm.
569 #[error("invalid key name")]
570 InvalidKeyName,
571 /// Unrecognized error.
572 ///
573 /// This error is returned when the System API returns an unrecognized error code.
574 /// Please report to ic-cdk maintainers.
575 #[error("unrecognized error: {0}")]
576 UnrecognizedError(u32),
577}
578
579/// Helper function to handle the result of a signature cost function.
580fn sign_cost_result(dst: u128, code: u32) -> Result<u128, SignCostError> {
581 match code {
582 0 => Ok(dst),
583 1 => Err(SignCostError::InvalidCurveOrAlgorithm),
584 2 => Err(SignCostError::InvalidKeyName),
585 _ => Err(SignCostError::UnrecognizedError(code)),
586 }
587}
588
589/// Gets the cycle cost of the Management canister method [`sign_with_ecdsa`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-sign_with_ecdsa).
590///
591/// # Note
592///
593/// Alternatively, [`management_canister::cost_sign_with_ecdsa`](crate::management_canister::cost_sign_with_ecdsa) provides a higher-level API that wraps this function.
594///
595/// # Errors
596///
597/// This function will return an error if the `key_name` or the `ecdsa_curve` is invalid.
598/// The error type [`SignCostError`] provides more information about the reason of the error.
599pub fn cost_sign_with_ecdsa<T: AsRef<str>>(
600 key_name: T,
601 ecdsa_curve: u32,
602) -> Result<u128, SignCostError> {
603 let buf = key_name.as_ref();
604 let mut dst = 0u128;
605 // SAFETY:
606 // `buf`, being &str, is a readable sequence of UTF8 bytes and therefore can be passed to `ic0.cost_sign_with_ecdsa`.
607 // `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_sign_with_ecdsa`.
608 let code = unsafe {
609 ic0::cost_sign_with_ecdsa(
610 buf.as_ptr() as usize,
611 buf.len(),
612 ecdsa_curve,
613 &mut dst as *mut u128 as usize,
614 )
615 };
616 sign_cost_result(dst, code)
617}
618
619/// Gets the cycle cost of the Management canister method [`sign_with_schnorr`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-sign_with_schnorr).
620///
621/// # Note
622///
623/// Alternatively, [`management_canister::cost_sign_with_schnorr`](crate::management_canister::cost_sign_with_schnorr) provides a higher-level API that wraps this function.
624///
625/// # Errors
626///
627/// This function will return an error if the `key_name` or the `algorithm` is invalid.
628/// The error type [`SignCostError`] provides more information about the reason of the error.
629pub fn cost_sign_with_schnorr<T: AsRef<str>>(
630 key_name: T,
631 algorithm: u32,
632) -> Result<u128, SignCostError> {
633 let buf = key_name.as_ref();
634 let mut dst = 0u128;
635 // SAFETY:
636 // `buf`, being &str, is a readable sequence of UTF8 bytes and therefore can be passed to `ic0.cost_sign_with_schnorr`.
637 // `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_sign_with_schnorr`.
638 let code = unsafe {
639 ic0::cost_sign_with_schnorr(
640 buf.as_ptr() as usize,
641 buf.len(),
642 algorithm,
643 &mut dst as *mut u128 as usize,
644 )
645 };
646 sign_cost_result(dst, code)
647}
648
649/// Gets the cycle cost of the Management canister method [`vetkd_derive_key`](https://github.com/dfinity/portal/pull/3763).
650///
651/// Later, the description will be available in [the interface spec](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-vetkd_derive_key).
652///
653/// # Note
654///
655/// Alternatively, [`management_canister::cost_vetkd_derive_key`](crate::management_canister::cost_vetkd_derive_key) provides a higher-level API that wraps this function.
656///
657/// # Errors
658///
659/// This function will return an error if the `key_name` or the `vetkd_curve` is invalid.
660/// The error type [`SignCostError`] provides more information about the reason of the error.
661pub fn cost_vetkd_derive_key<T: AsRef<str>>(
662 key_name: T,
663 vetkd_curve: u32,
664) -> Result<u128, SignCostError> {
665 let buf = key_name.as_ref();
666 let mut dst = 0u128;
667 // SAFETY:
668 // `buf`, being &str, is a readable sequence of UTF8 bytes and therefore can be passed to `ic0.cost_vetkd_derive_key`.
669 // `dst` is a mutable reference to a 16-byte buffer, which is the expected size for `ic0.cost_vetkd_derive_key`.
670 let code = unsafe {
671 ic0::cost_vetkd_derive_key(
672 buf.as_ptr() as usize,
673 buf.len(),
674 vetkd_curve,
675 &mut dst as *mut u128 as usize,
676 )
677 };
678 sign_cost_result(dst, code)
679}
680
681/// Emits textual trace messages.
682///
683/// On the "real" network, these do not do anything.
684///
685/// When executing in an environment that supports debugging, this copies out the data
686/// and logs, prints or stores it in an environment-appropriate way.
687pub fn debug_print<T: AsRef<str>>(data: T) {
688 let buf = data.as_ref();
689 // SAFETY: `buf` is a readable sequence of bytes and therefore can be passed to ic0.debug_print.
690 unsafe {
691 ic0::debug_print(buf.as_ptr() as usize, buf.len());
692 }
693}
694
695/// Traps with the given message.
696///
697/// The environment may copy out the data and log, print or store it in an environment-appropriate way,
698/// or include it in system-generated reject messages where appropriate.
699pub fn trap<T: AsRef<str>>(data: T) -> ! {
700 let buf = data.as_ref();
701 // SAFETY: `buf` is a readable sequence of bytes and therefore can be passed to ic0.trap.
702 unsafe {
703 ic0::trap(buf.as_ptr() as usize, buf.len());
704 }
705 unreachable!()
706}
707
708// # Deprecated API bindings
709//
710// The following functions are deprecated and will be removed in the future.
711// They are kept here for compatibility with existing code.
712
713/// Prints the given message.
714#[deprecated(since = "0.18.0", note = "Use `debug_print` instead")]
715pub fn print<S: std::convert::AsRef<str>>(s: S) {
716 let s = s.as_ref();
717 // SAFETY: `s`, being &str, is a readable sequence of bytes and therefore can be passed to ic0.debug_print.
718 unsafe {
719 ic0::debug_print(s.as_ptr() as usize, s.len());
720 }
721}
722
723/// Returns the caller of the current call.
724#[deprecated(since = "0.18.0", note = "Use `msg_caller` instead")]
725pub fn caller() -> Principal {
726 // SAFETY: ic0.msg_caller_size is always safe to call.
727 let len = unsafe { ic0::msg_caller_size() };
728 let mut bytes = vec![0u8; len];
729 // SAFETY: Because `bytes` is mutable, and allocated to `len` bytes, it is safe to be passed to `ic0.msg_caller_copy` with a 0-offset.
730 unsafe {
731 ic0::msg_caller_copy(bytes.as_mut_ptr() as usize, 0, len);
732 }
733 Principal::try_from(&bytes).unwrap()
734}
735
736/// Returns the canister id as a blob.
737#[deprecated(since = "0.18.0", note = "Use `canister_self` instead")]
738pub fn id() -> Principal {
739 // SAFETY: ic0.canister_self_size is always safe to call.
740 let len = unsafe { ic0::canister_self_size() };
741 let mut bytes = vec![0u8; len];
742 // SAFETY: Because `bytes` is mutable, and allocated to `len` bytes, it is safe to be passed to `ic0.canister_self_copy` with a 0-offset.
743 unsafe {
744 ic0::canister_self_copy(bytes.as_mut_ptr() as usize, 0, len);
745 }
746 Principal::try_from(&bytes).unwrap()
747}
748
749/// Gets the amount of funds available in the canister.
750#[deprecated(since = "0.18.0", note = "Use `canister_cycle_balance` instead")]
751pub fn canister_balance128() -> u128 {
752 let mut dst = 0u128;
753 // SAFETY: dst is writable and the size expected by ic0.canister_cycle_balance128.
754 unsafe { ic0::canister_cycle_balance128(&mut dst as *mut u128 as usize) }
755 dst
756}
757
758/// Sets the certified data of this canister.
759///
760/// Canisters can store up to 32 bytes of data that is certified by
761/// the system on a regular basis. One can call [data_certificate]
762/// function from a query call to get a certificate authenticating the
763/// value set by calling this function.
764///
765/// This function can only be called from the following contexts:
766///. - "canister_init", "canister_pre_upgrade" and "canister_post_upgrade"
767/// hooks.
768///. - "canister_update" calls.
769///. - reply or reject callbacks.
770///
771/// # Panics
772///
773///.- This function traps if data.len() > 32.
774///.- This function traps if it's called from an illegal context
775/// (e.g., from a query call).
776#[deprecated(since = "0.18.0", note = "Use `certified_data_set` instead")]
777pub fn set_certified_data(data: &[u8]) {
778 // SAFETY: because data is a slice ref, its pointer and length are valid to pass to ic0.certified_data_set.
779 unsafe { ic0::certified_data_set(data.as_ptr() as usize, data.len()) }
780}
781
782/// Sets global timer.
783///
784/// The canister can set a global timer to make the system
785/// schedule a call to the exported canister_global_timer
786/// Wasm method after the specified time.
787/// The time must be provided as nanoseconds since 1970-01-01.
788///
789/// The function returns the previous value of the timer.
790/// If no timer is set before invoking the function, then the function returns zero.
791///
792/// Passing zero as an argument to the function deactivates the timer and thus
793/// prevents the system from scheduling calls to the canister's canister_global_timer Wasm method.
794#[deprecated(since = "0.18.0", note = "Use `global_timer_set` instead")]
795pub fn set_global_timer(timestamp: u64) -> u64 {
796 // SAFETY: ic0.global_timer_set is always safe to call.
797 unsafe { ic0::global_timer_set(timestamp) }
798}