In JavaScript, how can I discover which subnet a canister is running on? Or in other words, where can I find the subnet ID for a given canister ID?
This is the one part of the registry I know: You can use get_subnet_for_canister
. It returns the subnet that canister id is assigned to if the id is assigned to any subnet. It doesn’t check if the canister actually exists
2 Likes
HAHAHA, I didn’t pay attention to the thread and thought you were providing an additional answer to the one about “subnet metadata” we discussed yesterday, @Severin. So, I kept going with a solution using Agent-js—without the registry. That’s why I originally replied, mentioning the documentation.
Anyway, here’s what I ultimately found, and it seems to work (at least locally). Another trick seems to be using AgentJS’s request
and providing a paths
equals to subnet
.
import {
CanisterStatus as AgentCanisterStatus,
AnonymousIdentity,
type Identity
} from '@dfinity/agent';
export const subnetId = async ({
canisterId
}: {
canisterId: string;
}): Promise<string | undefined> => {
const agent = await getAgent({ identity: new AnonymousIdentity() });
const path = 'subnet' as const;
const result = await AgentCanisterStatus.request({
canisterId: Principal.from(canisterId),
agent,
paths: [path]
});
const subnet: AgentCanisterStatus.Status | undefined = result.get(path);
const isSubnetStatus = (
subnet: AgentCanisterStatus.Status | undefined
): subnet is AgentCanisterStatus.SubnetStatus =>
nonNullish(subnet) && typeof subnet === 'object' && 'subnetId' in subnet;
return isSubnetStatus(subnet) ? subnet.subnetId : undefined;
};
I’ll use it in Juno.
1 Like