# Reuse and Version Numscript Programs

Source: https://docs.formance.com/v4.0/modules/ledger/transactions/numscript-library

Stack: v4.0

Store a Numscript program in a ledger when several callers must execute the same reviewed transaction logic. Callers send a name, version, and variables instead of embedding the source in every request.

For production traffic, publish an immutable semantic version and request that exact version. This makes a deployment reproducible and gives the application an explicit rollback target.

## Prerequisites

You need an existing normal ledger and a token with `ledger:write` to publish and execute programs — the save needs `ledger:LedgerWrite`, the execution needs `ledger:TransactionWrite` — plus `ledger:read` for the verification requests. The virtual scopes below assume the default scope mapping.

These HTTP write examples assume that the cluster accepts unsigned requests. If your cluster requires Ed25519 request signatures, follow [Configure Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing) and use a signed gRPC client or `ledgerctl` configured with a signing key; the HTTP write handlers submit unsigned requests.

If the ledger enforces account types, replace the demo destination with an address that matches its configured patterns.

```bash
set -eo pipefail

export LEDGER_URL="https://ledger.example.com"
export LEDGER_NAME="main"
export LEDGER_TOKEN="replace-with-an-access-token"
export RUN_ID=${RUN_ID:-"$(date +%s)$$"}

export NUMSCRIPT_NAME="transfer-$RUN_ID"
export DESTINATION_ACCOUNT="merchants:numscript-demo:$RUN_ID"
export TRANSFER_REFERENCE="transfer:$RUN_ID"
```

## Publish an immutable version

Define a reusable transfer program:

```numscript
vars {
  account $source
  account $destination
  monetary $amount
}

send $amount (
  source = $source
  destination = $destination
)
```

Put the same source in a shell variable for the request below:

```bash
TRANSFER_V1=$(cat <<'NUMSCRIPT'
vars {
  account $source
  account $destination
  monetary $amount
}

send $amount (
  source = $source
  destination = $destination
)
NUMSCRIPT
)
```

Save it under the run-specific name in `$NUMSCRIPT_NAME` as version `1.0.0`. The `Idempotency-Key` makes the save safe to retry after a lost response:

```bash
jq --null-input \
  --arg content "$TRANSFER_V1" \
  '{content: $content, version: "1.0.0"}' \
  | curl --fail-with-body --silent --show-error \
      --request PUT "$LEDGER_URL/v3/$LEDGER_NAME/numscripts/$NUMSCRIPT_NAME" \
      --header "Authorization: Bearer $LEDGER_TOKEN" \
      --header "Content-Type: application/json" \
      --header "Idempotency-Key: numscript:$NUMSCRIPT_NAME:1.0.0" \
      --data @- \
  > /tmp/numscript-transfer-1.0.0.json
```

Ledger parses the program before saving it. A successful save returns `201 Created` with the stored program info. Verify the stored source before pointing callers at the new version.

Verify the stored source through an exact-version lookup:

```bash
curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/numscripts/$NUMSCRIPT_NAME?version=1.0.0" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e --arg name "$NUMSCRIPT_NAME" --arg content "$TRANSFER_V1" '
      .data
      | select(.name == $name and .version == "1.0.0" and .content == $content)
      | {name, version, content, createdAt}'
```

The command exits successfully only when the response reports the requested name, exact version, and submitted source.

## Execute the saved program

Reference the exact version in a transaction request:

```bash
jq --null-input \
  --arg reference "$TRANSFER_REFERENCE" \
  --arg name "$NUMSCRIPT_NAME" \
  --arg destination "$DESTINATION_ACCOUNT" \
  '{
    reference: $reference,
    scriptReference: {
      name: $name,
      version: "1.0.0",
      vars: {
        source: "world",
        destination: $destination,
        amount: "USD/2 2500"
      }
    }
  }' \
  | curl --fail-with-body --silent --show-error \
      --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
      --header "Authorization: Bearer $LEDGER_TOKEN" \
      --header "Content-Type: application/json" \
      --header "Idempotency-Key: $TRANSFER_REFERENCE:create" \
      --data @- \
  > /tmp/referenced-numscript-transaction.json
```

Expected result: Ledger returns `201 Created`, and `.data.transaction.postings` contains the movement produced by the exact `1.0.0` version. This example uses `world` as an explicit funding boundary. For an internal transfer, pass a funded account instead.

Verify both the program choice and the accounting result:

