Is it possible to auto generate motoko types from candid? Or to import candid directly to motoko somehow?

To call canisters from motoko that are not written in motoko.

Thereā€™s a tool called didc that you can use.

$ cat first_project.did 
service : {
    "greet": (text) -> (text) query;
}

USAGE:
    didc bind <input> --target <target>

OPTIONS:
    -t, --target <target>    Specifies target language [possible values: js, ts, did, mo,
                             rs]

$ didc bind first_project.did --target mo
// This is a generated Motoko binding.
// Please use `import service "ic:canister_id"` instead to call canisters on the IC if possible.

module { public type Self = actor { greet : shared query Text -> async Text } }


$ didc bind first_project.did --target rs
// This is an experimental feature to generate Rust binding from Candid.
// You may want to manually adjust some of the types.
use ic_cdk::export::candid::{self, CandidType, Deserialize};
use ic_cdk::api::call::CallResult;

struct SERVICE(candid::Principal);
impl SERVICE{
  pub async fn greet(&self, arg0: String) -> CallResult<(String,)> {
    ic_cdk::call(self.0, "greet", (arg0,)).await
  }
}
1 Like

See Importing from another canister

This part is admittedly a bit vague:

For the imported canister actor, types are derived from the Candid file ā€” the project-name.did file ā€” for the canister rather than from Motoko itself.

Perhaps someone more familiar with this feature of Motoko can help with that.

Define the service type you want to call and then declare an actor of that type.

Here is the ledger declaration: origyn_nft/dfxtypes.mo at main Ā· ORIGYN-SA/origyn_nft Ā· GitHub

Here it is used:

1 Like

import "canister:name" imports the service type from the did file, even if the canister is written in Motoko. This ensures we can call canisters written in other languages.

Thank you all very much that is helpful.

@chenyan that does not work for a canister class correct?

You mean for actor class? Yes, for actor class, you will need to import the mo file directly. Because there is no counterpart in the Rust CDK to define an actor class.