use candid::{CandidType, Nat, Principal};
use ic_cdk::call::Call;
use serde::Deserialize;
#[derive(CandidType, Deserialize, Clone, Debug)]
pub struct Account {
pub owner: Principal,
pub subaccount: Option<Vec<u8>>,
}
fn account(owner: Principal) -> Account {
Account {
owner,
subaccount: None,
}
}
#[derive(CandidType, Deserialize, Debug)]
struct TransferFromArgs {
to: Account,
fee: Option<Nat>,
spender_subaccount: Option<Vec<u8>>,
from: Account,
memo: Option<Vec<u8>>,
created_at_time: Option<u64>,
amount: Nat,
}
#[derive(CandidType, Deserialize, Debug)]
struct TransferArgs {
to: Account,
fee: Option<Nat>,
memo: Option<Vec<u8>>,
from_subaccount: Option<Vec<u8>>,
created_at_time: Option<u64>,
amount: Nat,
}
#[derive(CandidType, Deserialize, Debug)]
struct WithdrawArgs {
to: Principal,
from_subaccount: Option<Vec<u8>>,
created_at_time: Option<u64>,
amount: Nat,
}
#[derive(CandidType, Deserialize, Debug)]
enum LedgerError {
GenericError {
message: String,
error_code: Nat,
},
TemporarilyUnavailable,
BadBurn {
min_burn_amount: Nat,
},
Duplicate {
duplicate_of: Nat,
},
BadFee {
expected_fee: Nat,
},
CreatedInFuture {
ledger_time: u64,
},
TooOld,
InsufficientFunds {
balance: Nat,
},
InsufficientAllowance {
allowance: Nat,
},
FailedToWithdraw {
rejection_code: RejectionCode,
fee_block: Option<Nat>,
rejection_reason: String,
},
InvalidReceiver {
receiver: Principal,
},
}
#[derive(CandidType, Deserialize, Debug)]
enum RejectionCode {
NoError,
SysFatal,
SysTransient,
DestinationInvalid,
CanisterReject,
CanisterError,
Unknown,
}
#[derive(CandidType, Deserialize, Debug)]
enum LedgerResult {
Ok(Nat),
Err(LedgerError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Failure {
Rejected(String),
Refused(String),
FeeCharged(String),
Undecodable(String),
}
impl Failure {
pub fn nothing_moved(&self) -> bool {
matches!(self, Failure::Rejected(_) | Failure::Refused(_))
}
pub fn message(&self) -> String {
match self {
Failure::Rejected(m) | Failure::Refused(m) => m.clone(),
Failure::FeeCharged(m) => format!("{m}; the amount came back but the fee was charged"),
Failure::Undecodable(m) => format!(
"{m}; the transfer may have gone through, so nothing was undone and the amount is recorded as unreconciled for the operator"
),
}
}
}
async fn call(ledger: Principal, method: &str, arg: impl CandidType) -> Result<u128, Failure> {
let res = Call::unbounded_wait(ledger, method)
.with_arg(arg)
.await
.map_err(|e| Failure::Rejected(format!("{method}: {e:?}")))?;
match res.candid::<LedgerResult>() {
Ok(LedgerResult::Ok(n)) => nat_to_u128(n)
.ok_or_else(|| Failure::Undecodable(format!("{method}: block index above u128"))),
Ok(LedgerResult::Err(e)) => {
let m = format!("{method}: ledger refused: {e:?}");
Err(match e {
LedgerError::FailedToWithdraw {
fee_block: Some(_), ..
} => Failure::FeeCharged(m),
_ => Failure::Refused(m),
})
}
Err(e) => Err(Failure::Undecodable(format!(
"{method}: undecodable reply: {e}"
))),
}
}
fn nat_to_u128(n: Nat) -> Option<u128> {
u128::try_from(n.0).ok()
}
pub async fn fee(ledger: Principal) -> Result<u128, Failure> {
let res = Call::unbounded_wait(ledger, "icrc1_fee")
.await
.map_err(|e| Failure::Rejected(format!("icrc1_fee: {e:?}")))?;
let n = res
.candid::<Nat>()
.map_err(|e| Failure::Undecodable(format!("icrc1_fee: undecodable reply: {e}")))?;
nat_to_u128(n).ok_or_else(|| Failure::Undecodable("icrc1_fee: fee above u128".to_string()))
}
pub async fn pull(
ledger: Principal,
payer: Principal,
amount: u128,
fee: u128,
) -> Result<u128, Failure> {
call(
ledger,
"icrc2_transfer_from",
TransferFromArgs {
to: account(ic_cdk::api::canister_self()),
fee: Some(Nat::from(fee)),
spender_subaccount: None,
from: account(payer),
memo: None,
created_at_time: None,
amount: Nat::from(amount),
},
)
.await
}
pub async fn pay(
ledger: Principal,
to: Principal,
amount: u128,
fee: u128,
) -> Result<u128, Failure> {
call(
ledger,
"icrc1_transfer",
TransferArgs {
to: account(to),
fee: Some(Nat::from(fee)),
memo: None,
from_subaccount: None,
created_at_time: None,
amount: Nat::from(amount),
},
)
.await
}
pub async fn fund_self(ledger: Principal, amount: u128) -> Result<u128, Failure> {
call(
ledger,
"withdraw",
WithdrawArgs {
to: ic_cdk::api::canister_self(),
from_subaccount: None,
created_at_time: None,
amount: Nat::from(amount),
},
)
.await
}