Nood question, probably not the last, but, how do you convert candid::nat
to u128
?
I try to transfer cycles before deleting a canister.
let arg = CanisterIdRecord { canister_id: ic_cdk::id() };
let response = canister_status(arg).await.unwrap().0; // <- here candid::nat
The status returns candid::nat
but
let cycles: Nat = response.cycles - Nat::from(100_000_000_000u128);
deposit_cycles(arg_deposit, cycles).await.unwrap(); // <- here it needs u128
to deposit I need u128
AdamS
October 21, 2022, 10:47pm
2
The underlying BigUint is a public field on the Nat type - just .0
again. Then you can convert that to u128 via TryFrom or ToPrimitive.
Note that if you’re trying to get the balance of the current canister, that’s a system function and you don’t have to go through the management canister - ic_cdk::api::canister_balance128()
3 Likes
Thanks for the solution and explanation @AdamS , it did the job.
canister_balance128
is also a good tips, I’ll use it. I was using canister_status
because I am still hoping that somewhere there is an information about the minimal amount of cycles to retain before deleting a canister .
If it can be useful in the future for anyone landing on this, here the implementation of above elements:
use ic_cdk::api::management_canister::main::{ CanisterIdRecord, deposit_cycles };
use ic_cdk::api::{ canister_balance128 };
#[update]
async fn transfer_cycles() {
// TODO: determine effective threshold - how few cycles should be retained before deleting the canister?
// use freezing_threshold_in_cycles? - https://github.com/dfinity/interface-spec/pull/18/files
// actually above PR was ultimately deleted? - https://forum.dfinity.org/t/minimal-cycles-to-delete-canister/15926
// Source: https://forum.dfinity.org/t/candid-nat-to-u128/16016
let balance: u128 = canister_balance128();
let cycles: u128 = balance - 100_000_000_000u128;
if cycles > 0 {
let arg_deposit = CanisterIdRecord { canister_id: caller };
deposit_cycles(arg_deposit, cycles).await.unwrap();
}
}
2 Likes