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.

13 Likes

hi , Ori

I tried to import Canister2 deployed on local network in Canister1 as module , Canister 2 is build in another project, so I tried as
import Canister2 “canister:canister2”;
when I deploy canister 1 , the error shows as import error [M0011], canister alias “canister2” not defined

so what I should do to correct import canister 2 ?

You can follow the second approach above, use the canister id shown in the terminal when you deployed the canister2 project.

If you don’t want to pass the id in you can also hard code it, like this: https://forum.dfinity.org/t/how-to-use-cowsay-project-in-my-project/6473/2?u=ori

In your local dev environment, if you need to start clean then deploying projects in the same order every time will ensure the assigned canister id doesn’t change.

(For your production deployment, note the mainnet canister id will be different to the locally deployed one so you’ll have to account for that.)

1 Like