use crate::cli::clap::parsed_options;
use crate::cli::common::{
COLLECTION_MODE_LIVE, CurrentUnixSecsError, SourceOutputOptions, collection_help,
current_unix_secs, write_text_or_json,
};
use crate::presentation::system::cmc::cmc_cycles_report_text;
use crate::presentation::system::cmc::cmc_xdr_report_text;
use clap::{ArgMatches, Command as ClapCommand, Subcommand};
use ic_query::report::CollectionSourceRequest;
use ic_query::system::cmc::CmcHostError;
use ic_query::system::cmc::DEFAULT_CMC_SOURCE_ENDPOINT;
use ic_query::system::cmc::build_cmc_cycles_report;
use ic_query::system::cmc::build_cmc_xdr_report;
use serde::Serialize;
use std::io;
use thiserror::Error as ThisError;
const SYSTEM_HELP_AFTER: &str = "\
Examples:
icq system xdr
icq system cycles";
const XDR_HELP_AFTER: &str = "\
Examples:
icq system xdr
icq system xdr --json";
const CYCLES_HELP_AFTER: &str = "\
Examples:
icq system cycles
icq system cycles --json";
#[derive(Debug, ThisError)]
pub enum SystemCommandError {
#[error("{0}")]
Usage(String),
#[error(transparent)]
CmcHost(#[from] CmcHostError),
#[error(transparent)]
Clock(#[from] CurrentUnixSecsError),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
}
#[derive(Subcommand)]
#[command(about = "Inspect native IC system-canister metadata", long_about = None, after_help = SYSTEM_HELP_AFTER)]
enum SystemCommand {
#[command(about = "Show the certified CMC ICP/XDR conversion rate", long_about = None, after_help = collection_help(COLLECTION_MODE_LIVE, XDR_HELP_AFTER))]
Xdr(SourceOutputOptions),
#[command(about = "Show cycles conversions derived from the certified CMC rate", long_about = None, after_help = collection_help(COLLECTION_MODE_LIVE, CYCLES_HELP_AFTER))]
Cycles(SourceOutputOptions),
}
pub async fn run_matches(matches: &ArgMatches, network: &str) -> Result<(), SystemCommandError> {
match parsed_options::<SystemCommand>(matches) {
SystemCommand::Xdr(options) => {
run_report(options, network, build_cmc_xdr_report, cmc_xdr_report_text).await
}
SystemCommand::Cycles(options) => {
run_report(
options,
network,
build_cmc_cycles_report,
cmc_cycles_report_text,
)
.await
}
}
}
async fn run_report<Report>(
options: SourceOutputOptions,
network: &str,
build: impl AsyncFn(&CollectionSourceRequest) -> Result<Report, CmcHostError>,
render_text: fn(&Report) -> String,
) -> Result<(), SystemCommandError>
where
Report: Serialize,
{
let format = options.format();
let request = CollectionSourceRequest::from_unix_secs(
network,
options.source_endpoint,
current_unix_secs()?,
"ic-query",
);
let report = build(&request).await?;
write_text_or_json(format, &report, render_text)
}
pub fn command() -> ClapCommand {
SystemCommand::augment_subcommands(ClapCommand::new("system")).mut_subcommands(|command| {
command.mut_arg("source-endpoint", |arg| {
arg.default_value(DEFAULT_CMC_SOURCE_ENDPOINT)
.help("IC API endpoint used for the native CMC query")
})
})
}
#[cfg(test)]
mod tests;