I decided to learn to write smart contract for EOS, but I’m not a fan of C++. So I decided that it would be cool to use a functional language for this. Unfortunately the Ethereum Virtual Machine is not ready for EOS and there are not a lot of languages that compile down to WASM. Rust just recently added this feature natively (here the best guide I found).

How does the current system work?

Actually it’s easier than expected. There is a tool called eoscpp that compiles the contract from C++ to a .wasm file. What it actually does is just launch clang with a bunch of flags. Namely it sets the target to wasm32 then it get rid of the standard library and notifies the compiler that there won’t be any main entrypoint. Here the full line, which is the core of it:

So I thought it shouldn’t be too hard to create a eosrustc that would do the same for Rust.

The most basic contract in C++

Here is the most basic contract I could come up with (still untested on the blockchain, mind you):

which, as you may imagine, just prints 5 when deployed.

The file print.h, to avoid further dependencies, was cut down to just the following lines

How to create the same contract in Rust

  1. I created a new project with cargo new eos
  2. Edited the Cargo.toml to look like this
  1. After many trials and errors I ended up with the following lib.rs in my src folder:
  1. Compiled with the command

which was taken from the above guide.

The two contract side by side

I could get the following contract in WASM from the Rust code:

While C++ gave me this (reordered for easier comparison):


I haven’t had time to actually test them on the blockchain, but it’s pretty good to see that I could get a similar result.

I imagine what seems to be type declarations on the Rust contract won’t hurt, but I’m puzzled by the $memory 17 line. My hypothesis is that 17 is the minimum amount of reserved memory by default. I could not confirm this though by just looking at the code of the compiler.

The $env.printi vs $printi has no significance, it’s just a variable name. The Rust compiler add the env prefix to make it explicit that it comes from the env namespace, nothing else to it.

Anyways, I hope you had a good dose of inspiration. I’m sure we can soon demonstrate that writing EOS smart contracts in Rust is possible and that the contract libraries will be rewritten soon for rust (actually maybe they can be just linked for now🤔).

I may try to actually deploy the contract and see if it works in EOS Dawn, I’ll update this article or write a follow up.

Stay tuned and happy hacking.

(Visited 1,093 times, 1 visits today)