Skip to content

Commit

Permalink
docs: add usage example for ExperimentalInternetComputer.call() on …
Browse files Browse the repository at this point in the history
…"Inter-canister calls" page (#4774)

Updates the documentation in response to [this forum post](https://forum.dfinity.org/t/ic-call-or-experimentalinternetcomputer-call/36900).
  • Loading branch information
rvanasa authored Nov 21, 2024
1 parent a5f51a7 commit cc1eac1
Showing 1 changed file with 44 additions and 5 deletions.
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" />

0 comments on commit cc1eac1

Please sign in to comment.