Compile Motoko to Wasm

Is it possible to compile Motoko code directly to wasm file without conister ?
like if i would compile c/c++ code to wasm and call it from nodejs or other languages ?

Hi, you can explore using the standalone moc compiler:

https://sdk.dfinity.org/docs/language-guide/compiler-ref.html

To run it from the sdk install directory:

$(dfx cache show)/moc

You could also set an alias importing the base library:

alias moc="$(dfx cache show)/moc --package base $(dfx cache show)/base"

Then just pass it the .mo file, eg if you want to see your Debug.print() output you can use:

moc main.mo -r

Or to output a wasm file:

moc main.mo

i tried to call function add
i get this error :
(index):1 Uncaught (in promise) TypeError: WebAssembly.instantiate(): Import #0 module=“ic0” error: module is not an object or function

actor {

public func add(val1:Int,val2:Int):async Int{

    return val1 + val2;

};

public func sub(val1:Int,val2:Int):async Int{

    return val1 - val2;

};

};

here is javascript code:

function add(wasm){

const add = wasm.exports.add

console.log(add(2,2))

}

function wfadd(){

fetch("./src/main/main.wasm").then(response=>

    response.arrayBuffer()

).then((bytes)=>

    WebAssembly.instantiate(bytes,importObj)

).then(result=>

    result.instance

).then(add)

}

wfadd()

Hmmm I’ve actually been using Rust or C++ for any in-browser Wasm myself, so I’m not sure of the workflow for Motoko, perhaps @claudio can help here? I know you can target other runtimes via WASI straight from moc.

Edit: The actor { } class isn’t needed for non-canister wasm output, so try removing that.

You can use the -wasi-system-api flag on the compiler to make it emit WASI compatible code, but the only interface that is implemented is logging. That’s good enough to write unit tests and run all kinds of pure synchronous Motoko in wasmtime, but I don’t think the browser engines implement WASI.

Check out the testing setup of the base or the matchers libraries for examples.

2 Likes