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 network.
38pub fn query_cycle_balance(
39    icp: &IcpCli,
40    canister_id: &str,
41    network: &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(network)) {
46        return query_local_cycle_balance(network, canister_id, icp_root).map_err(Into::into);
47    }
48
49    let output = icp.canister_query_output_with_candid(
50        canister_id,
51        protocol::CANIC_CYCLE_BALANCE,
52        Some(ICP_JSON_OUTPUT),
53        candid_path,
54    )?;
55    decode_json_result_response(&output).map_err(Into::into)
56}
57
58fn query_local_cycle_balance(
59    network: &str,
60    canister_id: &str,
61    icp_root: Option<&Path>,
62) -> Result<u128, ReplicaQueryError> {
63    icp_root.map_or_else(
64        || replica_query::query_cycle_balance(Some(network), canister_id),
65        |root| replica_query::query_cycle_balance_from_root(Some(network), canister_id, root),
66    )
67}