```bash
jq '.data.transaction | {id, reference, postings}' \
  /tmp/referenced-numscript-transaction.json

curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$DESTINATION_ACCOUNT" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      .data.volumes[]
      | select(.asset == "USD/2" and .color == "")
      | .volumes.input == "2500"
        and .volumes.output == "0"
        and .volumes.balance == "2500"'
```

The destination balance increases by `2500` minor units.

## Publish a compatible change

Semantic versions are immutable. Publish changed behavior under a new version instead of overwriting `1.0.0`. Version `1.1.0` adds a metadata tag:

```numscript
vars {
  account $source
  account $destination
  monetary $amount
}

set_tx_meta("program", "transfer@1.1.0")

send $amount (
  source = $source
  destination = $destination
)
```

Put that source in a shell variable and save it as `1.1.0`:

```bash
TRANSFER_V1_1=$(cat <<'NUMSCRIPT'
vars {
  account $source
  account $destination
  monetary $amount
}

set_tx_meta("program", "transfer@1.1.0")

send $amount (
  source = $source
  destination = $destination
)
NUMSCRIPT
)

jq --null-input \
  --arg content "$TRANSFER_V1_1" \
  '{content: $content, version: "1.1.0"}' \
  | curl --fail-with-body --silent --show-error \
      --request PUT "$LEDGER_URL/v3/$LEDGER_NAME/numscripts/$NUMSCRIPT_NAME" \
      --header "Authorization: Bearer $LEDGER_TOKEN" \
      --header "Content-Type: application/json" \
      --header "Idempotency-Key: numscript:$NUMSCRIPT_NAME:1.1.0" \
      --data @- \
  > /dev/null
```

Confirm that both versions remain available:

```bash
(
set -euo pipefail

for VERSION in 1.0.0 1.1.0; do
  curl --fail-with-body --silent --show-error \
    "$LEDGER_URL/v3/$LEDGER_NAME/numscripts/$NUMSCRIPT_NAME?version=$VERSION" \
    --header "Authorization: Bearer $LEDGER_TOKEN" \
    | jq -er --arg name "$NUMSCRIPT_NAME" --arg version "$VERSION" '
        .data
        | select(.name == $name and .version == $version)
        | .name + "@" + .version'
done
)
```

Expected output, with the run-specific name substituted for `<name>`:

```text
<name>@1.0.0
<name>@1.1.0
```

Move callers to `1.1.0` only after testing representative balances, metadata, and failure cases. Roll back the application by changing its `scriptReference.version` to `1.0.0`; no library mutation is required.

## Understand version resolution

A selector means different things on the read path and the write path. Reads are permissive; execution and publication are not.

Accepted on `GET /v3/{ledgerName}/numscripts/{name}?version=`:

| Requested version | Resolves to                                                                                |
| ----------------- | ------------------------------------------------------------------------------------------ |
| `1.0.0`           | That exact immutable version.                                                              |
| `1.0`             | The greatest stored `1.0.x` version.                                                       |
| `1`               | The greatest stored `1.x.y` version.                                                       |
| `latest`          | The greatest stored semantic version.                                                      |
| Omitted           | The greatest stored semantic version. `latest` and an omitted value are the same selector. |

Accepted in `scriptReference.version` on a transaction:

| Requested version      | Behavior                                                                                        | Production guidance                                    |
| ---------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| `1.0.0`                | Executes that exact immutable version.                                                          | Recommended for a stable deployment.                   |
| `latest`               | Re-resolves to the greatest stored version on every execution.                                  | Use for development or an explicitly mutable workflow. |
| `1`, `1.0`, or omitted | Rejected with `400` and an invalid-version reason. Partial and omitted selectors are read-only. | Not available. Pin an exact version.                   |

`PUT .../numscripts/{name}` accepts an exact `major.minor.patch` only. `latest`, a partial selector, and an omitted version are all rejected with `400` and an invalid-version reason.

Ledger accepts only numeric selectors with one to three components (`1`, `1.2`, or `1.2.3`), the literal `latest`, or an omitted value. Version ranges, prerelease labels, and build metadata are not supported.

Saving a version advances the program's pointer only when the new version is the greatest stored: the pointer is `max(current, new)`, so adding an older version out of order does not move it. There is no separate mutable `latest` slot — `latest` is a selector that re-resolves through that pointer on every request.

`latest` re-resolves on every execution, so an operation without a retained idempotency outcome can run different source after another caller publishes a greater version. A retained request that submitted `latest` replays its first outcome: Ledger audits the selector as submitted and never rewrites it to a concrete version, so an unchanged body cannot become an idempotency conflict because the resolution moved. Exact semantic versions avoid the ambiguity altogether.

