Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["canhttp", "examples/http_canister"]
members = ["canhttp", "examples/http_canister", "ic-canister-runtime"]
resolver = "2"

[workspace.package]
Expand All @@ -12,6 +12,7 @@ readme = "README.md"

[workspace.dependencies]
assert_matches = "1.5.0"
async-trait = "0.1.88"
candid = { version = "0.10.13" }
ciborium = "0.2.2"
futures-channel = "0.3.31"
Expand Down
8 changes: 8 additions & 0 deletions ic-canister-runtime/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
22 changes: 22 additions & 0 deletions ic-canister-runtime/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "ic-canister-runtime"
version = "0.1.0"
description = "Rust library that abstracts the canister runtime on the Internet Computer"
license.workspace = true
readme.workspace = true
homepage.workspace = true
authors.workspace = true
edition.workspace = true
include = ["src", "Cargo.toml", "CHANGELOG.md", "LICENSE", "README.md"]
repository.workspace = true
documentation = "https://docs.rs/ic-canister-runtime"

[dependencies]
async-trait = { workspace = true }
candid = { workspace = true }
ic-cdk = { workspace = true }
ic-error-types = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }

[dev-dependencies]
1 change: 1 addition & 0 deletions ic-canister-runtime/LICENSE
1 change: 1 addition & 0 deletions ic-canister-runtime/NOTICE
162 changes: 162 additions & 0 deletions ic-canister-runtime/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
//! Library to abstract the canister runtime so that code making requests to canisters can be reused:
//! * in production using [`ic_cdk`],
//! * in unit tests by mocking this trait,
//! * in integration tests by implementing this trait for `PocketIc`.

#![forbid(unsafe_code)]
#![forbid(missing_docs)]

use async_trait::async_trait;
use candid::{utils::ArgumentEncoder, CandidType, Principal};
use ic_cdk::call::{Call, CallFailed, CandidDecodeFailed};
use ic_error_types::RejectCode;
use serde::de::DeserializeOwned;
use thiserror::Error;

/// Abstract the canister runtime so that code making requests to canisters can be reused:
/// * in production using [`ic_cdk`],
/// * in unit tests by mocking this trait,
/// * in integration tests by implementing this trait for `PocketIc`.
#[async_trait]
pub trait Runtime {
/// Defines how asynchronous inter-canister update calls are made.
async fn update_call<In, Out>(
&self,
id: Principal,
method: &str,
args: In,
cycles: u128,
) -> Result<Out, IcError>
where
In: ArgumentEncoder + Send,
Out: CandidType + DeserializeOwned;

/// Defines how asynchronous inter-canister query calls are made.
async fn query_call<In, Out>(
&self,
id: Principal,
method: &str,
args: In,
) -> Result<Out, IcError>
where
In: ArgumentEncoder + Send,
Out: CandidType + DeserializeOwned;
}

/// Error returned by the Internet Computer when making an inter-canister call.
#[derive(Error, Clone, Debug, PartialEq, Eq)]
pub enum IcError {
/// The liquid cycle balance is insufficient to perform the call.
#[error("Insufficient liquid cycles balance, available: {available}, required: {required}")]
InsufficientLiquidCycleBalance {
/// The liquid cycle balance available in the canister.
available: u128,
/// The required cycles to perform the call.
required: u128,
},

/// The `ic0.call_perform` operation failed when performing the inter-canister call.
#[error("Inter-canister call perform failed")]
CallPerformFailed,

/// The inter-canister call is rejected.
#[error("Inter-canister call rejected: {code:?} - {message})")]
CallRejected {
/// Rejection code as specified [here](https://internetcomputer.org/docs/current/references/ic-interface-spec#reject-codes)
code: RejectCode,
/// Associated helper message.
message: String,
},

/// The response from the inter-canister call could not be decoded as Candid.
#[error("The inter-canister call response could not be decoded: {message}")]
CandidDecodeFailed {
/// The specific Candid error that occurred.
message: String,
},
}

impl From<CallFailed> for IcError {
fn from(err: CallFailed) -> Self {
match err {
CallFailed::CallPerformFailed(_) => IcError::CallPerformFailed,
CallFailed::CallRejected(e) => {
IcError::CallRejected {
// `CallRejected::reject_code()` can only return an error result if there is a
// new error code on ICP that the CDK is not aware of. We map it to `SysFatal`
// since none of the other error codes apply.
// In particular, note that `RejectCode::SysUnknown` is only applicable to
// inter-canister calls that used `ic0.call_with_best_effort_response`.
code: e.reject_code().unwrap_or(RejectCode::SysFatal),
message: e.reject_message().to_string(),
}
}
CallFailed::InsufficientLiquidCycleBalance(e) => {
IcError::InsufficientLiquidCycleBalance {
available: e.available,
required: e.required,
}
}
}
}
}

impl From<CandidDecodeFailed> for IcError {
fn from(err: CandidDecodeFailed) -> Self {
IcError::CandidDecodeFailed {
message: err.to_string(),
}
}
}

/// Runtime when interacting with a canister running on the Internet Computer.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
pub struct IcRuntime {
_private: (),
}

impl IcRuntime {
/// Create a new instance of [`IcRuntime`].
pub fn new() -> Self {
Self::default()
}
}

#[async_trait]
impl Runtime for IcRuntime {
async fn update_call<In, Out>(
&self,
id: Principal,
method: &str,
args: In,
cycles: u128,
) -> Result<Out, IcError>
where
In: ArgumentEncoder + Send,
Out: CandidType + DeserializeOwned,
{
Call::unbounded_wait(id, method)
.with_args(&args)
.with_cycles(cycles)
.await
.map_err(IcError::from)
.and_then(|response| response.candid::<Out>().map_err(IcError::from))
}

async fn query_call<In, Out>(
&self,
id: Principal,
method: &str,
args: In,
) -> Result<Out, IcError>
where
In: ArgumentEncoder + Send,
Out: CandidType + DeserializeOwned,
{
Call::unbounded_wait(id, method)
.with_args(&args)
.await
.map_err(IcError::from)
.and_then(|response| response.candid::<Out>().map_err(IcError::from))
}
}
5 changes: 5 additions & 0 deletions release-plz.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ name = "canhttp"
#git_release_enable = false # enable GitHub releases
publish = true # enable `cargo publish`

[[package]]
name = "ic-canister-runtime"
#git_release_enable = false # enable GitHub releases
publish = true # enable `cargo publish`

[[package]]
name = "http_canister"
release = false # don't process this package