Skip to main content

Generating Candid files for Rust canisters

Beginner
Rust

Candid interface files (.did) are not generated automatically for Rust canisters like they are for Motoko canisters. For Rust canisters, you can:

  1. Write the .did file yourself
  2. Use the candid-extractor and generate-did tools to extract the Candid from the canister's Wasm.

Using candid-extractor and generate-did tools

Step 1: Install candid-extractor

You need to install the candid-extractor, which is required for extracting the .did file in both approaches:

cargo install candid-extractor

Step 2: Add the export_candid! macro

In your Rust canister code, call the export_candid! macro at the end of your lib.rs file:

use ic_cdk::query;
use ic_cdk::update;

#[query]
fn hello(name: String) -> String {
format!("Hello, {}!", name)
}

#[update]
fn world(name: String) -> String {
format!("World, {}!", name)
}

// Enable Candid export
ic_cdk::export_candid!();

Step 3: Generate the .did file:

You can now choose one of the following options:

Option 1: Automatic generation using generate-did crate.

generate-did automates the build and extraction process into a single command.

Install it with:

cargo install generate-did

candid-extractor must be installed and in your PATH and the canister must be buildable to Wasm run from your project root.

Then, run:

generate-did <canister_name>

Replace <canister_name> with the directory name of your canister (which must include a valid Cargo.toml).

This command will:

  • Build the canister to Wasm.
  • Extract the Candid interface.
  • Place the .did file directly into the canister directory.

For more details, see:

Option 2: Manual extraction using candid-extractor.

Before extracting the Candid interface, you must first compile the canister's Wasm module:

cargo build --release --target wasm32-unknown-unknown --package <CANISTER>

The Wasm module will be stored at:

target/wasm32-unknown-unknown/release/<CANISTER>.wasm

Then you can extract the Candid interface from the Wasm module and save it to a file:

candid-extractor target/wasm32-unknown-unknown/release/<CANISTER>.wasm > <CANISTER>.did