# Automatically generate candid from rust sources

**URL:** <https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924>\
**Category:** Developers\
**Created:** [July 15, 2021, 4:17pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924 "2021-07-15T16:17:06Z")\
**Posts on this page:** 20\
**Page:** 3

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 12, 2023, 10:11pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/41 "2023-07-12T22:11:59Z")

</div>

> [@chenyan](#):
>
> You have your own build script anyway. What’s the difficulty in adding a few more lines?

It’s not about adding a few lines, it’s about the complexity of installing yet another dependency, a Wasm runtime, on an arbitrary developer’s machine. DFINITY has done a great job of getting dfx to work very well across architectures, we currently don’t have the infrastructure setup to easily precompile dependencies across architectures…maybe we’ve been doing it wrong, but it’s been difficult to deal with these issues.

cargo test caused problems in the past because of long compile times and issues compiling across architectures like I mentioned, then we switched to installing a wasm runtime across architectures which as had its own problems, the latest being that wasmer (and we had to switch away from wasmtime because there were issues with wasi) not working on Mac M1s, and now we’re trying to get the Candid out in post\_install using `__export_service` which is problematic for other reasons.

The developer experience for us and our users will be excellent if dfx can remove the requirement to specify a candid file and if it can automatically generate and obtain it from Rust canisters, even if those canisters are declared as custom.

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 12, 2023, 10:18pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/42 "2023-07-12T22:18:48Z")

</div>

There are at least two problems with retrieving the Candid in post\_install:

1. There is no way to put the Candid into the metadata before the first deploy
2. init/post\_upgrade params don’t work when deploying with dfx because apparently the `--argument` is not encoded or recognized by dfx since the Candid file is empty (in our case it is empty because on the first deploy we create a Candid file with an empty service, then on that post\_install we request the Candid and write it to disk, then on subsequent deploys everything is good unless the init/post\_upgrade params change)

I’m currently stuck on this problem right now, 1 isn’t too bad for the moment because `__get_candid_interface_tmp_hack` is supported by tooling, but 2 seems like a blocking issue (that I just discovered).

---

<div class="post-metadata">

**Author:** ![chenyan](https://avatars.discourse-cdn.com/v4/letter/c/35a633/32.png) [@chenyan](https://forum.dfinity.org/u/chenyan)\
**Post date:** [July 12, 2023, 10:54pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/43 "2023-07-12T22:54:31Z")

</div>

> Yes this helps a lot, but allowing custom canisters to turn on this option seems the more ideal solution so that we can remove this code entirely from our build process.

It’s not possible to remove this code entirely from the build process. dfx has no knowledge of how your build script works, so you will have to adapt the build script. dfx can certainly help by providing the necessary dependencies, e.g., wasmtime and ic-wasm in the cache. Your current approach for using post\_install is certainly problematic, and that’s what we want to fix.

> Actually this might not help, as I mentioned above I switched from wasmtime to wasmer because of issues with wasi, but perhaps you’ve overcome those issues in the cdk.

Maybe. We will have to see. Can you show me your build script, so that I can take a deeper look?

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 12, 2023, 11:05pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/44 "2023-07-12T23:05:17Z")

</div>

