-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add ic-canister-runtime crate
#35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+224
−1
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| ../LICENSE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| ../NOTICE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.