Fetch remote candid and convert it to JavaScript

Hey,
in my use case I try to get some candid information from a remote canister and later I’m going to call a function from the remote canister.

To do so I use the following solution I have found:

# fetch the candid
const candid_source = await fetchCandid(canisterId, agent);

to fetch the candid as text from the remote canister, then I convert this text to javascript with the following function:

async candidToJS (candid_source: string){
    // call didjs canister
    const didjs_interface: IDL.InterfaceFactory = ({ IDL }) =>
      IDL.Service({
        did_to_js: IDL.Func([IDL.Text], [IDL.Opt(IDL.Text)], ["query"]),
    });
  
    const candidCanister = 'a4gq6-oaaaa-aaaab-qaa4q-cai';
    const agent2 = HttpAgent.createSync({ host:"https://icp-api.io" });
    
    const didjs = Actor.createActor(didjs_interface, {
      agent: agent2,
      canisterId: candidCanister,
    });
  
    const js: any = await didjs['did_to_js'](candid_source);
    if (Array.isArray(js) && js.length === 0) {
      return undefined;
    }
    return js[0];
};

At the end this is working.

My question is, is there another way to convert the Candid text to JavaScript besides using this remote solution? Or, what is the recommended way to do that?

Alternatively you can run the rust crate that converts candid to JS in WASM with something like e.g. wasm-pack.

Thank you, but I want to do this in JavaScript directly in an application.

Maybe @chenyan has a good idea?

You can run WASM directly from JavaScript inside a browser. Also in a native application e.g. Android you can compile the Rust implementation to a native binding.

As far as I’m aware there’s no pure JavaScript implementation of candid as of now.

Yep, either calling the remote didjs canister, or build a wasm and call in JS. For the latter, here is the doc: candid - Rust.

Thanks for the answers. That sounds a bit exaggerated to me, but I will also try the wasm approach out of curiosity and to learn.

Yep, the wasm approach works too and is super fast :hushed:.

1 Like