> [@chenyan](#):
>
> It’s not possible to remove this code entirely from the build process. dfx has no knowledge of how your build script works, so you will have to adapt the build script

If dfx sees a custom canister that has a property turned on to automatically generate the Candid from Rust code, couldn’t it look at the wasm binary path in the dfx.json and generate the Candid? I don’t see why this would require dfx to know anything about the custom build script. In fact I don’t even think dfx needs to care about the language, since it’s just running the Wasm binary through wasmtime. If dfx sees a property in the dfx.json instructing it to run the Wasm binary through wasmtime to retrieve the Candid, can’t it do that without needing to know anything else? This could be on by default for Rust canisters and off by default for custom canisters but with the option to turn it on.

Here’s our script on main for Kybra (doesn’t have the local wasmtime/wasmer execution, we now do everything in a post\_install script): [kybra/kybra/\_\_main\_\_.py at main · demergent-labs/kybra · GitHub](https://github.com/demergent-labs/kybra/blob/main/kybra/ __main__.py)

Here’s where we used to run wasmer: [kybra/kybra/candid.py at 3e74103a75faeafe6f5c9e6f433cb34888383332 · demergent-labs/kybra · GitHub](https://github.com/demergent-labs/kybra/blob/3e74103a75faeafe6f5c9e6f433cb34888383332/kybra/candid.py)

Here’s where we used to run Candid test: [kybra/kybra/\_\_main\_\_.py at 0.4.0 · demergent-labs/kybra · GitHub](https://github.com/demergent-labs/kybra/blob/0.4.0/kybra/ __main__.py#L440)

I might have been mistaken about my reasons for not using wasmtime, I think we may have been using wasmer from the beginning, I’m pretty sure I tried wasmtime first and then switched over to wasmer for reasons I don’t now remember.

P.S. we do something similar in Azle, the situation is much better in Azle because Node.js uses V8 which has Wasm support by default so we can just use that to generate the Candid relatively easily: [https://github.com/demergent-labs/azle/blob/main/src/compiler/generate\_candid\_file.ts](https://github.com/demergent-labs/azle/blob/main/src/compiler/generate_candid_file.ts)

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 28, 2023, 9:54pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/45 "2023-07-28T21:54:42Z")

</div>

So I want to reply to this comment: [Ic-cdk wasi feature - #8 by chenyan](https://forum.dfinity.org/t/ic-cdk-wasi-feature/21796/8)

Any updated thoughts on allowing custom canisters to turn this functionality on?

---

<div class="post-metadata">

**Author:** ![chenyan](https://avatars.discourse-cdn.com/v4/letter/c/35a633/32.png) [@chenyan](https://forum.dfinity.org/u/chenyan)\
**Post date:** [July 28, 2023, 10:00pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/46 "2023-07-28T22:00:40Z")

</div>

By definition, dfx won’t interfere with custom canisters. For Azle, you will have to adapt the build script [https://github.com/dfinity/cdk-rs/blob/main/examples/build.sh](https://github.com/dfinity/cdk-rs/blob/main/examples/build.sh) to use the new ic-cdk feature.

If the difficulty is in the extra dependency of wasmtime and ic-wasm, we will provide the binaries in dfx cache.

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 28, 2023, 10:02pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/47 "2023-07-28T22:02:28Z")

</div>

I didn’t realize that there were two different binaries, I think I understand some of the issues now. In that case I would ask if that situation can ever be addressed, so that there is only ever one binary produced that the candid can be extracted from and can be deployed. We are doing that right now, one compilation produces a binary that can be executed in a Wasm VM to obtain the Candid, and that same binary can be deployed to the IC.

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 28, 2023, 10:09pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/49 "2023-07-28T22:09:22Z")

</div>

This is how we’re able to produce just one Wasm binary that the Candid can be extracted from and that can be deployed to the IC:

Essentially we do this in the canister:

```rust
        candid::export_service!();

        // Heavily inspired by https://stackoverflow.com/a/47676844
        #[no_mangle]
        pub fn get_candid_pointer() -> *mut std::os::raw::c_char {
            let c_string = std::ffi::CString::new(__export_service()).unwrap();

            c_string.into_raw()
        }

```

And we do this in Node.js during the build step:

```typescript
import { readFileSync, writeFileSync } from 'fs';

export function generateCandidFile(candidPath: string, wasmFilePath: string) {
    const wasmBuffer = readFileSync(wasmFilePath);

    const wasmModule = new WebAssembly.Module(wasmBuffer);
    const wasmInstance = new WebAssembly.Instance(wasmModule, {
        ic0: {
            accept_message: () => {},
            call_cycles_add: () => {},
            call_cycles_add128: () => {},
            call_data_append: () => {},
            call_new: () => {},
            call_on_cleanup: () => {},
            call_perform: () => {},
            canister_cycle_balance: () => {},
            canister_cycle_balance128: () => {},
            canister_self_copy: () => {},
            canister_self_size: () => {},
            canister_version: () => {},
            certified_data_set: () => {},
            data_certificate_copy: () => {},
            data_certificate_present: () => {},
            data_certificate_size: () => {},
            debug_print: () => {},
            global_timer_set: () => {},
            instruction_counter: () => {},
            is_controller: () => {},
            msg_arg_data_copy: () => {},
            msg_arg_data_size: () => {},
            msg_caller_copy: () => {},
            msg_caller_size: () => {},
            msg_cycles_accept: () => {},
            msg_cycles_accept128: () => {},
            msg_cycles_available: () => {},
            msg_cycles_refunded: () => {},
            msg_cycles_refunded128: () => {},
            msg_method_name_copy: () => {},
            msg_method_name_size: () => {},
            msg_reject_code: () => {},
            msg_reject_msg_copy: () => {},
            msg_reject_msg_size: () => {},
            msg_reject: () => {},
            msg_reply_data_append: () => {},
            msg_reply: () => {},
            performance_counter: () => {},
            stable_grow: () => {},
            stable_read: () => {},
            stable_size: () => {},
            stable_write: () => {},
            stable64_grow: () => {},
            stable64_read: () => {},
            stable64_size: () => {},
            stable64_write: () => {},
            time: () => {},
            trap: () => {}
        }
    });

    const candidPointer = (wasmInstance.exports as any).get_candid_pointer();

    const memory = new Uint8Array((wasmInstance.exports.memory as any).buffer);

    let candidBytes = [];
    let i = candidPointer;
    while (memory[i] !== 0) {
        candidBytes.push(memory[i]);
        i += 1;
    }

    writeFileSync(candidPath, Buffer.from(candidBytes));
}

```

---

<div class="post-metadata">

**Author:** ![chenyan](https://avatars.discourse-cdn.com/v4/letter/c/35a633/32.png) [@chenyan](https://forum.dfinity.org/u/chenyan)\
**Post date:** [July 28, 2023, 10:11pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/50 "2023-07-28T22:11:04Z")

</div>

> We are doing that right now, one compilation produces a binary that can be executed in a Wasm VM to obtain the Candid

IIUC, you are taking a more complicated detour to achieve that. So using the new ic-cdk feature is an improvement.

> In that case I would ask if that situation can ever be addressed, so that there is only ever one binary produced that the candid can be extracted from and can be deployed.

Probably not. Not without changing rustc or the rust analyzer. However, developer can also choose an opposite direction similar to protobuf: Developers write candid file as the source of truth to define data types and API. We can then provide tools to generate bindings from candid to the host language. If we go with this approach, we don’t need to generate did file anymore.

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [July 28, 2023, 10:12pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/51 "2023-07-28T22:12:02Z")

</div>

Ideally we could remove this code, remove the similar code in Kybra, not be required to generate Candid at all, and remove the need for the developer to specify a path to a Candid file in dfx.json.

---

<div class="post-metadata">

**Author:** ![dfx-json](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/dfx-json/32/4784_2.png) [@dfx-json](https://forum.dfinity.org/u/dfx-json)\
**Post date:** [August 2, 2023, 3:17pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/52 "2023-08-02T15:17:25Z")

</div>

Hi @lastmjs - we have a developer tooling working group session tomorrow (8/3) and this will be one of the topics we will discuss. I encourage you to attend to voice what you’d like to see and help us shape the feature.

---

<div class="post-metadata">

**Author:** ![lwshang](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lwshang/32/3394_2.png) [@lwshang](https://forum.dfinity.org/u/lwshang)\
**Post date:** [August 2, 2023, 4:29pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/53 "2023-08-02T16:29:11Z")

</div>

For the upcoming group session, I summarized my thoughts [here](https://forum.dfinity.org/t/technical-working-group-developer-tooling/11941/49).

---

<div class="post-metadata">

**Author:** ![lastmjs](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/lastmjs/32/3406_2.png) [@lastmjs](https://forum.dfinity.org/u/lastmjs)\
**Post date:** [August 5, 2023, 4:28am UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/54 "2023-08-05T04:28:23Z")

</div>

Unfortunately I wasn’t able to attend the session.

---

<div class="post-metadata">

**Author:** ![Dustin](https://avatars.discourse-cdn.com/v4/letter/d/5daacb/32.png) [@Dustin](https://forum.dfinity.org/u/Dustin)\
**Post date:** [August 19, 2023, 8:44am UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/55 "2023-08-19T08:44:22Z")

</div>

Is the feature to automatically generate .did files from rust code available somewhere? If not, is there an expected timeline for the release? I’m fully with @lastmjs on this. This feature is important for a good developer experience. Spent the last few hours looking for the problem until I realised the automatic generation for rust canisters wasn’t available.

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [August 19, 2023, 1:21pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/56 "2023-08-19T13:21:14Z")

</div>

> [@Dustin](#):
>
> Is the feature to automatically generate .did files from rust code available somewhere?

Yes you can now generate the did from Rust without workaround but, it needs an additional script / call to wastime afterwards. Ultimately I understand the goal is to make all automatic.

I wrote a post about last improvements and current state, hope that helps:

[https://daviddalbusco.medium.com/automatic-candid-generation-in-rust-exploring-the-ic-cdk-v0-10-0-update-d1ad76bd4f69](https://daviddalbusco.medium.com/automatic-candid-generation-in-rust-exploring-the-ic-cdk-v0-10-0-update-d1ad76bd4f69)

---

<div class="post-metadata">

**Author:** ![Dustin](https://avatars.discourse-cdn.com/v4/letter/d/5daacb/32.png) [@Dustin](https://forum.dfinity.org/u/Dustin)\
**Post date:** [August 19, 2023, 1:43pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/57 "2023-08-19T13:43:14Z")

</div>

This is perfect, thanks!

---

<div class="post-metadata">

**Author:** ![sadernalwis](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/sadernalwis/32/12288_2.png) [@sadernalwis](https://forum.dfinity.org/u/sadernalwis)\
**Post date:** [September 14, 2023, 4:33pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/59 "2023-09-14T16:33:25Z")

</div>

Well @peterparker’s solution works up until `stable--structures` are used.  
the workaround for the original workaround involving updating “ic-cdk”  
[PR](https://github.com/dfinity/stable-structures/pull/108)  
has been rejected.  
Is there a way to do it all within ic sdk?

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [September 14, 2023, 4:40pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/60 "2023-09-14T16:40:09Z")

</div>

I literally complained about this today and literally also shared the wording “it’s a pain in the a” with my colleagues.

The PR you mention wasn’t a proper solution for a definitive implementation. Team is now trying their best to push the effort.

There is a draft PR opened in the cdk-rs ([feat: sdk 1227 by lwshang · Pull Request #424 · dfinity/cdk-rs · GitHub](https://github.com/dfinity/cdk-rs/pull/424)), there will be a new CLI tool and now there are discussing the integration in dfx.

Meanwhile, using above PR ([chore: update ic-cdk to 0.10 by lwshang · Pull Request #108 · dfinity/stable-structures · GitHub](https://github.com/dfinity/stable-structures/pull/108)) remains the workaround I know.

i.e. I generally develop and only when I want to generate the did files, I switch the source of the crate in the toml file.

---

<div class="post-metadata">

**Author:** ![sadernalwis](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/sadernalwis/32/12288_2.png) [@sadernalwis](https://forum.dfinity.org/u/sadernalwis)\
**Post date:** [September 14, 2023, 5:21pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/61 "2023-09-14T17:21:49Z")

</div>

definitely a pain in the A 😅 .  
seems like I will have to keep both solutions,  
ur script and “\_\_get\_candid\_interface\_tmp\_hack”

```auto
"generate_old": "scripts/build_did.sh && dfx generate backend",
"generate": "cargo test generate_candid && dfx generate backend",

```

thank you really for the script and pushing this. 🙏

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [September 18, 2023, 7:08pm UTC](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924/62 "2023-09-18T19:08:31Z")

</div>

Great news @sadernalwis , the `stable--structures` incompatibility has been resolved by today’s release of the new `ic_cdk@0.11.0` and the new CLI tool [candid-extractor](https://crates.io/crates/candid-extractor).

I updated my blog post but, to summarize the difference:

1. bump ic\_cdk and related libraries

2. install `candid-extractor`

3. update the `did.sh` script I provided as follow

```auto
#!/usr/bin/env bash

function generate_did() {
  local canister=$1
  canister_root="src/$canister"

  cargo build --manifest-path="$canister_root/Cargo.toml" \
      --target wasm32-unknown-unknown \
      --release --package "$canister"

  candid-extractor "target/wasm32-unknown-unknown/release/$canister.wasm" > "$canister_root/$canister.did"
}

# The list of canisters of your project
CANISTERS=console,observatory,mission_control,satellite

for canister in $(echo $CANISTERS | sed "s/,/ /g")
do
    generate_did "$canister"
done

```

Big shout-out to @lwshang for this improvement 🙏. Not all heroes wear capes!!!

[Previous page](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924.md?page=2)

[Next page](https://forum.dfinity.org/t/automatically-generate-candid-from-rust-sources/5924.md?page=4)
