# Recompute in the browser

> konto's bill recompute compiled to WebAssembly: three functions over the module's memory, JSON in and out, the same code that sealed the bill, and how to call it from JavaScript or Node.

„Rechnung nachrechnen“ only means something if the customer's own device does the
arithmetic. `web/konto-wasm` compiles `konto-bill`'s recompute to WebAssembly, so the
browser runs the exact code that sealed the bill; JavaScript never computes money.

## Build

```sh
just wasm
# target/wasm32-unknown-unknown/wasm/konto_wasm.wasm (about 480 KB, 150 KB gzipped)
```

`just wasm` also runs the module in Node against the household bill, so CI proves the
browser build, not only the native one.

## The interface

| Export | Meaning |
|---|---|
| `memory` | the module's linear memory |
| `input(len) → ptr` | a buffer of `len` bytes; write the bill JSON into it |
| `recompute() → len` | recomputes the bill in the buffer; the length of the answer |
| `output() → ptr` | the answer: `{"matches": bool, "message": "…", "verdict": …}` |

There is no generated glue and no JavaScript tooling. The only `unsafe` in the shim is the
naming of the exports.

```js
const { instance } = await WebAssembly.instantiateStreaming(fetch('konto_wasm.wasm'));
const { memory, input, recompute, output } = instance.exports;

function check(bill) {
  const bytes = new TextEncoder().encode(JSON.stringify(bill));
  const at = input(bytes.length);            // may grow the memory: take views after it
  new Uint8Array(memory.buffer, at, bytes.length).set(bytes);
  const length = recompute();
  return JSON.parse(new TextDecoder().decode(new Uint8Array(memory.buffer, output(), length)));
}

check(sealedBill);  // { matches: true, message: "Stimmt auf den Cent.", verdict: { verdict: "matches" } }
```

Pass the sealed bill itself (the `bill` field of `GET /v1/bills/{number}`). A changed bill
names the first difference; input that is not a bill answers
„Die Rechnung ließ sich nicht lesen; bitte die Rechnung neu laden.“ and never matches.

Take every view of `memory.buffer` after calling `input()`: growing the memory detaches
earlier views.

## What a match means

A match says that the bill's lines, VAT groups, totals and digest are consistent with its
inputs. It does not say who issued the bill; that follows from where the bill came from.
See [A bill that proves itself](bill.md#the-digest).
