Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add usage example for ExperimentalInternetComputer.call() on "Inter-canister calls" page #4774

Merged
merged 5 commits into from
Nov 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 44 additions & 5 deletions doc/md/writing-motoko/intercanister-calls.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,24 @@ This example will showcase a simple way to configure inter-canister calls that c

## Example

Consider the following code for `canister1`:
Consider the following code for `Canister1`:

```motoko no-repl
import Canister2 "canister:canister2";

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

Then, consider the following code for `canister2`:
Then, consider the following code for `Canister2`:

```motoko
import Debug "mo:base/Debug";

actor {
actor Canister2 {
public func getValue() : async Nat {
Debug.print("Hello from canister 2!");
return 10;
Expand Down Expand Up @@ -72,4 +72,43 @@ Then, use the following call, replacing `canisterID` with the principal ID of a
dfx canister call canister1 main "canisterID"
```

<img src="https://github.com/user-attachments/assets/844ca364-4d71-42b3-aaec-4a6c3509ee2e" alt="Logo" width="150" height="150" />
## Advanced usage

If the method name or input types are unknown at compile time, it's possible to call arbitrary canister methods using the `ExperimentalInternetComputer` module.

Here is an example which you can modify for your specific use case:

```motoko
import IC "mo:base/ExperimentalInternetComputer";
import Debug "mo:base/Debug";

actor AdvancedCanister1 {
public func main(canisterId : Principal) : async Nat {
// Define the method name and input args
let name = "getValue";
let args = (123);

// Call the method
let encodedArgs = to_candid (args);
let encodedValue = await IC.call(canisterId, name, encodedArgs);

// Decode the return value
let ?value : ?Nat = from_candid encodedValue
else Debug.trap("Unexpected return value");
return value;
}
}
```

```motoko
import Debug "mo:base/Debug";

actor AdvancedCanister2 {
public func getValue(number: Nat) : async Nat {
Debug.print("Hello from advanced canister 2!");
return number * 2;
};
};
```

<img src="https://github.com/user-attachments/assets/844ca364-4d71-42b3-aaec-4a6c3509ee2e" alt="Logo" width="150" height="150" />
Loading