Calling a canister function from a standalone rust program

Hello!

I have written a basic canister and deployed/tested it on my laptop with dfx.

Now I would like to write a standalone rust program that calls the canister’s functions.

Can you please point me to some code examples so I can study how this is best accomplished?

Thank you!

Here’s a simple helper that I’ve written for a quickstart bounty, that sends some bytes to the canister: ic-quickstart-actor-model/main.rs at main · GLicDEV/ic-quickstart-actor-model · GitHub

The main thing is in this piece of code:

let (response,) = canister
        .update_("load_wasm")
        .with_arg_raw(Encode!(&wasm).unwrap())
        .build::<(bool,)>()
        .call_and_wait(waiter)
        .await
        .unwrap();

Here the canister exposes a function called “load_wasm” and expects a vec[u8] and returns a bool. Let me know if you have any questions and I’ll do my best to help.

Note that “Encode!” will help you encode the arguments, whatever the canister expects, and the type you specify in build::<(type,) should match the returned type of the function you are calling. Also note that this is a (tuple,) → this is done so that some type magic works in the back.

If you want to see more examples, I usually search Dfinity’s git repo for the functions I’d like to explore (update_ in this case) and read through the results. Hint: look for the end to end test cases, there’s lots of code for calling and interacting with canisters there.

2 Likes

This is very useful – thank you very much indeed!