This example package demonstrates compiling a simple AssemblyScript program, add.ts
which adds two numbers to WASM, executing it in a host environment, and accessing it's methods.
This package additionally demonstrates running WASM using both the AssemblyScript loader, which provides convenience functionality and compatibility, and native WebAssembly framework.
- NodeJS & NPM is required to build the project dependencies, run the WASM compile, and run tests. NPM comes installed with NodeJS by default
Before running the project, you must also install the project's dependencies. From the project root, run:
npm install
src/
- Contains the AssemblyScript (.ts
) source code to be compiled into the WASM module, for example add.tsbuild/
- Contains the compiled output WASM file resulting from the build processtest/
- Contains NodeJS test code demonstrating and unit testing the functionality contained in and exposed by the compiled WASM module inbuild
package.json
- Contains the dependency declarations and NPM build & test scripts. Controls WASM & AssemblyScript compiler options
- Write AssemblyScript code with exported functions
- Compile the AssemblyScript code to WASM
- Modify tests in
test/
to test functions exported from AssemblyScript code - Run tests
- Repeat!
To compile the add.ts
code to a WASM binary:
npm run build
A add.wasm
file will be produced in the build
directory
Test the module outside of the context of the blockchain:
npm test
How to access and use AssemblyScript WASM modules from NodeJS, from test/add.unit.spec.js:
const util = require('../../../../src/util');
const imports = util.getDefaultImports();
const buffer = fs.readFileSync(path.resolve(__dirname, '../build/add.wasm'));
module = await loader.instantiateBuffer(buffer, imports);
//use module.<function name> to access functions!
console.log(module.add(3, 99)); // => 102
Add two integers together and return the resulting sum
Add an integer to a running total and return the resulting running total