Calling another canister's methods

A simple example showing how to call between canisters.

You can import another canister as you would a module, and any public methods in the second canister will be available locally, for example:

canister1/main.mo

import Canister2 "canister:canister2";

actor {
    public func main() : async Nat {
        return await Canister2.getValue();
    };
};

canister2/main.mo

import Prim "mo:prim";

actor {
    public func getValue() : async Nat {
        Prim.debugPrint("Hello from canister 2!");
        return 10;
    };
};
4 Likes

You can also use a canister id to access a previously deployed canister:

canister1/main.mo

actor {
    public func main(canisterId: Text) : async Nat {
        let canister2 = actor(canisterId): actor { getValue: () -> async Nat };
        return await canister2.getValue();
    };
};

Where canister2’s id from the previous example can be passed in, similar to:

$ dfx canister call canister1 main "ic:6EF4FCAD1FD36EB654" --type string

Note the type signature actor { getValue: () -> async Nat } can be a subtype of that exposed by canister2.

4 Likes