Using Rust packages from a Motoko canister

I’ve put together a minimal example of using a Rust crate in a Motoko canister in this repo - zkTrainer.

This commit is the very start of a developer grant-funded project (outlined here) but I’ve used it to create a framework that I can build upon further and to share the details here for the benefit of anyone who might come across this thread while searching for ways to go about this.

The steps I used to set this up are as follows:

  • check prerequisites and run the usual commands to start a new dfx project
      dfx start --clean --background
      dfx new my-project --type=rust
      cd my-project
      code . (to open VSCode)
  • rename my-project-backend to wrapper (or whatever name you prefer) using find & replace, and rename the directory accordingly
  • (also search for the same text with underscore instead of hyphen)
  • separately start a dfx Motoko project
  • copy the directory containing main.mo into src in my-project
  • if renaming the directory, replace the name throughout the project
  • add details into dfx.json file
  • copy Cargo.toml file from Rust backend directory into Motoko backend directory (here) and edit package name
  • copy .did file from Rust backend directory into Motoko backend directory (here) and edit file name
  • from the project root folder run
      cargo add <crate-name>
      cargo build --target wasm32-unknown-unknown --release

I then wrote the code for the Rust wrapper and Motoko backend as shown in the links so as to be able to wrap a single type and method from the winterfell crate and use it in a Motoko canister.

This might not be the most efficient way to achieve this (and doesn’t use Canpack) but it does produce a working example. Happy to hear if anyone has suggestions for improvement.

1 Like