Skip to main content

canic_host/cycle_balance/
mod.rs

1//! Module: cycle_balance
2//!
3//! Responsibility: query the maintained Canic cycle-balance endpoint.
4//! Does not own: cycle accounting, local replica transport, or report aggregation.
5//! Boundary: decodes the canonical typed endpoint result into a host balance.
6
7#[cfg(test)]
8mod tests;
9
10use crate::{
11    icp::{IcpCli, IcpCommandError, IcpJsonResponseError, decode_json_result_response},
12    replica_query::{self, ReplicaQueryError},
13};
14use std::path::Path;
15use thiserror::Error as ThisError;
16
17use canic_core::protocol;
18
19const ICP_JSON_OUTPUT: &str = "json";
20
21///
22/// CycleBalanceQueryError
23///
24
25#[derive(Debug, ThisError)]
26pub enum CycleBalanceQueryError {
27    #[error(transparent)]
28    Icp(#[from] IcpCommandError),
29
30    #[error(transparent)]
31    Replica(#[from] ReplicaQueryError),
32
33    #[error(transparent)]
34    Response(#[from] IcpJsonResponseError),
35}
36
37/// Query `canic_cycle_balance` through the transport selected by the environment.
38pub fn query_cycle_balance(
39    icp: &IcpCli,
40    canister_id: &str,
41    environment: &str,
42    icp_root: Option<&Path>,
43    candid_path: Option<&Path>,
44) -> Result<u128, CycleBalanceQueryError> {
45    if replica_query::should_use_local_replica_query(Some(environment)) {
46        return replica_query::query_cycle_balance(Some(environment), canister_id, icp_root)
47            .map_err(Into::into);
48    }
49
50    let output = icp.canister_query_output_with_candid(
51        canister_id,
52        protocol::CANIC_CYCLE_BALANCE,
53        Some(ICP_JSON_OUTPUT),
54        candid_path,
55    )?;
56    decode_json_result_response(&output).map_err(Into::into)
57}