Rust ic_cdk: Minimal example of passing argument to `main::install_code` and decoding inside the target canister

The install_code function provided by the Rust CDK has a mechanism to pass arguments to the target canister as part of the InstallCodeArgument as documented here.

Is there a minimal example I can refer that demonstrates how to use this to correctly encode and decode the argument that I wish to pass. I wish to be able to refer to that value in the post_upgrade as documented is possible

The argument that I wish to pass is a custom struct containing some primitive values.


I think you just need to candid encode the struct, e.g. with candid - Rust, but I haven’t done this myself.

Thank you. Let me try and come back with findings

1 Like

For someone else stumbling onto this,

The solution is to encode using candid::encode_args as demonstrated in the example

And on the receiving end, use call::arg_data. Specifically, use the turbofish syntax to parse it to the exact shape you expect it to be.

Btw, it also requires them to be in a tuple even if passing a single argument.

This is what my code looks like:

Sender side

let arg = candid::encode_args((version_number,))
                .expect("Failed to serialize the install argument.");

Receiving side

call::arg_data::<(u64, )>().0
1 Like

On the receiving side, if you are using #[ic_cdk_macros::init], you can just add a function parameter, same as with query or update.


Oh, that’s quite cool that it’s taken care of by the CDK macro.

We really need to better document these nuggets of information

EDIT: It’s already documented here

It is documented in the init macro’s docs :wink:

1 Like

Hey, I’ve played with this before. Here’s how I handled it:

  1. In code, from rust to rust. You can create a struct however you’d like, and pass it in install_code, like so: quickstart_scaling/ at 3c9a65ee19c0fa458d4ddc8582c76d7bd6dbdbdf · GLicDEV/quickstart_scaling · GitHub

On the receiving side, you get it like so: quickstart_scaling/ at 3c9a65ee19c0fa458d4ddc8582c76d7bd6dbdbdf · GLicDEV/quickstart_scaling · GitHub

  1. For compatibility with dfx, and for automatic did generation, you can append your init function with the proper macro, as described here: How to pass install arguments from dfx?

Hope this helps

1 Like