# numscript

[Numscript](https://docs.formance.com/numscript/), Formance's DSL for moving
money, for Elixir.

It runs the **official interpreter** (`github.com/formancehq/numscript`, MIT),
compiled to WebAssembly, inside [Wasmex](https://hex.pm/packages/wasmex). The
module is compiled once at boot and kept warm in a pool of instances, so a call
takes about **2 ms**. Nothing to install: the WASM ships in `priv/`.

The library is stateless: your ledger owns the balances.

```elixir
def deps do
  [{:numscript, "~> 0.2"}]
end
```

## Usage

```elixir
script = """
vars { monetary $amount }

send $amount (
  source      = @revenue allowing unbounded overdraft
  destination = {
    30%       to @savings
    remaining to @checking
  }
)
"""

{:ok, %Numscript.Result{postings: postings}} =
  Numscript.run(script, %{"amount" => {"USD/2", 100_000}})

# [%Numscript.Posting{source: "revenue", destination: "savings",  asset: "USD/2", amount: 30_000},
#  %Numscript.Posting{source: "revenue", destination: "checking", asset: "USD/2", amount: 70_000}]
```

### Balances and locking

The interpreter only knows the balances you pass; a missing account has zero.
Pass a map, or a function that receives the script's dependencies (sorted) and
returns the map. Use it to lock the accounts and read their balances inside the
same database transaction that writes the postings:

```elixir
Repo.transaction(fn ->
  {:ok, result} =
    Numscript.run(script, vars,
      balances: fn deps ->
        # deps: [{"checking", "USD/2"}, {"revenue", "USD/2"}, ...], always sorted,
        # so two transactions lock accounts in the same order (no deadlocks)
        MyLedger.lock_and_read!(deps)
      end
    )

  MyLedger.write_postings!(result.postings)
end)
```

### Errors

Errors are `%Numscript.Error{kind, message, start, end, details}`:

```elixir
{:error, %Numscript.Error{kind: "MissingFundsErr", details: %{"needed" => "500", "available" => "200"}}} =
  Numscript.run("send [USD/2 500] (source = @cash destination = @supplier)", %{},
    balances: %{"cash" => %{"USD/2" => 200}})

{:error, %Numscript.Error{kind: "ParserError", start: {2, 10}}} = Numscript.check("...")
```

`start` and `end` are `{line, column}` from 1, ready to highlight in an editor.

### API

| Function | |
| --- | --- |
| `Numscript.run(script, vars, opts)` | postings, transaction and account metadata |
| `Numscript.check(script)` | parses; returns the variables the script expects |
| `Numscript.dependencies(script, vars)` | accounts and assets read and written |
| `Numscript.interpreter_version()` | version of the bundled interpreter |
| `Numscript.features()` | experimental feature flags |

`run/3` options: `:balances`, `:meta` (account metadata), `:features`, `:timeout`.

## Experimental features

Some constructs sit behind the interpreter's feature flags, for example account
interpolation:

```elixir
script = """
vars { account $parent }
send [USD/2 100] (source = @world destination = @$parent:savings)
"""

Numscript.run(script, %{"parent" => "people:ann"}, features: ["experimental-account-interpolation"])
```

They work, but Formance may still change them. `test/experimental_test.exs`
pins the behaviour this library relies on; it is the contract to check before
bumping the interpreter.

## Configuration

```elixir
config :numscript,
  pool_size: 8,           # live instances (default: System.schedulers_online())
  compile_on_boot: true   # compile the WASM when the application starts
```

## How it works

`wasm/main.go` wraps the interpreter as a WASI reactor
(`GOOS=wasip1 GOARCH=wasm -buildmode=c-shared`) exporting `alloc`, `handle` and
`free`. Requests and responses are JSON, written to and read from the
instance's memory. An internal pool keeps up to `pool_size` instances alive,
each serving one call at a time; an instance whose call fails or times out is
replaced.

At load, the module's SHA-256 is checked against `priv/numscript.wasm.sha256`.
CI rebuilds the WASM from source and checks that the hash matches.

### Upgrading the interpreter

```sh
cd wasm && go get github.com/formancehq/numscript@<version> && cd ..
make wasm          # rebuilds priv/numscript.wasm and its .sha256
mix test           # experimental_test.exs must stay green
```

## License

MIT. The bundled interpreter is © Formance, Inc, MIT; see `NOTICE`.