## Check whether a program name is still used

The usage counter answers one question: is anything still calling this program name? It aggregates invocations across every version stored under that name:

```bash
(
USAGE_TIMEOUT_SECONDS=${USAGE_TIMEOUT_SECONDS:-30}
USAGE_DEADLINE=$((SECONDS + USAGE_TIMEOUT_SECONDS))
USAGE_READY=false

while ((SECONDS < USAGE_DEADLINE)); do
  if ! curl --fail-with-body --silent --show-error \
      "$LEDGER_URL/v3/$LEDGER_NAME/numscripts/$NUMSCRIPT_NAME/usage" \
      --header "Authorization: Bearer $LEDGER_TOKEN" \
      > /tmp/numscript-usage.json; then
    echo "Usage request failed; inspect /tmp/numscript-usage.json before retrying." >&2
    exit 1
  fi

  USAGE_COUNT=$(jq -er '.data.count | select(type == "number")' \
    /tmp/numscript-usage.json) || {
    echo "Usage response did not contain a numeric data.count." >&2
    exit 1
  }

  if ((USAGE_COUNT >= 1)); then
    USAGE_READY=true
    break
  fi

  sleep 2
done

if [[ "$USAGE_READY" != "true" ]]; then
  echo "Usage did not converge within ${USAGE_TIMEOUT_SECONDS}s; the transaction result is unchanged. Retry this read later." >&2
  exit 1
fi

jq '.data | {count, lastUsed}' /tmp/numscript-usage.json
)
```

After the example transaction, the result eventually reports a positive count and the greatest effective transaction timestamp seen for this name:

```json
{
  "count": 1,
  "lastUsed": "2026-07-17T10:30:00Z"
}
```

The HTTP route requires the `ledger:read` virtual scope; the direct gRPC method checks the granular query-read permission. It does not accept a checkpoint or minimum log sequence. The counter normally follows committed writes after a short background interval, but catch-up after startup or restore can take longer; increase `USAGE_TIMEOUT_SECONDS` or retry the read later in those cases. It counts only committed transactions that used `scriptReference`: failed or skipped attempts, inline scripts, and idempotent replays do not add another invocation. An unknown program name on an existing ledger returns `count: 0`; an unknown ledger returns `404`.

Treat usage as an operational adoption signal, not a billing counter. The counter is eventually consistent, so a `0` response can mean the program has never run or that the counter has not caught up yet. `lastUsed` is an effective transaction timestamp, not the time the counter observed the invocation. Entries without a saved-program identity, including records replayed from another ledger, do not add to this count. The count is per program name, not per semantic version.

## List the programs in a ledger

List the current entry for each program in the ledger:

```bash
curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/numscripts" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq '.data[] | {name, version, createdAt}'
```

The Ledger 3.0 numscript surface has no delete operation: the routes are `GET` for the listing, an individual program, its usage, and its versions, plus `PUT` to save. A published semantic version is immutable and permanent, so retiring a program means moving its callers off it rather than removing it from the ledger. Combine the usage signal with a search of deployed callers and recent transaction evidence before you treat a program name as unused; a low or zero count alone is not enough.

## Handle errors and retries

| Result                               | Meaning                                                                                                                                 | Action                                                                                                  |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `400` with a parse reason            | The Numscript source is invalid                                                                                                         | Fix and test the source before publishing a version.                                                    |
| `400` with an invalid-version reason | A save version is not an exact `major.minor.patch`, or an executable `scriptReference.version` is neither an exact version nor `latest` | Publish with `major.minor.patch`, and execute with an exact version.                                    |
| `404`                                | The program or requested version does not exist                                                                                         | Check the ledger, name, and version constraint.                                                         |
| `409`                                | The semantic version already exists                                                                                                     | Do not overwrite it. Compare the stored content, then select the existing version or publish a new one. |
| `503`                                | The write path is temporarily unavailable                                                                                               | Read the exact target version before retrying, because the save may have committed.                     |

`PUT .../numscripts/{name}` honors the `Idempotency-Key` header, so send one and retry the identical body under the same key when a network failure makes a save uncertain. If you did not send a key, fetch the exact semantic version and compare its content instead. If it exists and matches, treat the publication as successful. If it differs, preserve the stored version and publish the intended change under a new version.

Continue with [Retry Writes Safely](https://docs.formance.com/v4.0/modules/ledger/transactions/idempotency-and-references) and apply it to every transaction that executes a saved program.
