EOS Development For Beginners: WebAssembly

in eos •  2 years ago 

Many guys are trying to learn how to develop smart contracts on EOS. However, those smart contracts are written by C++ and compiled into WebAssembly which seemed strange to most non-c++ programmers. So before diving deep into the EOS, it’s better to learn some basic stuff about WebAssembly.

What’s WebAssembly

I don’t want to copy the definition from its official website. You can take a look at it by yourself. Here you can think it as a file that can be loaded and run in the web browser. It’s similar to the Javascript, but it’s much faster, tinier and safer than JS.

How to write Webassembly

Here is a work flow:

Basically there are four steps, I will go though it by a very simple example.

  • 1. Write the C/C++ code

The following code is used to calculate the square root of a number.

#include <math.h>
float getSqrt (float num) {
  return sqrt(num);

  • 2. Compile C/C++code into wasm (the format of Webassembly)

There are many ways to compile the code. To simplify the process, I found a very easy way to do that.

Copy your code to that website and click the build button, you can find complied file in the below.

Then download the program.wasm file to your local box.

  • 3. Load the wasm into browser with JavaScript

Create a test.html using the following code, put it in the same fold as program.wasm

<!doctype html>
  <title>WASM Test</title>
    .then(res => {
      if (res.ok)
        return res.arrayBuffer();
      throw new Error(`Unable to fetch WASM.`);
    .then(bytes => {
      return WebAssembly.compile(bytes);
    .then(module => {
      return WebAssembly.instantiate(module);
    .then(instance => {
      window.wasmSqrt = instance.exports.getSqrt;
  • 4. Run the method in Web browser

To work around the website cross-origin issues, we need to run a local web server in that folder. With Linux or Mac, let's do

python -m SimpleHTTPServer

Then open our Chrome browser, go to this page: http://localhost:8000/test.html. In the console, try the following method.


Through this tutorial, you get familiar with WebAssemply, but for the advanced study, please check eos-example-exchange-contract-and-benefits-of-c written by @dan

If you are interested in how to build EOS on mac, please check my previous tutorial.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thanks for the post! I like the focus on concrete steps and keeping it simple, would love to see more EOS-specific examples intermediate in difficulty between this and @dan's posts.. :)

Yeah. I am learning step by step. Hope I can write more.

Hey, thanks for the post. Keep them coming!

This seems like content that is actually useful to people and deserves sharing. Upvoted.

Thanks for your post.