top_up_canister function

Future<Nat> top_up_canister(
  1. Caller caller,
  2. IcpTokens icp_tokens,
  3. Principal canister_id, {
  4. Uint8List? from_subaccount_bytes,
  5. Nat64? block_height,
})

Top-up the cycles on a canister with some ICP using the NNS ledger and the cycles-minting-canister.

Returns the amount of the cycles that the canister is topped up with.

Transforms the icp_tokens into cycles for the canister.

Use an optional from_subaccount_bytes to use ICP in a subaccount of the caller.

The block_height parameter has the same usage as in the create_canister function. Check the documentation for the create_canister function about the block_height parameter.

Implementation

Future<Nat> top_up_canister(Caller caller, IcpTokens icp_tokens, Principal canister_id, {Uint8List? from_subaccount_bytes, Nat64? block_height}) async {
    Uint8List to_subaccount_bytes = principal_as_an_icpsubaccountbytes(canister_id);

    if (block_height == null) {
        block_height = match_variant<Nat64>(await transfer_icp(
            caller,
            icp_id(SYSTEM_CANISTERS.cycles_mint.principal, subaccount_bytes: to_subaccount_bytes),
            icp_tokens,
            subaccount_bytes: from_subaccount_bytes,
            memo: MEMO_TOP_UP_CANISTER_nat64,
        ), {
            'Ok': (block_height) {
                return block_height as Nat64;
            },
            'Err': (transfer_error) {
                return match_variant<Never>(transfer_error as Variant, transfer_error_match_map);
            }
        });
        print('block_height: ${block_height.value}');
    } else {
        print('using given block_height: ${block_height.value}');
    }

    Record notifytopupargs = Record.of_the_map({
        'block_index' : block_height,
        'canister_id' : canister_id,
    });

    Variant notify_top_up_result = c_backwards(await SYSTEM_CANISTERS.cycles_mint.call(
        calltype: CallType.call,
        method_name: 'notify_top_up',
        put_bytes: c_forwards([notifytopupargs]),
        caller: caller
    ))[0] as Variant;

    return match_variant<Nat>(notify_top_up_result, {
        'Ok': (nat) {
            return nat as Nat;
        },
        'Err': (notify_error) {
            return match_variant<Never>(notify_error as Variant, cmc_notify_error_match_map);
        }
    });

}