0

I have the following AssmemblyScript module:

export function add(a: i32, b: i32): i32 {
  return a + b;
}

export function printNum(a: string): f64 {
  return parseFloat(a);
}

Which is generated with asc assembly/index.ts --target release

I'm then consuming that in my host TypeScript files:

import fs from "fs";
import loader from "@assemblyscript/loader";
import { join } from "path";

const wasmModule = loader.instantiateSync(fs.readFileSync(join(__dirname, "..", "/build/untouched.wasm")), {});
module.exports = wasmModule.exports;

And I can call add just fine:

const { add, printNum } = require("./wasm");
console.log(add(1, 2)); // correctly prints 3

However, trying to call printNum doesn't crash my Node process, but the process exits successfully, without the code being called:

    const [row] = await db.getWhere({});
    console.log("balance", row.balance, typeof row.balance); // balance 123456789123456789.123456789123456789 string
    try {
      const result = printNum(row.balance);
      console.log("result", result);
    } catch (error) {
      console.log(error);
    }
    console.log(add(1, 2));

    console.log("done");

The printNum function is never called, or it's called and internally errors? I don't receive any error in the catch, and the subsequent two console.logs are never called

If I comment out the whole printNum try/catch, those next two console.logs are executed

Where do I begin debugging this? Or can anyone spot any errors in my AssemblyScript printNum method itself that might cause this?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331

1 Answers1

1

printNum takes a pointer to a string. To create a new string use __newString and pass the returned pointer to printNum.

const { add, printNum, __newString } = require("./wasm");
const result = printNum(__newString(row.balance));

Reference

Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
  • You're right! Realised this after I posted. As an aside, do you know why `export function printNum(a: string): string { const num = parseFloat(a); const res: f64 = num + 1; return res.toString(); }` would return "123456789123456790.0" after being called like so: `const ptr = __newString(row.balance); const result = printNum(ptr);` ? To me, passing in "123456789123456789.123456789123456789" should return "123456789123456790.123456789123456789" – benhowdle89 May 26 '21 at 13:36
  • an f64 can only hold a specific amount of precision. Just pasting the number in your dev console and printing it already truncates it. – Sebastian Speitel May 26 '21 at 13:38
  • got you! Does AssemblyScript contain a Number Type that would accommodate such a precision? – benhowdle89 May 26 '21 at 13:41
  • f64 is already a double. For everything else you would need something like `as-bignum` but that's still in early development. – Sebastian Speitel May 26 '21 at 13:44