use crate::{
call::AsyncCall, canister::Argument, interfaces::management_canister::MgmtMethod, Canister,
};
use async_trait::async_trait;
use candid::{CandidType, Deserialize, Nat};
use ic_agent::{export::Principal, AgentError, RequestId};
use std::str::FromStr;
pub use super::attributes::{ComputeAllocation, FreezingThreshold, MemoryAllocation};
use std::convert::{From, TryInto};
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct CanisterSettings {
pub controllers: Option<Vec<Principal>>,
pub compute_allocation: Option<Nat>,
pub memory_allocation: Option<Nat>,
pub freezing_threshold: Option<Nat>,
}
#[derive(Debug)]
pub struct CreateCanisterBuilder<'agent, 'canister: 'agent> {
canister: &'canister Canister<'agent>,
effective_canister_id: Principal,
controllers: Option<Result<Vec<Principal>, AgentError>>,
compute_allocation: Option<Result<ComputeAllocation, AgentError>>,
memory_allocation: Option<Result<MemoryAllocation, AgentError>>,
freezing_threshold: Option<Result<FreezingThreshold, AgentError>>,
is_provisional_create: bool,
amount: Option<u128>,
}
impl<'agent, 'canister: 'agent> CreateCanisterBuilder<'agent, 'canister> {
pub fn builder(canister: &'canister Canister<'agent>) -> Self {
Self {
canister,
effective_canister_id: Principal::management_canister(),
controllers: None,
compute_allocation: None,
memory_allocation: None,
freezing_threshold: None,
is_provisional_create: false,
amount: None,
}
}
#[allow(clippy::wrong_self_convention)]
pub fn as_provisional_create_with_amount(self, amount: Option<u128>) -> Self {
Self {
is_provisional_create: true,
amount,
..self
}
}
pub fn with_effective_canister_id<C, E>(self, effective_canister_id: C) -> Self
where
E: std::fmt::Display,
C: TryInto<Principal, Error = E>,
{
match effective_canister_id.try_into() {
Ok(effective_canister_id) => Self {
effective_canister_id,
..self
},
Err(_) => self,
}
}
pub fn with_optional_controller<C, E>(self, controller: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<Principal, Error = E>,
{
let controller_to_add: Option<Result<Principal, _>> = controller.map(|ca| {
ca.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
});
let controllers: Option<Result<Vec<Principal>, _>> =
match (controller_to_add, self.controllers) {
(_, Some(Err(sticky))) => Some(Err(sticky)),
(Some(Err(e)), _) => Some(Err(e)),
(None, _) => None,
(Some(Ok(controller)), Some(Ok(controllers))) => {
let mut controllers = controllers;
controllers.push(controller);
Some(Ok(controllers))
}
(Some(Ok(controller)), None) => Some(Ok(vec![controller])),
};
Self {
controllers,
..self
}
}
pub fn with_controller<C, E>(self, controller: C) -> Self
where
E: std::fmt::Display,
C: TryInto<Principal, Error = E>,
{
self.with_optional_controller(Some(controller))
}
pub fn with_optional_compute_allocation<C, E>(self, compute_allocation: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<ComputeAllocation, Error = E>,
{
Self {
compute_allocation: compute_allocation.map(|ca| {
ca.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_compute_allocation<C, E>(self, compute_allocation: C) -> Self
where
E: std::fmt::Display,
C: TryInto<ComputeAllocation, Error = E>,
{
self.with_optional_compute_allocation(Some(compute_allocation))
}
pub fn with_optional_memory_allocation<E, C>(self, memory_allocation: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<MemoryAllocation, Error = E>,
{
Self {
memory_allocation: memory_allocation.map(|ma| {
ma.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_memory_allocation<C, E>(self, memory_allocation: C) -> Self
where
E: std::fmt::Display,
C: TryInto<MemoryAllocation, Error = E>,
{
self.with_optional_memory_allocation(Some(memory_allocation))
}
pub fn with_optional_freezing_threshold<E, C>(self, freezing_threshold: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<FreezingThreshold, Error = E>,
{
Self {
freezing_threshold: freezing_threshold.map(|ma| {
ma.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_freezing_threshold<C, E>(self, freezing_threshold: C) -> Self
where
E: std::fmt::Display,
C: TryInto<FreezingThreshold, Error = E>,
{
self.with_optional_freezing_threshold(Some(freezing_threshold))
}
pub fn build(self) -> Result<impl 'agent + AsyncCall<(Principal,)>, AgentError> {
let controllers = match self.controllers {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(x),
None => None,
};
let compute_allocation = match self.compute_allocation {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u8::from(x))),
None => None,
};
let memory_allocation = match self.memory_allocation {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u64::from(x))),
None => None,
};
let freezing_threshold = match self.freezing_threshold {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u64::from(x))),
None => None,
};
#[derive(Deserialize, CandidType)]
struct Out {
canister_id: Principal,
}
let async_builder = if self.is_provisional_create {
#[derive(CandidType)]
struct In {
amount: Option<Nat>,
settings: CanisterSettings,
}
let in_arg = In {
amount: self.amount.map(Nat::from),
settings: CanisterSettings {
controllers,
compute_allocation,
memory_allocation,
freezing_threshold,
},
};
self.canister
.update_(MgmtMethod::ProvisionalCreateCanisterWithCycles.as_ref())
.with_arg(in_arg)
.with_effective_canister_id(self.effective_canister_id)
} else {
self.canister
.update_(MgmtMethod::CreateCanister.as_ref())
.with_arg(CanisterSettings {
controllers,
compute_allocation,
memory_allocation,
freezing_threshold,
})
.with_effective_canister_id(self.effective_canister_id)
};
Ok(async_builder
.build()
.map(|result: (Out,)| (result.0.canister_id,)))
}
pub async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
pub async fn call_and_wait(self) -> Result<(Principal,), AgentError> {
self.build()?.call_and_wait().await
}
}
#[async_trait]
impl<'agent, 'canister: 'agent> AsyncCall<(Principal,)>
for CreateCanisterBuilder<'agent, 'canister>
{
async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
async fn call_and_wait(self) -> Result<(Principal,), AgentError> {
self.build()?.call_and_wait().await
}
}
#[derive(Debug, Copy, Clone, CandidType, Deserialize, Eq, PartialEq)]
pub enum InstallMode {
#[serde(rename = "install")]
Install,
#[serde(rename = "reinstall")]
Reinstall,
#[serde(rename = "upgrade")]
Upgrade,
}
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct CanisterInstall {
pub mode: InstallMode,
pub canister_id: Principal,
#[serde(with = "serde_bytes")]
pub wasm_module: Vec<u8>,
#[serde(with = "serde_bytes")]
pub arg: Vec<u8>,
}
impl FromStr for InstallMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"install" => Ok(InstallMode::Install),
"reinstall" => Ok(InstallMode::Reinstall),
"upgrade" => Ok(InstallMode::Upgrade),
&_ => Err(format!("Invalid install mode: {}", s)),
}
}
}
#[derive(Debug)]
pub struct InstallCodeBuilder<'agent, 'canister: 'agent> {
canister: &'canister Canister<'agent>,
canister_id: Principal,
wasm: &'canister [u8],
arg: Argument,
mode: Option<InstallMode>,
}
impl<'agent, 'canister: 'agent> InstallCodeBuilder<'agent, 'canister> {
pub fn builder(
canister: &'canister Canister<'agent>,
canister_id: &Principal,
wasm: &'canister [u8],
) -> Self {
Self {
canister,
canister_id: *canister_id,
wasm,
arg: Default::default(),
mode: None,
}
}
pub fn with_arg<Argument: CandidType + Sync + Send>(
mut self,
arg: Argument,
) -> InstallCodeBuilder<'agent, 'canister> {
self.arg.push_idl_arg(arg);
self
}
pub fn with_raw_arg(mut self, arg: Vec<u8>) -> InstallCodeBuilder<'agent, 'canister> {
self.arg.set_raw_arg(arg);
self
}
pub fn with_mode(self, mode: InstallMode) -> Self {
Self {
mode: Some(mode),
..self
}
}
pub fn build(self) -> Result<impl 'agent + AsyncCall<()>, AgentError> {
Ok(self
.canister
.update_(MgmtMethod::InstallCode.as_ref())
.with_arg(CanisterInstall {
mode: self.mode.unwrap_or(InstallMode::Install),
canister_id: self.canister_id,
wasm_module: self.wasm.to_owned(),
arg: self.arg.serialize()?,
})
.with_effective_canister_id(self.canister_id)
.build())
}
pub async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
pub async fn call_and_wait(self) -> Result<(), AgentError> {
self.build()?.call_and_wait().await
}
}
#[async_trait]
impl<'agent, 'canister: 'agent> AsyncCall<()> for InstallCodeBuilder<'agent, 'canister> {
async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
async fn call_and_wait(self) -> Result<(), AgentError> {
self.build()?.call_and_wait().await
}
}
#[derive(Debug)]
pub struct UpdateCanisterBuilder<'agent, 'canister: 'agent> {
canister: &'canister Canister<'agent>,
canister_id: Principal,
controllers: Option<Result<Vec<Principal>, AgentError>>,
compute_allocation: Option<Result<ComputeAllocation, AgentError>>,
memory_allocation: Option<Result<MemoryAllocation, AgentError>>,
freezing_threshold: Option<Result<FreezingThreshold, AgentError>>,
}
impl<'agent, 'canister: 'agent> UpdateCanisterBuilder<'agent, 'canister> {
pub fn builder(canister: &'canister Canister<'agent>, canister_id: &Principal) -> Self {
Self {
canister,
canister_id: *canister_id,
controllers: None,
compute_allocation: None,
memory_allocation: None,
freezing_threshold: None,
}
}
pub fn with_optional_controller<C, E>(self, controller: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<Principal, Error = E>,
{
let controller_to_add: Option<Result<Principal, _>> = controller.map(|ca| {
ca.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
});
let controllers: Option<Result<Vec<Principal>, _>> =
match (controller_to_add, self.controllers) {
(_, Some(Err(sticky))) => Some(Err(sticky)),
(Some(Err(e)), _) => Some(Err(e)),
(None, _) => None,
(Some(Ok(controller)), Some(Ok(controllers))) => {
let mut controllers = controllers;
controllers.push(controller);
Some(Ok(controllers))
}
(Some(Ok(controller)), None) => Some(Ok(vec![controller])),
};
Self {
controllers,
..self
}
}
pub fn with_controller<C, E>(self, controller: C) -> Self
where
E: std::fmt::Display,
C: TryInto<Principal, Error = E>,
{
self.with_optional_controller(Some(controller))
}
pub fn with_optional_compute_allocation<C, E>(self, compute_allocation: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<ComputeAllocation, Error = E>,
{
Self {
compute_allocation: compute_allocation.map(|ca| {
ca.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_compute_allocation<C, E>(self, compute_allocation: C) -> Self
where
E: std::fmt::Display,
C: TryInto<ComputeAllocation, Error = E>,
{
self.with_optional_compute_allocation(Some(compute_allocation))
}
pub fn with_optional_memory_allocation<E, C>(self, memory_allocation: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<MemoryAllocation, Error = E>,
{
Self {
memory_allocation: memory_allocation.map(|ma| {
ma.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_memory_allocation<C, E>(self, memory_allocation: C) -> Self
where
E: std::fmt::Display,
C: TryInto<MemoryAllocation, Error = E>,
{
self.with_optional_memory_allocation(Some(memory_allocation))
}
pub fn with_optional_freezing_threshold<E, C>(self, freezing_threshold: Option<C>) -> Self
where
E: std::fmt::Display,
C: TryInto<FreezingThreshold, Error = E>,
{
Self {
freezing_threshold: freezing_threshold.map(|ma| {
ma.try_into()
.map_err(|e| AgentError::MessageError(format!("{}", e)))
}),
..self
}
}
pub fn with_freezing_threshold<C, E>(self, freezing_threshold: C) -> Self
where
E: std::fmt::Display,
C: TryInto<FreezingThreshold, Error = E>,
{
self.with_optional_freezing_threshold(Some(freezing_threshold))
}
pub fn build(self) -> Result<impl 'agent + AsyncCall<()>, AgentError> {
#[derive(CandidType)]
struct In {
canister_id: Principal,
settings: CanisterSettings,
}
let controllers = match self.controllers {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(x),
None => None,
};
let compute_allocation = match self.compute_allocation {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u8::from(x))),
None => None,
};
let memory_allocation = match self.memory_allocation {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u64::from(x))),
None => None,
};
let freezing_threshold = match self.freezing_threshold {
Some(Err(x)) => return Err(AgentError::MessageError(format!("{}", x))),
Some(Ok(x)) => Some(Nat::from(u64::from(x))),
None => None,
};
Ok(self
.canister
.update_(MgmtMethod::UpdateSettings.as_ref())
.with_arg(In {
canister_id: self.canister_id,
settings: CanisterSettings {
controllers,
compute_allocation,
memory_allocation,
freezing_threshold,
},
})
.with_effective_canister_id(self.canister_id)
.build())
}
pub async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
pub async fn call_and_wait(self) -> Result<(), AgentError> {
self.build()?.call_and_wait().await
}
}
#[async_trait]
impl<'agent, 'canister: 'agent> AsyncCall<()> for UpdateCanisterBuilder<'agent, 'canister> {
async fn call(self) -> Result<RequestId, AgentError> {
self.build()?.call().await
}
async fn call_and_wait(self) -> Result<(), AgentError> {
self.build()?.call_and_wait().await
}
}