lib.rs

cdk-rsx/crates/cdk-rsx-management/src/lib.rs

lib.rs1,811 lines← SDK documentation
1#![doc = include_str!("../README.md")]2#![cfg_attr(docsrs, feature(doc_cfg))]34use candid::{CandidType, Nat, Principal, Reserved};5use cdk_rsx::api::{6    SignCostError, canister_version, cost_create_canister,7    cost_sign_with_ecdsa as ic0_cost_sign_with_ecdsa,8    cost_sign_with_schnorr as ic0_cost_sign_with_schnorr,9    cost_vetkd_derive_key as ic0_cost_vetkd_derive_key, subnet_self_node_count,10};11use cdk_rsx::call::{Call, CallFailed, Response};1213/// A fixed Internet Computer management-protocol response decode failure.14#[derive(thiserror::Error, Debug, Clone)]15#[error("management Candid response rejected: {0}")]16pub struct ManagementDecodeFailed(String);17/// Errors of the fixed external management protocol, separate from public Wire.18#[derive(thiserror::Error, Debug, Clone)]19pub enum ManagementError {20    #[error(transparent)]21    Call(#[from] CallFailed),22    #[error(transparent)]23    Decode(#[from] ManagementDecodeFailed),24}25pub type CallResult<T> = Result<T, ManagementError>;2627// This adapter is private and only used for the IC's fixed Candid protocols.28// Ordinary Call::with_args/Response::wire have no Candid path or dependency.29trait ManagementRequest: Sized {30    fn management_arg<A: CandidType>(self, value: A) -> Self;31}32impl ManagementRequest for Call<'_, '_> {33    fn management_arg<A: CandidType>(self, value: A) -> Self {34        // Management replies can include large HTTP bodies or snapshot chunks.35        self.take_raw_args(candid::encode_one(value).expect("management argument encoding"))36            .with_response_limits(cdk_rsx::wire::LARGE_PAYLOAD_LIMITS)37    }38}39trait ManagementResponse {40    fn management<R: CandidType + for<'de> Deserialize<'de>>(41        &self,42    ) -> Result<R, ManagementDecodeFailed>;43}44impl ManagementResponse for Response {45    fn management<R: CandidType + for<'de> Deserialize<'de>>(46        &self,47    ) -> Result<R, ManagementDecodeFailed> {48        candid::decode_one(self).map_err(|e| ManagementDecodeFailed(e.to_string()))49    }50}51use serde::{Deserialize, Serialize};5253// Re-export types from the `ic-management-canister-types` crate.54pub use ic_management_canister_types::{55    Bip341, CanisterId, CanisterIdRecord, CanisterInfoArgs, CanisterInfoResult,56    CanisterMetadataArgs, CanisterMetadataResult, CanisterSettings, CanisterStatusArgs,57    CanisterStatusResult, CanisterStatusType, CanisterTimer, Change, ChangeDetails, ChangeOrigin,58    ChunkHash, ClearChunkStoreArgs, CodeDeploymentMode, CodeDeploymentRecord,59    ControllersChangeRecord, CreateCanisterResult, CreationRecord, DefiniteCanisterSettings,60    DeleteCanisterArgs, DeleteCanisterSnapshotArgs, DepositCyclesArgs, EcdsaCurve, EcdsaKeyId,61    EcdsaPublicKeyArgs, EcdsaPublicKeyResult, EnvironmentVariable, FlexibleHttpGlobalError,62    FlexibleHttpNodeDetail, FlexibleHttpNodeError, FlexibleHttpRequestArgs, FlexibleHttpRequestErr,63    FlexibleHttpRequestResult, FromCanisterRecord, FromUserRecord, HttpHeader, HttpMethod,64    HttpRequestArgs, HttpRequestResourceReport, HttpRequestResult, ListCanisterSnapshotsArgs,65    ListCanisterSnapshotsResult, LoadSnapshotRecord, LogVisibility, MemoryMetrics, NodeMetrics,66    NodeMetricsHistoryArgs, NodeMetricsHistoryRecord, NodeMetricsHistoryResult,67    OnLowWasmMemoryHookStatus, ProvisionalCreateCanisterWithCyclesResult,68    ProvisionalTopUpCanisterArgs, QueryStats, RawRandResult, ReadCanisterSnapshotDataArgs,69    ReadCanisterSnapshotDataResult, ReadCanisterSnapshotMetadataArgs,70    ReadCanisterSnapshotMetadataResult, RenameCanisterRecord, RenameToRecord, ReplicationCounts,71    ResourceUsage, SchnorrAlgorithm, SchnorrAux, SchnorrKeyId, SchnorrPublicKeyArgs,72    SchnorrPublicKeyResult, SignWithEcdsaArgs, SignWithEcdsaResult, SignWithSchnorrArgs,73    SignWithSchnorrResult, Snapshot, SnapshotDataKind, SnapshotDataOffset, SnapshotId,74    SnapshotMetadataGlobal, SnapshotSource, SnapshotVisibility, StartCanisterArgs,75    StatusVisibility, StopCanisterArgs, StoredChunksArgs, StoredChunksResult, SubnetInfoArgs,76    SubnetInfoResult, TakeCanisterSnapshotArgs, TakeCanisterSnapshotResult, TransformArgs,77    TransformContext, TransformFunc, UploadCanisterSnapshotDataArgs,78    UploadCanisterSnapshotMetadataArgs, UploadCanisterSnapshotMetadataResult, UploadChunkArgs,79    UploadChunkResult, VetKDCurve, VetKDDeriveKeyArgs, VetKDDeriveKeyResult, VetKDKeyId,80    VetKDPublicKeyArgs, VetKDPublicKeyResult, WasmModule,81};8283// Following Args types contain `sender_canister_version` field which is set automatically in the corresponding functions.84// We provide reduced versions of these types to avoid duplication of the field.85use ic_management_canister_types::{86    CreateCanisterArgs as CreateCanisterArgsComplete,87    InstallChunkedCodeArgs as InstallChunkedCodeArgsComplete,88    InstallCodeArgs as InstallCodeArgsComplete,89    LoadCanisterSnapshotArgs as LoadCanisterSnapshotArgsComplete,90    ProvisionalCreateCanisterWithCyclesArgs as ProvisionalCreateCanisterWithCyclesArgsComplete,91    UninstallCodeArgs as UninstallCodeArgsComplete,92    UpdateSettingsArgs as UpdateSettingsArgsComplete,93};9495/// Store-compatible installation modes. Upgrade flags are determined by the CDK.96#[derive(97    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy,98)]99pub enum InstallMode {100    /// Install into an empty canister.101    Install,102    /// Deliberately discard existing state and install afresh.103    Reinstall,104    /// Preserve Store memory and run the generated pre-upgrade gate.105    Upgrade,106}107impl InstallMode {108    fn wire(self) -> ic_management_canister_types::CanisterInstallMode {109        use ic_management_canister_types::{110            CanisterInstallMode as Mode, UpgradeFlags, WasmMemoryPersistence,111        };112        match self {113            Self::Install => Mode::Install,114            Self::Reinstall => Mode::Reinstall,115            Self::Upgrade => Mode::Upgrade(Some(UpgradeFlags {116                skip_pre_upgrade: Some(false),117                wasm_memory_persistence: Some(WasmMemoryPersistence::Keep),118            })),119        }120    }121}122123/// The error type for the [`sign_with_ecdsa`] and [`sign_with_schnorr`] functions.124#[derive(thiserror::Error, Debug, Clone)]125pub enum SignCallError {126    /// The signature cost calculation failed.127    #[error(transparent)]128    SignCostError(#[from] SignCostError),129    /// Failed to make the inter-canister call to the management canister.130    #[error(transparent)]131    CallFailed(#[from] CallFailed),132    /// Failed to decode the response from the management canister.133    #[error(transparent)]134    ManagementDecodeFailed(#[from] ManagementDecodeFailed),135}136137/// Creates a new canister.138///139/// **Unbounded-wait call**140///141/// See [IC method `create_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-create_canister).142///143/// # Note144///145/// Canister creation costs cycles. That amount will be deducted from the newly created canister.146/// This method will only attach the required cycles for the canister creation (detemined by [`cost_create_canister`]).147/// The new canister will have a 0 cycle balance.148///149/// To ensure the new canister has extra cycles after creation, use [`create_canister_with_extra_cycles`] instead.150///151/// Cycles can also be deposited to the new canister using [`deposit_cycles`].152///153/// Check [Gas and cycles cost](https://internetcomputer.org/docs/current/developer-docs/gas-cost#canister-creation) for more details.154pub async fn create_canister(arg: &CreateCanisterArgs) -> CallResult<CreateCanisterResult> {155    let complete_arg = CreateCanisterArgsComplete {156        settings: arg.settings.clone(),157        sender_canister_version: Some(canister_version()),158    };159    let cycles = cost_create_canister();160    Ok(161        Call::unbounded_wait(Principal::management_canister(), "create_canister")162            .management_arg(&complete_arg)163            .with_cycles(cycles)164            .await?165            .management()?,166    )167}168169/// Creates a new canister with extra cycles.170///171/// **Unbounded-wait call**172///173/// See [IC method `create_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-create_canister).174///175/// # Note176///177/// Canister creation costs cycles. That amount will be deducted from the newly created canister.178/// This method will attach the required cycles for the canister creation (detemined by [`cost_create_canister`]) plus the `extra_cycles` to the call.179/// The new cansiter will have a cycle balance of `extra_cycles`.180///181/// To simply create a canister with 0 cycle balance, use [`create_canister`] instead.182///183/// Check [Gas and cycles cost](https://internetcomputer.org/docs/current/developer-docs/gas-cost#canister-creation) for more details.184pub async fn create_canister_with_extra_cycles(185    arg: &CreateCanisterArgs,186    extra_cycles: u128,187) -> CallResult<CreateCanisterResult> {188    let complete_arg = CreateCanisterArgsComplete {189        settings: arg.settings.clone(),190        sender_canister_version: Some(canister_version()),191    };192    let cycles = cost_create_canister() + extra_cycles;193    Ok(194        Call::unbounded_wait(Principal::management_canister(), "create_canister")195            .management_arg(&complete_arg)196            .with_cycles(cycles)197            .await?198            .management()?,199    )200}201202/// Argument type of [`create_canister`] and [`create_canister_with_extra_cycles`].203///204/// # Note205///206/// This type is a reduced version of [`ic_management_canister_types::CreateCanisterArgs`].207///208/// The `sender_canister_version` field is removed as it is set automatically in [`create_canister`] and [`create_canister_with_extra_cycles`].209#[derive(210    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default,211)]212pub struct CreateCanisterArgs {213    /// See [`CanisterSettings`].214    pub settings: Option<CanisterSettings>,215}216217/// Updates the settings of a canister.218///219/// **Unbounded-wait call**220///221/// See [IC method `update_settings`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-update_settings).222pub async fn update_settings(arg: &UpdateSettingsArgs) -> CallResult<()> {223    let complete_arg = UpdateSettingsArgsComplete {224        canister_id: arg.canister_id,225        settings: arg.settings.clone(),226        sender_canister_version: Some(canister_version()),227    };228    Ok(229        Call::unbounded_wait(Principal::management_canister(), "update_settings")230            .management_arg(&complete_arg)231            .await?232            .management()?,233    )234}235236/// Argument type of [`update_settings`]237///238/// # Note239///240/// This type is a reduced version of [`ic_management_canister_types::UpdateSettingsArgs`].241///242/// The `sender_canister_version` field is removed as it is set automatically in [`update_settings`].243#[derive(244    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone,245)]246pub struct UpdateSettingsArgs {247    /// Canister ID.248    pub canister_id: CanisterId,249    /// See [`CanisterSettings`].250    pub settings: CanisterSettings,251}252253/// Uploads a chunk to the chunk store of a canister.254///255/// **Unbounded-wait call**256///257/// See [IC method `upload_chunk`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-upload_chunk).258pub async fn upload_chunk(arg: &UploadChunkArgs) -> CallResult<UploadChunkResult> {259    Ok(260        Call::unbounded_wait(Principal::management_canister(), "upload_chunk")261            .management_arg(arg)262            .await?263            .management()?,264    )265}266267/// Clears the chunk store of a canister.268///269/// **Unbounded-wait call**270///271/// See [IC method `clear_chunk_store`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-clear_chunk_store).272pub async fn clear_chunk_store(arg: &ClearChunkStoreArgs) -> CallResult<()> {273    Ok(274        Call::unbounded_wait(Principal::management_canister(), "clear_chunk_store")275            .management_arg(arg)276            .await?277            .management()?,278    )279}280281/// Gets the hashes of all chunks stored in the chunk store of a canister.282///283/// **Bounded-wait call**284///285/// See [IC method `stored_chunks`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-stored_chunks).286pub async fn stored_chunks(arg: &StoredChunksArgs) -> CallResult<StoredChunksResult> {287    Ok(288        Call::bounded_wait(Principal::management_canister(), "stored_chunks")289            .management_arg(arg)290            .await?291            .management()?,292    )293}294295/// Installs code into a canister.296///297/// **Unbounded-wait call**298///299/// See [IC method `install_code`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-install_code).300pub async fn install_code(arg: &InstallCodeArgs) -> CallResult<()> {301    let complete_arg = InstallCodeArgsComplete {302        mode: arg.mode.wire(),303        canister_id: arg.canister_id,304        wasm_module: arg.wasm_module.clone(),305        arg: arg.arg.clone(),306        sender_canister_version: Some(canister_version()),307    };308    Ok(309        Call::unbounded_wait(Principal::management_canister(), "install_code")310            .management_arg(&complete_arg)311            .await?312            .management()?,313    )314}315316/// Argument type of [`install_code`].317///318/// # Note319///320/// This type is a reduced version of [`ic_management_canister_types::InstallCodeArgs`].321///322/// The `sender_canister_version` field is removed as it is set automatically in [`install_code`].323#[derive(324    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone,325)]326pub struct InstallCodeArgs {327    /// The installation mode; upgrades always retain Store memory and run its gate.328    pub mode: InstallMode,329    /// Canister ID.330    pub canister_id: CanisterId,331    /// Code to be installed.332    pub wasm_module: WasmModule,333    /// The argument to be passed to `canister_init` or `canister_post_upgrade`.334    #[serde(with = "serde_bytes")]335    pub arg: Vec<u8>,336}337338/// Installs code into a canister where the code has previously been uploaded in chunks.339///340/// **Unbounded-wait call**341///342/// See [IC method `install_chunked_code`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-install_chunked_code).343pub async fn install_chunked_code(arg: &InstallChunkedCodeArgs) -> CallResult<()> {344    let complete_arg = InstallChunkedCodeArgsComplete {345        mode: arg.mode.wire(),346        target_canister: arg.target_canister,347        store_canister: arg.store_canister,348        chunk_hashes_list: arg.chunk_hashes_list.clone(),349        wasm_module_hash: arg.wasm_module_hash.clone(),350        arg: arg.arg.clone(),351        sender_canister_version: Some(canister_version()),352    };353    Ok(354        Call::unbounded_wait(Principal::management_canister(), "install_chunked_code")355            .management_arg(&complete_arg)356            .await?357            .management()?,358    )359}360361/// Argument type of [`install_chunked_code`].362///363/// # Note364///365/// This type is a reduced version of [`ic_management_canister_types::InstallChunkedCodeArgs`].366///367/// The `sender_canister_version` field is removed as it is set automatically in [`install_chunked_code`].368#[derive(369    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone,370)]371pub struct InstallChunkedCodeArgs {372    /// The installation mode; upgrades always retain Store memory and run its gate.373    pub mode: InstallMode,374    /// Principal of the canister being installed.375    pub target_canister: CanisterId,376    /// The canister in whose chunk storage the chunks are stored (defaults to `target_canister` if not specified).377    pub store_canister: Option<CanisterId>,378    /// The list of chunks that make up the canister wasm.379    pub chunk_hashes_list: Vec<ChunkHash>,380    /// The sha256 hash of the wasm.381    #[serde(with = "serde_bytes")]382    pub wasm_module_hash: Vec<u8>,383    /// The argument to be passed to `canister_init` or `canister_post_upgrade`.384    #[serde(with = "serde_bytes")]385    pub arg: Vec<u8>,386}387388/// Removes a canister's code and state, making the canister empty again.389///390/// **Unbounded-wait call**391///392/// See [IC method `uninstall_code`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-uninstall_code).393pub async fn uninstall_code(arg: &UninstallCodeArgs) -> CallResult<()> {394    let complete_arg = UninstallCodeArgsComplete {395        canister_id: arg.canister_id,396        sender_canister_version: Some(canister_version()),397    };398    Ok(399        Call::unbounded_wait(Principal::management_canister(), "uninstall_code")400            .management_arg(&complete_arg)401            .await?402            .management()?,403    )404}405406/// Argument type of [`uninstall_code`].407///408/// # Note409///410/// This type is a reduced version of [`ic_management_canister_types::UninstallCodeArgs`].411///412/// The `sender_canister_version` field is removed as it is set automatically in [`uninstall_code`].413#[derive(414    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone,415)]416pub struct UninstallCodeArgs {417    /// Canister ID.418    pub canister_id: CanisterId,419}420421/// Starts a canister if the canister status was `stopped` or `stopping`.422///423/// **Unbounded-wait call**424///425/// See [IC method `start_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-start_canister).426pub async fn start_canister(arg: &StartCanisterArgs) -> CallResult<()> {427    Ok(428        Call::unbounded_wait(Principal::management_canister(), "start_canister")429            .management_arg(arg)430            .await?431            .management()?,432    )433}434435/// Stops a canister.436///437/// **Unbounded-wait call**438///439/// See [IC method `stop_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-stop_canister).440pub async fn stop_canister(arg: &StopCanisterArgs) -> CallResult<()> {441    Ok(442        Call::unbounded_wait(Principal::management_canister(), "stop_canister")443            .management_arg(arg)444            .await?445            .management()?,446    )447}448449/// Gets status information about the canister.450///451/// **Bounded-wait call**452///453/// See [IC method `canister_status`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-canister_status).454pub async fn canister_status(arg: &CanisterStatusArgs) -> CallResult<CanisterStatusResult> {455    Ok(456        Call::bounded_wait(Principal::management_canister(), "canister_status")457            .management_arg(arg)458            .await?459            .management()?,460    )461}462463/// Gets public information about the canister.464///465/// **Bounded-wait call**466///467/// See [IC method `canister_info`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-canister_info).468pub async fn canister_info(arg: &CanisterInfoArgs) -> CallResult<CanisterInfoResult> {469    Ok(470        Call::bounded_wait(Principal::management_canister(), "canister_info")471            .management_arg(arg)472            .await?473            .management()?,474    )475}476/// Gets canister's metadata contained in custom sections whose names have the form `icp:public <name>` or `icp:private <name>`477///478/// **Bounded-wait call**479///480/// See [IC method `canister_metadata`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-canister_metadata).481pub async fn canister_metadata(arg: &CanisterMetadataArgs) -> CallResult<CanisterMetadataResult> {482    Ok(483        Call::bounded_wait(Principal::management_canister(), "canister_metadata")484            .management_arg(arg)485            .await?486            .management()?,487    )488}489490/// Deletes a canister.491///492/// **Unbounded-wait call**493///494/// See [IC method `delete_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-delete_canister).495pub async fn delete_canister(arg: &DeleteCanisterArgs) -> CallResult<()> {496    Ok(497        Call::unbounded_wait(Principal::management_canister(), "delete_canister")498            .management_arg(arg)499            .await?500            .management()?,501    )502}503504/// Deposits cycles to a canister.505///506/// **Unbounded-wait call**507///508/// See [IC method `deposit_cycles`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-deposit_cycles).509pub async fn deposit_cycles(arg: &DepositCyclesArgs, cycles: u128) -> CallResult<()> {510    Ok(511        Call::unbounded_wait(Principal::management_canister(), "deposit_cycles")512            .management_arg(arg)513            .with_cycles(cycles)514            .await?515            .management()?,516    )517}518519/// Gets 32 pseudo-random bytes.520///521/// **Bounded-wait call**522///523/// See [IC method `raw_rand`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-raw_rand).524pub async fn raw_rand() -> CallResult<RawRandResult> {525    Ok(526        Call::bounded_wait(Principal::management_canister(), "raw_rand")527            .take_raw_args(candid::encode_args(()).expect("management empty arguments"))528            .await?529            .management()?,530    )531}532533/// The maximum `max_response_bytes` an HTTP outcall may declare, and the value used when the534/// field is omitted.535const MAX_RESPONSE_BYTES_LIMIT: u64 = 2_000_000;536/// The longest the system waits for an HTTP response.537const MAX_ROUNDTRIP_TIME_MS: u64 = 60_000;538/// The instruction limit of a query call, which bounds a `transform` function.539const MAX_TRANSFORM_INSTRUCTIONS: u64 = 5_000_000_000;540/// Bytes reserved on top of `max_response_bytes` for the Candid encoding of a response.541const CANDID_OVERHEAD_RESERVE_BYTES: u64 = 1_024;542/// The block space the system has for the responses of one flexible outcall, which bounds the543/// combined size of the responses it can deliver.544const MAX_FLEXIBLE_RESULT_BYTES: u64 = 2 * 1024 * 1024;545546/// # HTTP Outcall Type.547///548/// Which kind of HTTP outcall to price. See [`CostHttpRequestV2Args::outcall_type`].549#[derive(CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]550pub enum HttpOutcallType {551    /// An `http_request` with `is_replicated` set to `None` or `Some(true)`.552    #[serde(rename = "fully_replicated")]553    FullyReplicated(Reserved),554    /// An `http_request` with `is_replicated` set to `Some(false)`.555    #[serde(rename = "non_replicated")]556    NonReplicated(Reserved),557    /// A `flexible_http_request`, optionally with the replication counts it will use.558    ///559    /// If the counts are `None`, the endpoint's own defaults are priced.560    #[serde(rename = "flexible")]561    Flexible(Option<ReplicationCounts>),562}563564/// # Cost HTTP Request V2 Args.565///566/// The resource usage to price. Argument type of [`cost_http_request_v2`].567#[derive(CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]568pub struct CostHttpRequestV2Args {569    /// The byte length of the URL, the header names and values, the body, and the transform570    /// method name and context.571    pub request_bytes: u64,572    /// Milliseconds between sending the request and fully receiving the response.573    pub http_roundtrip_time_ms: u64,574    /// The byte length of the HTTP response, before transformation.575    pub raw_response_bytes: u64,576    /// The byte length of the response after transformation.577    pub transformed_response_bytes: u64,578    /// Instructions the transform function uses.579    pub transform_instructions: u64,580    /// The kind of outcall. If `None`, a fully replicated outcall is priced.581    pub outcall_type: Option<HttpOutcallType>,582}583584/// Calculates the cost of an HTTP outcall priced with pricing version `2`.585///586/// This returns the amount to **attach** for an outcall that consumes exactly the resources in587/// `arg`, not a prediction of the charge. The surplus is refunded, so the eventual charge is at588/// most the amount attached.589///590/// [`HttpRequest`] and [`FlexibleHttpRequest`] invoke this internally and attach the result.591///592/// # Panics593///594/// Panics if `arg` cannot be Candid-encoded, which cannot happen for a well-formed value.595pub fn cost_http_request_v2(arg: &CostHttpRequestV2Args) -> u128 {596    let bytes = candid::encode_one(arg).expect("failed to Candid-encode the cost parameters");597    cdk_rsx::api::cost_http_request_v2(&bytes)598}599600/// The resource usage a caller expects, used to size the cycles reservation.601///602/// Any field left unset falls back to the maximum the outcall could consume, which yields a603/// reservation the outcall cannot exhaust.604#[derive(Debug, Clone, Default, PartialEq, Eq)]605struct Reservation {606    roundtrip_time_ms: Option<u64>,607    raw_response_bytes: Option<u64>,608    transformed_response_bytes: Option<u64>,609    transform_instructions: Option<u64>,610}611612impl Reservation {613    /// Resolves the expected usage against `max_response_bytes`, filling unset fields with the614    /// maximum the outcall could consume.615    ///616    /// `transformed_default_cap` bounds the value an unset `transformed_response_bytes` falls617    /// back to. An expectation the caller set explicitly is always used as given.618    ///619    /// `has_transform` says whether the request sets a `transform` function. Without one the620    /// system never runs a transform, so an unset `transform_instructions` falls back to zero621    /// rather than to the query call instruction limit.622    fn resolve(623        &self,624        max_response_bytes: Option<u64>,625        transformed_default_cap: Option<u64>,626        has_transform: bool,627    ) -> (u64, u64, u64, u64) {628        let cap = max_response_bytes.unwrap_or(MAX_RESPONSE_BYTES_LIMIT);629        let transformed = self.transformed_response_bytes.unwrap_or_else(|| {630            let worst_case = cap.saturating_add(CANDID_OVERHEAD_RESERVE_BYTES);631            transformed_default_cap.map_or(worst_case, |c| worst_case.min(c))632        });633        (634            self.roundtrip_time_ms.unwrap_or(MAX_ROUNDTRIP_TIME_MS),635            self.raw_response_bytes.unwrap_or(cap),636            transformed,637            self.transform_instructions.unwrap_or(if has_transform {638                MAX_TRANSFORM_INSTRUCTIONS639            } else {640                0641            }),642        )643    }644}645646/// The largest a flexible outcall's responses can average and still be deliverable.647///648/// `None` when no response is ever delivered, or when `min_responses` is zero.649fn flexible_transformed_default_cap(replication: Option<&ReplicationCounts>) -> Option<u64> {650    let min_responses = match replication {651        Some(counts) => {652            if counts.max_responses == 0 {653                // Fire-and-forget: no response is delivered, so nothing bounds its size.654                return None;655            }656            counts.min_responses657        }658        // The system's own default when `replication` is unset.659        None => 2 * subnet_self_node_count() / 3 + 1,660    };661    (min_responses > 0).then(|| MAX_FLEXIBLE_RESULT_BYTES.div_ceil(u64::from(min_responses)))662}663664/// Computes the `request_bytes` an outcall is charged for.665fn request_bytes(666    url: &str,667    headers: &[HttpHeader],668    body: Option<&Vec<u8>>,669    transform: Option<&TransformContext>,670) -> u64 {671    (url.len()672        + headers673            .iter()674            .map(|h| h.name.len() + h.value.len())675            .sum::<usize>()676        + body.map_or(0, |b| b.len())677        + transform.map_or(0, |t| t.context.len() + t.function.0.method.len())) as u64678}679680/// A builder for an HTTP outcall via the Management canister method681/// [`http_request`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-http_request).682///683/// The outcall is always made with pricing version `2` ("pay-as-you-go"), which charges for the684/// resources the call actually consumes rather than for `max_response_bytes`.685///686/// Because the cycles attached to a version `2` outcall are also the budget each node may spend687/// on it, the amount to attach depends on how much the call is expected to consume. Every688/// `with_expected_*` method narrows that estimate; whatever is left unset falls back to the most689/// the outcall could consume, which yields a reservation the outcall cannot exhaust but which690/// holds far more cycles for the duration of the call.691///692/// Narrowing an expectation below what the call actually needs is not rejected up front. The693/// outcall runs with reduced limits, and potentially fails at a later point. A node that694/// exhausts its budget rejects instead of returning the response, possibly after the remote695/// server has already been contacted.696///697/// Use [`FlexibleHttpRequest`] for an outcall whose nodes return their individual responses.698///699/// # Examples700///701/// ```no_run702/// # use cdk_rsx_management::{HttpRequest, HttpMethod};703/// # async fn f() -> Result<(), Box<dyn std::error::Error>> {704/// let response = HttpRequest::new("https://example.com/api")705///     .with_method(HttpMethod::POST)706///     .with_body(b"{}".to_vec())707///     .with_max_response_bytes(4_000)708///     // a 200 ms call with a cheap transform reserves far less than the worst case709///     .with_expected_roundtrip_time_ms(200)710///     .with_expected_transform_instructions(1_000_000)711///     .send()712///     .await?;713/// # Ok(()) }714/// ```715#[must_use = "an HttpRequest does nothing unless you call `send`"]716#[derive(Debug, Clone)]717pub struct HttpRequest {718    args: HttpRequestArgs,719    reservation: Reservation,720}721722impl HttpRequest {723    /// Starts building an outcall to `url`.724    pub fn new(url: impl Into<String>) -> Self {725        Self {726            args: HttpRequestArgs {727                url: url.into(),728                pricing_version: Some(2),729                ..Default::default()730            },731            reservation: Reservation::default(),732        }733    }734735    /// Starts building an outcall from an existing [`HttpRequestArgs`].736    ///737    /// The `pricing_version` field is overwritten with `2`.738    pub fn from_args(args: HttpRequestArgs) -> Self {739        Self {740            args: HttpRequestArgs {741                pricing_version: Some(2),742                ..args743            },744            reservation: Reservation::default(),745        }746    }747748    /// Sets the HTTP method. Defaults to `GET`.749    ///750    /// `PUT`, `DELETE` and `PATCH` are accepted only in non-replicated mode, see751    /// [`Self::non_replicated`].752    pub fn with_method(mut self, method: HttpMethod) -> Self {753        self.args.method = method;754        self755    }756757    /// Sets the request headers.758    pub fn with_headers(mut self, headers: Vec<HttpHeader>) -> Self {759        self.args.headers = headers;760        self761    }762763    /// Appends one request header.764    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {765        self.args.headers.push(HttpHeader {766            name: name.into(),767            value: value.into(),768        });769        self770    }771772    /// Sets the request body.773    pub fn with_body(mut self, body: Vec<u8>) -> Self {774        self.args.body = Some(body);775        self776    }777778    /// Sets the maximum size of the response in bytes, up to 2MB.779    ///780    /// Under pricing version `2` this does not set the price, but it still bounds the response781    /// and it affects how many cycles are held while the call runs. Setting it as low as the782    /// response allows keeps the reservation small.783    pub fn with_max_response_bytes(mut self, max_response_bytes: u64) -> Self {784        self.args.max_response_bytes = Some(max_response_bytes);785        self786    }787788    /// Sets the transform function, which each node runs on its own response.789    pub fn with_transform(mut self, transform: TransformContext) -> Self {790        self.args.transform = Some(transform);791        self792    }793794    /// Makes the request from a single node chosen by the system, rather than from every node.795    ///796    /// This gives weaker integrity guarantees: the single node could observe or modify the797    /// response. It avoids the rate-limit pressure of one request per node, and it is the only798    /// mode in which `PUT`, `DELETE` and `PATCH` are accepted.799    pub fn non_replicated(mut self) -> Self {800        self.args.is_replicated = Some(false);801        self802    }803804    /// Sets the round-trip time the outcall is expected to take, in milliseconds.805    ///806    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it807    /// below what the call needs.808    ///809    /// Defaults to the 60 second maximum the system allows.810    pub fn with_expected_roundtrip_time_ms(mut self, ms: u64) -> Self {811        self.reservation.roundtrip_time_ms = Some(ms);812        self813    }814815    /// Sets the size the response is expected to have as it arrives from the server.816    ///817    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it818    /// below what the call needs.819    ///820    /// Defaults to `max_response_bytes`, or 2MB if that is unset.821    pub fn with_expected_raw_response_bytes(mut self, bytes: u64) -> Self {822        self.reservation.raw_response_bytes = Some(bytes);823        self824    }825826    /// Sets the size the response is expected to have after the transform function.827    ///828    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it829    /// below what the call needs.830    ///831    /// Defaults to `max_response_bytes` plus the bytes reserved for the Candid encoding, or 2MB832    /// plus that reserve if `max_response_bytes` is unset.833    pub fn with_expected_transformed_response_bytes(mut self, bytes: u64) -> Self {834        self.reservation.transformed_response_bytes = Some(bytes);835        self836    }837838    /// Sets the instructions the transform function is expected to use.839    ///840    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it841    /// below what the call needs.842    ///843    /// Defaults to the query call instruction limit when a transform is set, and to zero when844    /// none is, since the system then never runs one.845    pub fn with_expected_transform_instructions(mut self, instructions: u64) -> Self {846        self.reservation.transform_instructions = Some(instructions);847        self848    }849850    /// Returns the arguments the outcall will be made with.851    pub fn args(&self) -> &HttpRequestArgs {852        &self.args853    }854855    /// Returns the cycles that [`Self::send`] will attach.856    pub fn get_cost(&self) -> u128 {857        let (roundtrip, raw, transformed, instructions) = self.reservation.resolve(858            self.args.max_response_bytes,859            None,860            self.args.transform.is_some(),861        );862        cost_http_request_v2(&CostHttpRequestV2Args {863            request_bytes: request_bytes(864                &self.args.url,865                &self.args.headers,866                self.args.body.as_ref(),867                self.args.transform.as_ref(),868            ),869            http_roundtrip_time_ms: roundtrip,870            raw_response_bytes: raw,871            transformed_response_bytes: transformed,872            transform_instructions: instructions,873            // Absent means fully replicated, which is the encoding the system documents as the874            // default. Note this still emits the field as `null`: Candid keeps an `opt` field in875            // the type table, so it is not the same as omitting it.876            outcall_type: if self.args.is_replicated == Some(false) {877                Some(HttpOutcallType::NonReplicated(Reserved))878            } else {879                None880            },881        })882    }883884    /// Makes the outcall, attaching [`Self::get_cost`] cycles.885    ///886    /// **Unbounded-wait call**887    pub async fn send(self) -> CallResult<HttpRequestResult> {888        let cycles = self.get_cost();889        let result = Call::unbounded_wait(Principal::management_canister(), "http_request")890            .management_arg(&self.args)891            .with_cycles(cycles)892            .await?893            .management();894        Ok(result?)895    }896}897898/// A builder for a flexible HTTP outcall via the Management canister method899/// [`flexible_http_request`](https://internetcomputer.org/docs/references/ic-interface-spec#ic-flexible_http_request).900///901/// A committee of nodes make the request and the canister receives their individual responses902/// rather than one the subnet agreed on, so reconciling them is the canister's job. Flexible903/// outcalls are always priced with pricing version `2`.904///905/// Because the cycles attached to a version `2` outcall are also the budget the nodes may spend906/// on it, the amount to attach depends on how much the outcall is expected to consume. Every907/// `with_expected_*` method narrows that estimate; whatever is left unset falls back to the most908/// the outcall could consume, which yields a reservation the outcall cannot exhaust but which909/// holds far more cycles for the duration of the call.910///911/// Here the budget is split between the `total_requests` nodes rather than across the subnet, and912/// too few cycles surface in one of two ways. A node that exhausts its own share rejects, counting913/// towards [`TooManyRejects`](FlexibleHttpGlobalError::TooManyRejects). Separately, what the914/// committee leaves unspent is pooled to pay for delivering the result, and once that pool no915/// longer covers any result the outcall could still produce, it fails with916/// [`OutOfCycles`](FlexibleHttpGlobalError::OutOfCycles) instead. Delivery is priced by the sizes917/// of the responses, so that verdict can come after the nodes have already made their HTTP918/// requests: the outcall can spend cycles and still deliver no responses.919///920/// # Examples921///922/// ```no_run923/// # use cdk_rsx_management::{FlexibleHttpRequest, FlexibleHttpRequestResult, ReplicationCounts};924/// # async fn f() -> Result<(), Box<dyn std::error::Error>> {925/// // ask 3 nodes, accept any 2 or 3 answers926/// let result = FlexibleHttpRequest::new("https://example.com/price")927///     .with_replication(ReplicationCounts {928///         min_responses: 2,929///         max_responses: 3,930///         total_requests: 3,931///     })932///     .with_max_response_bytes(4_000)933///     .send()934///     .await?;935/// match result {936///     // fewer than `max_responses` is a normal success937///     FlexibleHttpRequestResult::Ok(responses) => { let _ = responses; }938///     FlexibleHttpRequestResult::Err(err) => { let _ = err.global_error; }939/// }940/// # Ok(()) }941/// ```942#[must_use = "a FlexibleHttpRequest does nothing unless you call `send`"]943#[derive(Debug, Clone)]944pub struct FlexibleHttpRequest {945    args: FlexibleHttpRequestArgs,946    reservation: Reservation,947}948949impl FlexibleHttpRequest {950    /// Starts building a flexible outcall to `url`.951    pub fn new(url: impl Into<String>) -> Self {952        Self {953            args: FlexibleHttpRequestArgs {954                url: url.into(),955                ..Default::default()956            },957            reservation: Reservation::default(),958        }959    }960961    /// Starts building a flexible outcall from an existing [`FlexibleHttpRequestArgs`].962    pub fn from_args(args: FlexibleHttpRequestArgs) -> Self {963        Self {964            args,965            reservation: Reservation::default(),966        }967    }968969    /// Sets the HTTP method. Defaults to `GET`.970    ///971    /// `PUT`, `DELETE` and `PATCH` are accepted only when the replication counts are972    /// deterministic, that is when `min_responses`, `max_responses` and `total_requests` are all973    /// equal.974    pub fn with_method(mut self, method: HttpMethod) -> Self {975        self.args.method = method;976        self977    }978979    /// Sets the request headers.980    pub fn with_headers(mut self, headers: Vec<HttpHeader>) -> Self {981        self.args.headers = headers;982        self983    }984985    /// Appends one request header.986    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {987        self.args.headers.push(HttpHeader {988            name: name.into(),989            value: value.into(),990        });991        self992    }993994    /// Sets the request body.995    pub fn with_body(mut self, body: Vec<u8>) -> Self {996        self.args.body = Some(body);997        self998    }9991000    /// Sets the maximum size of any single node's response in bytes, up to 2MB.1001    ///1002    /// Note that at least `min_responses` must fit a 2MiB total, in order for a1003    /// result to be delivered.1004    pub fn with_max_response_bytes(mut self, max_response_bytes: u64) -> Self {1005        self.args.max_response_bytes = Some(max_response_bytes);1006        self1007    }10081009    /// Sets the transform function, which each node runs on its own response.1010    pub fn with_transform(mut self, transform: TransformContext) -> Self {1011        self.args.transform = Some(transform);1012        self1013    }10141015    /// Sets how many nodes issue the request and how many responses to require and accept.1016    ///1017    /// Must satisfy `0 <= min_responses <= max_responses <= total_requests` and1018    /// `1 <= total_requests <= N`, where `N` is1019    /// [`subnet_self_node_count`]. Defaults to1020    /// `floor(2 / 3 * N) + 1`, `N` and `N`.1021    pub fn with_replication(mut self, replication: ReplicationCounts) -> Self {1022        self.args.replication = Some(replication);1023        self1024    }10251026    /// Sets the round-trip time the outcall is expected to take, in milliseconds.1027    ///1028    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it1029    /// below what the call needs.1030    ///1031    /// Defaults to the 60 second maximum the system allows.1032    pub fn with_expected_roundtrip_time_ms(mut self, ms: u64) -> Self {1033        self.reservation.roundtrip_time_ms = Some(ms);1034        self1035    }10361037    /// Sets the size a response is expected to have as it arrives from the server.1038    ///1039    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it1040    /// below what the call needs.1041    ///1042    /// Defaults to `max_response_bytes`, or 2MB if that is unset.1043    pub fn with_expected_raw_response_bytes(mut self, bytes: u64) -> Self {1044        self.reservation.raw_response_bytes = Some(bytes);1045        self1046    }10471048    /// Sets the size a response is expected to have after the transform function.1049    ///1050    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it1051    /// below what the call needs.1052    ///1053    /// Defaults to `max_response_bytes` plus the bytes reserved for the Candid encoding, or 2MB1054    /// plus that reserve if `max_response_bytes` is unset, and is then capped at the largest a1055    /// response can average and still leave a deliverable result, that is at the 2MiB total1056    /// result limit divided by `min_responses`. With the default replication counts on a1057    /// 13 node subnet that cap is roughly 233KB. The cap applies to this default only: an1058    /// expectation set here is used as given. Nothing is capped when no response has to be1059    /// delivered, that is when `min_responses` is zero.1060    pub fn with_expected_transformed_response_bytes(mut self, bytes: u64) -> Self {1061        self.reservation.transformed_response_bytes = Some(bytes);1062        self1063    }10641065    /// Sets the instructions the transform function is expected to use.1066    ///1067    /// A lower expectation reserves fewer cycles; see [`Self`] for the risk of setting it1068    /// below what the call needs.1069    ///1070    /// Defaults to the query call instruction limit when a transform is set, and to zero when1071    /// none is, since the system then never runs one.1072    pub fn with_expected_transform_instructions(mut self, instructions: u64) -> Self {1073        self.reservation.transform_instructions = Some(instructions);1074        self1075    }10761077    /// Returns the arguments the outcall will be made with.1078    pub fn args(&self) -> &FlexibleHttpRequestArgs {1079        &self.args1080    }10811082    /// Returns the cycles that [`Self::send`] will attach.1083    pub fn get_cost(&self) -> u128 {1084        let (roundtrip, raw, transformed, instructions) = self.reservation.resolve(1085            self.args.max_response_bytes,1086            flexible_transformed_default_cap(self.args.replication.as_ref()),1087            self.args.transform.is_some(),1088        );1089        cost_http_request_v2(&CostHttpRequestV2Args {1090            request_bytes: request_bytes(1091                &self.args.url,1092                &self.args.headers,1093                self.args.body.as_ref(),1094                self.args.transform.as_ref(),1095            ),1096            http_roundtrip_time_ms: roundtrip,1097            raw_response_bytes: raw,1098            transformed_response_bytes: transformed,1099            transform_instructions: instructions,1100            outcall_type: Some(HttpOutcallType::Flexible(self.args.replication.clone())),1101        })1102    }11031104    /// Makes the outcall, attaching [`Self::get_cost`] cycles.1105    ///1106    /// **Unbounded-wait call**1107    ///1108    /// Both arms of [`FlexibleHttpRequestResult`] arrive as a reply. This returns `Err` only for1109    /// failures detected before the requests are issued, such as invalid arguments, invalid1110    /// replication counts, or too few attached cycles.1111    pub async fn send(self) -> CallResult<FlexibleHttpRequestResult> {1112        let cycles = self.get_cost();1113        let result =1114            Call::unbounded_wait(Principal::management_canister(), "flexible_http_request")1115                .management_arg(&self.args)1116                .with_cycles(cycles)1117                .await?1118                .management();1119        Ok(result?)1120    }1121}11221123/// Constructs a [`TransformContext`] from a query method name and context.1124pub fn transform_context_from_query(1125    candid_function_name: String,1126    context: Vec<u8>,1127) -> TransformContext {1128    TransformContext {1129        context,1130        function: TransformFunc(candid::Func {1131            method: candid_function_name,1132            principal: cdk_rsx::api::canister_self(),1133        }),1134    }1135}11361137/// Gets a SEC1 encoded ECDSA public key for the given canister using the given derivation path.1138///1139/// **Bounded-wait call**1140///1141/// See [IC method `ecdsa_public_key`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-ecdsa_public_key).1142pub async fn ecdsa_public_key(arg: &EcdsaPublicKeyArgs) -> CallResult<EcdsaPublicKeyResult> {1143    Ok(1144        Call::bounded_wait(Principal::management_canister(), "ecdsa_public_key")1145            .management_arg(arg)1146            .await?1147            .management()?,1148    )1149}11501151/// Calculates the cost of ECDSA signanature with the given [`SignWithEcdsaArgs`].1152///1153/// [`sign_with_ecdsa`] invokes this method internally and attaches the required cycles to the call.1154///1155/// # Note1156///1157/// Alternatively, [`api::cost_sign_with_ecdsa`][ic0_cost_sign_with_ecdsa] takes the numeric representation of the curve.1158pub fn cost_sign_with_ecdsa(arg: &SignWithEcdsaArgs) -> Result<u128, SignCostError> {1159    ic0_cost_sign_with_ecdsa(&arg.key_id.name, arg.key_id.curve.into())1160}11611162/// Gets a new ECDSA signature of the given `message_hash` with a user-specified amount of cycles.1163///1164/// **Unbounded-wait call**1165///1166/// The signature can be separately verified against a derived ECDSA public key.1167///1168/// See [IC method `sign_with_ecdsa`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-sign_with_ecdsa).1169///1170/// # Errors1171///1172/// This method returns an error of type [`SignCallError`].1173///1174/// The signature cost calculation may fail before the inter-canister call is made, resulting in a [`SignCallError::SignCostError`].1175///1176/// Since the call argument is constructed as [`SignWithEcdsaArgs`], the `ecdsa_curve` field is guaranteed to be valid.1177/// Therefore, [`SignCostError::InvalidCurveOrAlgorithm`] should not occur. If it does, it is likely an issue with the IC. Please report it.1178///1179/// # Note1180///1181/// Signature costs cycles which varies for different curves and key names.1182/// This method attaches the required cycles (detemined by [`cost_sign_with_ecdsa`]) to the call.1183///1184/// Check [Threshold signatures](https://internetcomputer.org/docs/current/references/t-sigs-how-it-works/#api-fees) for more details.1185pub async fn sign_with_ecdsa(1186    arg: &SignWithEcdsaArgs,1187) -> Result<SignWithEcdsaResult, SignCallError> {1188    let cycles = cost_sign_with_ecdsa(arg)?;1189    Ok(1190        Call::unbounded_wait(Principal::management_canister(), "sign_with_ecdsa")1191            .management_arg(arg)1192            .with_cycles(cycles)1193            .await?1194            .management()?,1195    )1196}11971198/// Gets a SEC1 encoded Schnorr public key for the given canister using the given derivation path.1199///1200/// **Bounded-wait call**1201///1202/// See [IC method `schnorr_public_key`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-schnorr_public_key).1203pub async fn schnorr_public_key(arg: &SchnorrPublicKeyArgs) -> CallResult<SchnorrPublicKeyResult> {1204    Ok(1205        Call::bounded_wait(Principal::management_canister(), "schnorr_public_key")1206            .management_arg(arg)1207            .await?1208            .management()?,1209    )1210}12111212/// Calculates the cost of Schnorr signanature with the given [`SignWithSchnorrArgs`].1213///1214/// [`sign_with_schnorr`] invokes this method internally and attaches the required cycles to the call.1215///1216/// # Note1217///1218/// Alternatively, [`api::cost_sign_with_schnorr`][ic0_cost_sign_with_schnorr] takes the numeric representation of the algorithm.1219pub fn cost_sign_with_schnorr(arg: &SignWithSchnorrArgs) -> Result<u128, SignCostError> {1220    ic0_cost_sign_with_schnorr(&arg.key_id.name, arg.key_id.algorithm.into())1221}12221223/// Gets a new Schnorr signature of the given message with a user-specified amount of cycles.1224///1225/// **Unbounded-wait call**1226///1227/// The signature can be separately verified against a derived Schnorr public key.1228///1229/// See [IC method `sign_with_schnorr`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-sign_with_schnorr).1230///1231/// # Errors1232///1233/// This method returns an error of type [`SignCallError`].1234///1235/// The signature cost calculation may fail before the inter-canister call is made, resulting in a [`SignCallError::SignCostError`].1236///1237/// Since the call argument is constructed as [`SignWithSchnorrArgs`], the `algorithm` field is guaranteed to be valid.1238/// Therefore, [`SignCostError::InvalidCurveOrAlgorithm`] should not occur. If it does, it is likely an issue with the IC. Please report it.1239///1240/// # Note1241///1242/// Signature costs cycles which varies for different algorithms and key names.1243/// This method attaches the required cycles (detemined by [`cost_sign_with_schnorr`]) to the call.1244///1245/// Check [Threshold signatures](https://internetcomputer.org/docs/current/references/t-sigs-how-it-works/#api-fees) for more details.1246pub async fn sign_with_schnorr(1247    arg: &SignWithSchnorrArgs,1248) -> Result<SignWithSchnorrResult, SignCallError> {1249    let cycles = cost_sign_with_schnorr(arg)?;1250    Ok(1251        Call::unbounded_wait(Principal::management_canister(), "sign_with_schnorr")1252            .management_arg(arg)1253            .with_cycles(cycles)1254            .await?1255            .management()?,1256    )1257}12581259/// Gets a VetKD public key.1260///1261/// **Bounded-wait call**1262///1263/// As of 2025-05-01, the vetKD feature is not yet available on the IC mainnet.1264/// The lastest PocketIC with the `with_nonmainnet_features(true)` flag can be used to test it.1265///1266/// See [IC method `vetkd_public_key`](https://github.com/dfinity/portal/pull/3763).1267///1268/// Later, the description will be available in [the interface spec](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-vetkd_public_key).1269pub async fn vetkd_public_key(arg: &VetKDPublicKeyArgs) -> CallResult<VetKDPublicKeyResult> {1270    Ok(1271        Call::bounded_wait(Principal::management_canister(), "vetkd_public_key")1272            .management_arg(arg)1273            .await?1274            .management()?,1275    )1276}12771278/// Calculates the cost of VetKD key derivation with the given [`VetKDDeriveKeyArgs`].1279///1280/// [`vetkd_derive_key`] invokes this method internally and attaches the required cycles to the call.1281///1282/// # Note1283///1284/// Alternatively, [`api::cost_vetkd_derive_key`][ic0_cost_vetkd_derive_key] takes the numeric representation of the algorithm.1285pub fn cost_vetkd_derive_key(arg: &VetKDDeriveKeyArgs) -> Result<u128, SignCostError> {1286    ic0_cost_vetkd_derive_key(&arg.key_id.name, arg.key_id.curve.into())1287}12881289/// Derives a key from the given input.1290///1291/// **Unbounded-wait call**1292///1293/// The returned encrypted key can be separately decrypted using the private secret key corresponding to the transport public key provided in the request, and the derivation correctness can be verified against the input and context provided in the request. See the [`ic_vetkeys` frontend library](https://github.com/dfinity/vetkd-devkit/tree/main/frontend/ic_vetkeys) for more details.1294///1295/// As of 2025-05-01, the vetKD feature is not yet available on the IC mainnet.1296/// The lastest PocketIC with the `with_nonmainnet_features(true)` flag can be used to test it.1297///1298/// See [IC method `vetkd_derive_key`](https://github.com/dfinity/portal/pull/3763) for the API specification.1299///1300/// Later, the description will be available in [the interface spec](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-vetkd_derive_key).1301///1302/// # Errors1303///1304/// This method returns an error of type [`SignCallError`].1305///1306/// The signature cost calculation may fail before the inter-canister call is made, resulting in a [`SignCallError::SignCostError`].1307///1308/// Since the call argument is constructed as [`VetKDDeriveKeyArgs`], the `curve` field is guaranteed to be valid.1309/// Therefore, [`SignCostError::InvalidCurveOrAlgorithm`] should not occur. If it does, it is likely an issue with the IC. Please report it.1310///1311/// # Note1312///1313/// VetKD key derivation costs cycles which varies for different algorithms and key names.1314/// This method attaches the required cycles (detemined by [`cost_vetkd_derive_key`]) to the call.1315///1316/// Check [Threshold signatures](https://internetcomputer.org/docs/current/references/t-sigs-how-it-works/#api-fees) for more details.1317pub async fn vetkd_derive_key(1318    arg: &VetKDDeriveKeyArgs,1319) -> Result<VetKDDeriveKeyResult, SignCallError> {1320    let cycles = cost_vetkd_derive_key(arg)?;1321    Ok(1322        Call::unbounded_wait(Principal::management_canister(), "vetkd_derive_key")1323            .management_arg(arg)1324            .with_cycles(cycles)1325            .await?1326            .management()?,1327    )1328}13291330/// Gets a time series of subnet's node metrics.1331///1332/// **Bounded-wait call**1333///1334/// See [IC method `node_metrics_history`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-node_metrics_history).1335pub async fn node_metrics_history(1336    arg: &NodeMetricsHistoryArgs,1337) -> CallResult<NodeMetricsHistoryResult> {1338    Ok(1339        Call::bounded_wait(Principal::management_canister(), "node_metrics_history")1340            .management_arg(arg)1341            .await?1342            .management()?,1343    )1344}13451346/// Gets the metadata about a subnet.1347///1348/// **Bounded-wait call**1349///1350/// See [IC method `subnet_info`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-subnet_info).1351pub async fn subnet_info(arg: &SubnetInfoArgs) -> CallResult<SubnetInfoResult> {1352    Ok(1353        Call::bounded_wait(Principal::management_canister(), "subnet_info")1354            .management_arg(arg)1355            .await?1356            .management()?,1357    )1358}13591360/// Creates a new canister with specified amount of cycles balance.1361///1362/// **Unbounded-wait call**1363///1364/// # Note1365///1366/// This method is only available in local development instances.1367///1368/// See [IC method `provisional_create_canister_with_cycles`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-provisional_create_canister_with_cycles).1369pub async fn provisional_create_canister_with_cycles(1370    arg: &ProvisionalCreateCanisterWithCyclesArgs,1371) -> CallResult<ProvisionalCreateCanisterWithCyclesResult> {1372    let complete_arg = ProvisionalCreateCanisterWithCyclesArgsComplete {1373        amount: arg.amount.clone(),1374        settings: arg.settings.clone(),1375        specified_id: arg.specified_id,1376        sender_canister_version: Some(canister_version()),1377    };1378    Ok(Call::unbounded_wait(1379        Principal::management_canister(),1380        "provisional_create_canister_with_cycles",1381    )1382    .management_arg(&complete_arg)1383    .await?1384    .management()?)1385}13861387/// Argument type of [`provisional_create_canister_with_cycles`].1388///1389/// # Note1390///1391/// This type is a reduced version of [`ic_management_canister_types::ProvisionalCreateCanisterWithCyclesArgs`].1392///1393/// The `sender_canister_version` field is removed as it is set automatically in [`provisional_create_canister_with_cycles`].1394#[derive(1395    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default,1396)]1397pub struct ProvisionalCreateCanisterWithCyclesArgs {1398    /// The created canister will have this amount of cycles.1399    pub amount: Option<Nat>,1400    /// Canister settings.1401    pub settings: Option<CanisterSettings>,1402    /// If set, the canister will be created under this id.1403    pub specified_id: Option<CanisterId>,1404}14051406/// Adds cycles to a canister.1407///1408/// **Unbounded-wait call**1409///1410/// # Note1411///1412/// This method is only available in local development instances.1413///1414/// See [IC method `provisional_top_up_canister`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-provisional_top_up_canister).1415pub async fn provisional_top_up_canister(arg: &ProvisionalTopUpCanisterArgs) -> CallResult<()> {1416    Ok(Call::unbounded_wait(1417        Principal::management_canister(),1418        "provisional_top_up_canister",1419    )1420    .management_arg(arg)1421    .await?1422    .management()?)1423}14241425/// Takes a snapshot of the specified canister.1426///1427/// **Unbounded-wait call**1428///1429/// A snapshot consists of the wasm memory, stable memory, certified variables, wasm chunk store and wasm binary.1430///1431/// See [IC method `take_canister_snapshot`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-take_canister_snapshot).1432pub async fn take_canister_snapshot(1433    arg: &TakeCanisterSnapshotArgs,1434) -> CallResult<TakeCanisterSnapshotResult> {1435    Ok(1436        Call::unbounded_wait(Principal::management_canister(), "take_canister_snapshot")1437            .management_arg(arg)1438            .await?1439            .management()?,1440    )1441}14421443/// Loads a snapshot onto the canister.1444///1445/// **Unbounded-wait call**1446///1447/// It fails if no snapshot with the specified `snapshot_id` can be found.1448///1449/// See [IC method `load_canister_snapshot`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-load_canister_snapshot).1450pub async fn load_canister_snapshot(arg: &LoadCanisterSnapshotArgs) -> CallResult<()> {1451    let complete_arg = LoadCanisterSnapshotArgsComplete {1452        canister_id: arg.canister_id,1453        snapshot_id: arg.snapshot_id.clone(),1454        sender_canister_version: Some(canister_version()),1455    };1456    Ok(1457        Call::unbounded_wait(Principal::management_canister(), "load_canister_snapshot")1458            .management_arg(&complete_arg)1459            .await?1460            .management()?,1461    )1462}14631464/// Argument type of [`load_canister_snapshot`].1465///1466/// # Note1467///1468/// This type is a reduced version of [`ic_management_canister_types::LoadCanisterSnapshotArgs`].1469///1470/// The `sender_canister_version` field is removed as it is set automatically in [`load_canister_snapshot`].1471#[derive(1472    CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone,1473)]1474pub struct LoadCanisterSnapshotArgs {1475    /// Canister ID.1476    pub canister_id: CanisterId,1477    /// ID of the snapshot to be loaded.1478    pub snapshot_id: SnapshotId,1479}14801481/// Reads metadata of a snapshot of a canister.1482///1483/// **Bounded-wait call**1484///1485/// See [IC method `read_canister_snapshot_metadata`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-read_canister_snapshot_metadata).1486pub async fn read_canister_snapshot_metadata(1487    arg: &ReadCanisterSnapshotMetadataArgs,1488) -> CallResult<ReadCanisterSnapshotMetadataResult> {1489    Ok(Call::bounded_wait(1490        Principal::management_canister(),1491        "read_canister_snapshot_metadata",1492    )1493    .management_arg(arg)1494    .await?1495    .management()?)1496}14971498/// Reads data of a snapshot of a canister.1499///1500/// **Bounded-wait call**1501///1502/// See [IC method `read_canister_snapshot_data`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-read_canister_snapshot_data).1503pub async fn read_canister_snapshot_data(1504    arg: &ReadCanisterSnapshotDataArgs,1505) -> CallResult<ReadCanisterSnapshotDataResult> {1506    Ok(Call::bounded_wait(1507        Principal::management_canister(),1508        "read_canister_snapshot_data",1509    )1510    .management_arg(arg)1511    .await?1512    .management()?)1513}15141515/// Creates a snapshot of that canister by uploading the snapshot's metadata.1516///1517/// **Bounded-wait call**1518///1519/// See [IC method `upload_canister_snapshot_metadata`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-upload_canister_snapshot_metadata).1520pub async fn upload_canister_snapshot_metadata(1521    arg: &UploadCanisterSnapshotMetadataArgs,1522) -> CallResult<UploadCanisterSnapshotMetadataResult> {1523    Ok(Call::bounded_wait(1524        Principal::management_canister(),1525        "upload_canister_snapshot_metadata",1526    )1527    .management_arg(arg)1528    .await?1529    .management()?)1530}15311532/// Uploads data to a snapshot of that canister.1533///1534/// **Bounded-wait call**1535///1536/// See [IC method `upload_canister_snapshot_data`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-upload_canister_snapshot_data).1537pub async fn upload_canister_snapshot_data(arg: &UploadCanisterSnapshotDataArgs) -> CallResult<()> {1538    Ok(Call::bounded_wait(1539        Principal::management_canister(),1540        "upload_canister_snapshot_data",1541    )1542    .management_arg(arg)1543    .await?1544    .management()?)1545}15461547/// Lists the snapshots of the canister.1548///1549/// **Bounded-wait call**1550///1551/// See [IC method `list_canister_snapshots`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-list_canister_snapshots).1552pub async fn list_canister_snapshots(1553    arg: &ListCanisterSnapshotsArgs,1554) -> CallResult<ListCanisterSnapshotsResult> {1555    Ok(1556        Call::bounded_wait(Principal::management_canister(), "list_canister_snapshots")1557            .management_arg(arg)1558            .await?1559            .management()?,1560    )1561}15621563/// Deletes a specified snapshot that belongs to an existing canister.1564///1565/// **Unbounded-wait call**1566///1567/// An error will be returned if the snapshot is not found.1568///1569/// See [IC method `delete_canister_snapshot`](https://internetcomputer.org/docs/current/references/ic-interface-spec/#ic-delete_canister_snapshot).1570pub async fn delete_canister_snapshot(arg: &DeleteCanisterSnapshotArgs) -> CallResult<()> {1571    Ok(1572        Call::unbounded_wait(Principal::management_canister(), "delete_canister_snapshot")1573            .management_arg(arg)1574            .await?1575            .management()?,1576    )1577}15781579#[cfg(test)]1580mod tests {1581    use super::*;15821583    /// The cost parameter record must round-trip through Candid, since it is handed to the1584    /// system API as an encoded blob.1585    #[test]1586    fn cost_args_candid_round_trip() {1587        for outcall_type in [1588            None,1589            Some(HttpOutcallType::FullyReplicated(Reserved)),1590            Some(HttpOutcallType::NonReplicated(Reserved)),1591            Some(HttpOutcallType::Flexible(None)),1592            Some(HttpOutcallType::Flexible(Some(ReplicationCounts {1593                min_responses: 2,1594                max_responses: 3,1595                total_requests: 3,1596            }))),1597        ] {1598            let args = CostHttpRequestV2Args {1599                request_bytes: 1,1600                http_roundtrip_time_ms: 2,1601                raw_response_bytes: 3,1602                transformed_response_bytes: 4,1603                transform_instructions: 5,1604                outcall_type,1605            };1606            let bytes = candid::encode_one(&args).unwrap();1607            let decoded: CostHttpRequestV2Args = candid::decode_one(&bytes).unwrap();1608            assert_eq!(args, decoded);1609        }1610    }16111612    /// An unset expectation must fall back to the maximum the outcall could consume.1613    #[test]1614    fn reservation_defaults_to_the_maxima() {1615        let (roundtrip, raw, transformed, instructions) =1616            Reservation::default().resolve(None, None, true);1617        assert_eq!(roundtrip, MAX_ROUNDTRIP_TIME_MS);1618        assert_eq!(raw, MAX_RESPONSE_BYTES_LIMIT);1619        assert_eq!(1620            transformed,1621            MAX_RESPONSE_BYTES_LIMIT + CANDID_OVERHEAD_RESERVE_BYTES1622        );1623        assert_eq!(instructions, MAX_TRANSFORM_INSTRUCTIONS);1624    }16251626    /// `max_response_bytes` bounds both response sizes when they are not given explicitly.1627    #[test]1628    fn reservation_defaults_follow_max_response_bytes() {1629        let (_, raw, transformed, _) = Reservation::default().resolve(Some(4_000), None, true);1630        assert_eq!(raw, 4_000);1631        assert_eq!(transformed, 4_000 + CANDID_OVERHEAD_RESERVE_BYTES);1632    }16331634    /// An explicit expectation must win over the default.1635    #[test]1636    fn reservation_uses_supplied_values() {1637        let reservation = Reservation {1638            roundtrip_time_ms: Some(300),1639            raw_response_bytes: Some(1_000),1640            transformed_response_bytes: Some(900),1641            transform_instructions: Some(1_000_000),1642        };1643        assert_eq!(1644            reservation.resolve(Some(4_000), None, true),1645            (300, 1_000, 900, 1_000_000)1646        );1647    }16481649    /// The builder must always ask for pricing version 2, including via `from_args`.1650    #[test]1651    fn builder_always_selects_pricing_version_2() {1652        assert_eq!(1653            HttpRequest::new("https://example.com")1654                .args()1655                .pricing_version,1656            Some(2)1657        );1658        let args = HttpRequestArgs {1659            url: "https://example.com".to_string(),1660            pricing_version: Some(1),1661            ..Default::default()1662        };1663        assert_eq!(HttpRequest::from_args(args).args().pricing_version, Some(2));1664    }16651666    /// `non_replicated` must be reflected in both the args and the priced outcall type.1667    #[test]1668    fn non_replicated_is_recorded() {1669        let req = HttpRequest::new("https://example.com").non_replicated();1670        assert_eq!(req.args().is_replicated, Some(false));1671    }16721673    /// The flexible builder records the replication counts, and leaves them unset so the1674    /// system picks its defaults when the caller does not.1675    #[test]1676    fn flexible_replication_is_recorded() {1677        assert_eq!(1678            FlexibleHttpRequest::new("https://example.com")1679                .args()1680                .replication,1681            None1682        );1683        let counts = ReplicationCounts {1684            min_responses: 2,1685            max_responses: 3,1686            total_requests: 3,1687        };1688        assert_eq!(1689            FlexibleHttpRequest::new("https://example.com")1690                .with_replication(counts.clone())1691                .args()1692                .replication,1693            Some(counts)1694        );1695    }16961697    /// The flexible default for `transformed_response_bytes` is the block budget split across1698    /// the responses that have to be delivered together.1699    #[test]1700    fn flexible_default_cap_divides_the_block_budget() {1701        let counts = ReplicationCounts {1702            min_responses: 9,1703            max_responses: 13,1704            total_requests: 13,1705        };1706        let cap = flexible_transformed_default_cap(Some(&counts)).unwrap();1707        assert_eq!(cap, MAX_FLEXIBLE_RESULT_BYTES.div_ceil(9));1708        // The rounding only matters when every node's response has to be delivered, since the1709        // reserve prices `total_requests` of them. Rounding down is 8 bytes short here.1710        let deterministic = ReplicationCounts {1711            min_responses: 9,1712            max_responses: 9,1713            total_requests: 9,1714        };1715        let cap = flexible_transformed_default_cap(Some(&deterministic)).unwrap();1716        assert!(9 * cap >= MAX_FLEXIBLE_RESULT_BYTES);1717        // Rounding down instead would have left the reserve 8 bytes short of a full block.1718        assert_eq!(9 * (cap - 1), MAX_FLEXIBLE_RESULT_BYTES - 8);1719    }17201721    /// Nothing bounds the response size when no response is delivered, or when no minimum is1722    /// required, so those must not divide by `min_responses`.1723    #[test]1724    fn flexible_default_cap_is_absent_when_nothing_must_be_delivered() {1725        // Fire-and-forget.1726        assert_eq!(1727            flexible_transformed_default_cap(Some(&ReplicationCounts {1728                min_responses: 0,1729                max_responses: 0,1730                total_requests: 3,1731            })),1732            None1733        );1734        // No minimum, but responses may still arrive.1735        assert_eq!(1736            flexible_transformed_default_cap(Some(&ReplicationCounts {1737                min_responses: 0,1738                max_responses: 3,1739                total_requests: 3,1740            })),1741            None1742        );1743    }17441745    /// The cap applies to the fallback only, and never raises it.1746    #[test]1747    fn flexible_cap_bounds_the_default_but_not_an_explicit_expectation() {1748        let cap = Some(233_016);1749        // Unset: the worst case is cut down to the cap.1750        let (_, _, transformed, _) = Reservation::default().resolve(None, cap, true);1751        assert_eq!(transformed, 233_016);1752        // A small `max_response_bytes` already sits below the cap, so nothing changes.1753        let (_, _, transformed, _) = Reservation::default().resolve(Some(4_000), cap, true);1754        assert_eq!(transformed, 4_000 + CANDID_OVERHEAD_RESERVE_BYTES);1755        // An explicit expectation is used as given, above the cap or below it.1756        let reservation = Reservation {1757            transformed_response_bytes: Some(1_000_000),1758            ..Default::default()1759        };1760        let (_, _, transformed, _) = reservation.resolve(None, cap, true);1761        assert_eq!(transformed, 1_000_000);1762    }17631764    /// Without a transform the system never runs one, so nothing is reserved for it.1765    #[test]1766    fn no_transform_reserves_no_instructions() {1767        let (.., instructions) = Reservation::default().resolve(None, None, false);1768        assert_eq!(instructions, 0);1769        let (.., instructions) = Reservation::default().resolve(None, None, true);1770        assert_eq!(instructions, MAX_TRANSFORM_INSTRUCTIONS);1771        // An explicit expectation still wins, transform or not.1772        let reservation = Reservation {1773            transform_instructions: Some(7),1774            ..Default::default()1775        };1776        let (.., instructions) = reservation.resolve(None, None, false);1777        assert_eq!(instructions, 7);1778    }17791780    /// `request_bytes` counts the URL, the headers, the body and the transform.1781    #[test]1782    fn request_bytes_counts_every_variable_part() {1783        let headers = vec![HttpHeader {1784            name: "ab".to_string(),1785            value: "cde".to_string(),1786        }];1787        let body = vec![0u8; 7];1788        assert_eq!(1789            request_bytes("https://x", &headers, Some(&body), None),1790            (9 + 2 + 3 + 7) as u641791        );1792    }1793}17941795#[cfg(test)]1796mod install_tests {1797    use super::*;1798    #[test]1799    fn upgrades_encode_keep_and_cannot_skip_root_gate() {1800        use ic_management_canister_types::{CanisterInstallMode as Mode, WasmMemoryPersistence};1801        let encoded = candid::encode_one(InstallMode::Upgrade.wire()).unwrap();1802        let Mode::Upgrade(Some(flags)) = candid::decode_one::<Mode>(&encoded).unwrap() else {1803            panic!("missing upgrade flags")1804        };1805        assert_eq!(flags.skip_pre_upgrade, Some(false));1806        assert_eq!(1807            flags.wasm_memory_persistence,1808            Some(WasmMemoryPersistence::Keep)1809        );1810    }1811}