Automatically generate candid from rust sources

I see the macros candid::export_service!(), but how do I use it?
Should I implement another macros that will call __export_service() and write a file with the content it returns or what?

Try this

}

export_service!();

#[ic_cdk_macros::query(name = "__get_candid_interface_tmp_hack")]
fn export_candid() -> String {
    __export_service()
}

(taken from candid/lib.rs at a555d77704d691bb8f34e21a049d44ba0acee3f8 · dfinity/candid · GitHub).

It would probably a reasonable feature request for cdk-rs to provide all of the above under a single macro (expose_candid_interface()). This would especially be useful if the underlying interface changes – then people just have to recompile their canisters, but not change any code.

3 Likes

Thanks!

But what do I write under candid key in my dfx.json?
In the mentioned example there is a valid candid file already written by hand.

The problem I want to solve is to generate .did file automatically.

There is a PR for generating did files: feat: export candid by chenyan-dfinity · Pull Request #28 · dfinity/cdk-rs · GitHub

The proposed solution requires compiling the code twice, one for WASI and one for IC. Not ideal, but works.

2 Likes

I believe it pays off to have your .did file committed to the repository, documented, and curated manually. This is the face of your canister, the main thing that people who integrate with your canister will care about. It’s a lot like a header file for a C/C++ library or a module interface file in OCaml.

Being able to generate a .did file automatically is still very useful:

  1. You can use it get the first version of the .did file that you can edit by hand afterwards.
  2. You can use it to generate the actual interface of your canister and pipe it to didc subtype as a precommit hook to make sure that the manually curated .did file is not obsolete.

IC governance canister adds a main function that outputs the .did file when compiled in native mode:

The generated governance.did file is also committed to the repository: ic/governance.did at 40ab84f4fcb9e6c2441e91a59cfaa5acf84fe38d · dfinity/ic · GitHub

4 Likes