WebAssembly is a recent addition to browsers that enable the use of other languages than JavaScript for writing web apps. Here is a short guide to writing a Hello World application in Rust and getting it running as a SAFE web application.
There is a working demo at safe://hello.webassembly
. It only prints “Hello World” in the developer console, so you need to open that to see the message.
First you need to install the Rust language and Emscripten to be able compile your Rust code to WebAssembly.
You can use the following guide for that if you don’t have this installed already.
Once you have installed it, create a directory for the project and place the following in the file hello.rs
fn main() {
println!(“Hello World!”);
}
Then you need to create an index.html
file in the same directory with the following content. Replace the url variable that’s set to safe://hello.webassembly with your own url.
<html>
<script>
var Module = {};
function runWebAssembly(appToken, url)
{
return window.safeApp.webFetch(appToken, url + 'hello.wasm')
.then(buffer => {
Module.wasmBinary = buffer;
var script = document.createElement('script');
script.src = url + 'hello.js';
script.onload = function() {
console.log("Emscripten boilerplate loaded.")
}
document.body.appendChild(script);
});
}
let app = {
name: 'Hello Webassembly',
id: 'net.webassembly.tutorial.webapp.example1',
version: '0.1.0',
vendor: 'webassembly'
}
function connectAndRun(appToken, funct)
{
return window.safeApp.connect(appToken)
.then(_ => funct().then(_ => window.safeApp.free(appToken)));
}
var url = 'safe://hello.webassembly/';
window.safeApp.initialise(app)
.then((appToken) => connectAndRun(appToken, function(){ return runWebAssembly(appToken, url); }))
.catch((err) => { console.error("Error from webapp: ", err); })
</script>
</html>
Next you need to compile the Rust code to WebAssembly with the following command
rustc --target=wasm32-unknown-emscripten hello.rs
The files hello.js
and hello.wasm
was now created by the compiler. hello.wasm
is the actual compiled rust code while hello.js
is boilerplate javascript code needed to load and run the WebAssembly file.
The last step is to upload index.html
, hello.js
and hello.wasm
to your site, then you should be able to go to your site and see “Hello World” printed in the dev console.
Next I’ll be looking into how to call JavaScript functions from Rust to be able to call the SAFE JavaScript API from the Rust web application and store some data on the SAFE Network.