-
Notifications
You must be signed in to change notification settings - Fork 86
/
fetch_candid.ts
39 lines (36 loc) · 1.31 KB
/
fetch_candid.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { Actor, ActorSubclass, CanisterStatus, HttpAgent } from '.';
import { Principal } from '@dfinity/principal';
import { IDL } from '@dfinity/candid';
/**
* Retrieves the Candid interface for the specified canister.
*
* @param agent The agent to use for the request (usually an `HttpAgent`)
* @param canisterId A string corresponding to the canister ID
* @returns Candid source code
*/
export async function fetchCandid(canisterId: string, agent?: HttpAgent): Promise<string> {
if (!agent) {
// Create an anonymous `HttpAgent` (adapted from Candid UI)
agent = new HttpAgent();
if (agent.isLocal()) {
agent.fetchRootKey();
}
}
// Attempt to use canister metadata
const status = await CanisterStatus.request({
agent,
canisterId: Principal.fromText(canisterId),
paths: ['candid'],
});
const candid = status.get('candid') as string | undefined;
if (candid) {
return candid;
}
// Use `__get_candid_interface_tmp_hack` for canisters without Candid metadata
const tmpHackInterface: IDL.InterfaceFactory = ({ IDL }) =>
IDL.Service({
__get_candid_interface_tmp_hack: IDL.Func([], [IDL.Text], ['query']),
});
const actor: ActorSubclass = Actor.createActor(tmpHackInterface, { agent, canisterId });
return (await actor.__get_candid_interface_tmp_hack()) as string;
}