Hey, Motoko and Rust developers!
The Languages team at DFINITY is exploring several approaches to make it easier to call Rust functions from Motoko canisters. This forum post summarizes the current status for Motoko-Rust interoperability and gives anyone who is interested a place to voice opinions and feedback.
Currently, the simplest way to call Rust functions in Motoko is to use two different canisters on the same subnet, one written in Rust and the other in Motoko. This has several advantages (good support for multi-canister projects in dfx
, data structure conversions handled via Candid interface) but also has various drawbacks (async/await syntax, difficult state management, and possibly the introduction of canister commit points).
Although complicated to do by hand, it’s also possible to manually recompile the Motoko compiler and runtime system with custom Rust language bindings. This provides a foreign function interface with static linking, making it possible to use both languages in the same WebAssembly module. However, this currently has major limitations in practice, especially when trying to allocate memory from a Rust function.
The goal of this exploration is to reduce the learning curve and mitigate the drawbacks for each of these approaches.
Here is a summary of recent progress:
- Canpack: a solution for Motoko developers to use Rust libraries via a generated sibling canister
- Add Rust crates using a
[rust-dependencies]
section in yourmops.toml
file (example). - It’s also possible to create Motoko libraries which depend on Rust crates without requiring additional setup on the canister end.
- This is an experimental tool; whether this becomes an official project depends on developer interest.
- Add Rust crates using a
- GitHub PR: Motoko compiler support for custom runtime system (RTS) functions
- Removes the need for a recompiled
moc
binary to add Rust bindings (still requires a custom RTS). - Low-level capability which we can build upon with additional tooling over time.
- Removes the need for a recompiled
If you have a specific use case for calling Rust from Motoko (such as needing a cryptographic function or parser which isn’t yet available in the Motoko ecosystem), please feel free to let us know so we can prioritize the overall most useful solution.
As a quick side note, another possible approach to communication between Motoko and Rust is the Wasm component model specification. It’s currently undecided whether this will be supported in the replica, so this exploration focuses on solutions with incremental value at each step towards the long-term goal of seamless Motoko-Rust interoperability.
Looking forward to hearing your thoughts on this topic!
Cheers,
~ Ryan