# Write Transactions with Numscript

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

Stack: v4.0

Numscript describes the result you want while Ledger resolves the postings against current balances. Use it for ordered fallback sources, percentage splits, bounded overdrafts, or metadata changes that belong to the same transaction.

Use [explicit postings](https://docs.formance.com/v4.0/modules/ledger/transactions/create-with-postings) when your application already knows every movement. That keeps the request smaller and the application remains the source of the routing decision.

## Prerequisites

You need an existing normal ledger and a token with `ledger:write` for the transactions plus `ledger:read` for the account checks. If the ledger enforces account types, use addresses that match its configured patterns.

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.

```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 WALLET_ACCOUNT="users:$RUN_ID:wallet"
export BANK_ACCOUNT="users:$RUN_ID:bank"
export DESTINATION_ACCOUNT="merchants:$RUN_ID"
export FUNDING_REFERENCE="setup:$RUN_ID:funding"
export PAYMENT_REFERENCE="numscript-payment:$RUN_ID"
```

The example pays USD 80.00 from two balances. Fund the wallet with USD 60.00 and the bank account with USD 50.00 first:

```bash
jq --null-input \
  --arg reference "$FUNDING_REFERENCE" \
  --arg wallet "$WALLET_ACCOUNT" \
  --arg bank "$BANK_ACCOUNT" \
  '{
    reference: $reference,
    postings: [
      {source: "world", destination: $wallet, amount: 6000, asset: "USD/2"},
      {source: "world", destination: $bank, amount: 5000, asset: "USD/2"}
    ]
  }' \
  | 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: $FUNDING_REFERENCE" \
      --data @- \
  > /dev/null
```

## Declare the program and its variables

The program lists sources in priority order. Ledger takes the available amount from the wallet before using the bank account.

```numscript
vars {
  account $wallet
  account $bank
  account $destination
  monetary $amount
  string $order_id
}

set_tx_meta("order_id", $order_id)
set_tx_meta("kind", "purchase")

send $amount (
  source = {
    $wallet
    $bank
  }
  destination = $destination
)
```

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

```bash
SCRIPT=$(cat <<'NUMSCRIPT'
vars {
  account $wallet
  account $bank
  account $destination
  monetary $amount
  string $order_id
}

set_tx_meta("order_id", $order_id)
set_tx_meta("kind", "purchase")

send $amount (
  source = {
    $wallet
    $bank
  }
  destination = $destination
)
NUMSCRIPT
)
```

Pass values separately from the source. This avoids constructing executable code from application input.

| Numscript type | Variable value example |
| -------------- | ---------------------- |
| `account`      | `users:alice:wallet`   |
| `monetary`     | `USD/2 8000`           |
| `asset`        | `USD/2`                |
| `string`       | `ord-2026-0043`        |
| `number`       | `42`                   |
| `portion`      | `2.5%` or `1/4`        |

## Execute the inline program

Build the JSON body with `jq` so newlines and quotes in the program are encoded correctly:

```bash
jq --null-input \
  --arg plain "$SCRIPT" \
  --arg wallet "$WALLET_ACCOUNT" \
  --arg bank "$BANK_ACCOUNT" \
  --arg destination "$DESTINATION_ACCOUNT" \
  --arg reference "$PAYMENT_REFERENCE" \
  --arg orderId "$RUN_ID" \
  '{
    reference: $reference,
    script: {
      plain: $plain,
      vars: {
        wallet: $wallet,
        bank: $bank,
        destination: $destination,
        amount: "USD/2 8000",
        order_id: $orderId
      }
    }
  }' \
  | 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: $PAYMENT_REFERENCE:create" \
      --data @- \
  > /tmp/numscript-transaction.json
```

Ledger returns `201 Created`. Inspect the resolved postings rather than duplicating the resolution logic in your application:

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

The transaction contains two postings to `$DESTINATION_ACCOUNT`: USD 60.00 from `$WALLET_ACCOUNT` and USD 20.00 from `$BANK_ACCOUNT`. It also contains the run ID and `kind: "purchase"` in its metadata.

## Verify the resolved state

Check the destination and both sources. Each command fails if the expected balance is absent:

```bash
get_usd_balance() {
  local account=$1
  curl --fail-with-body --silent --show-error \
    "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$account" \
    --header "Authorization: Bearer $LEDGER_TOKEN" \
    | jq -er '
        .data.volumes[]
        | select(.asset == "USD/2" and .color == "")
        | .volumes.balance'
}

test "$(get_usd_balance "$WALLET_ACCOUNT")" = "0" &&
test "$(get_usd_balance "$BANK_ACCOUNT")" = "3000" &&
test "$(get_usd_balance "$DESTINATION_ACCOUNT")" = "8000"
```

After this example:

- the wallet balance is `"0"`;
- the bank balance is `"3000"`;
- the merchant balance is `"8000"`.

## Choose source behavior deliberately

| Construct                          | Behavior                                                  | Use it when                                                                                         |
| ---------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `@world`                           | Creates or destroys an amount at the ledger boundary      | The business event represents issuance, deposit, withdrawal, or another explicit boundary movement. |
| `{ $wallet $bank }`                | Draws from sources in order until the amount is satisfied | A payment has a documented funding priority.                                                        |
| `allowing overdraft up to $limit`  | Permits a negative balance up to a monetary bound         | The account has a controlled credit limit in the same asset.                                        |
| `allowing unbounded overdraft`     | Removes the balance floor for that source                 | The account is explicitly modeled as an unlimited liability or technical clearing account.          |
| `set_tx_meta` / `set_account_meta` | Writes metadata in the same committed transaction         | The metadata describes the accounting event or an involved account at that point in time.           |

An unbounded overdraft can hide a funding error by allowing any negative balance. Prefer a bounded overdraft when the domain has a credit limit, and alert on negative balances independently.

## Handle errors

| Failure                                           | What to inspect                                                           | Action                                                                                                                                                                                                                                           |
| ------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Numscript parse error                             | The parser details in `errorCode` and `errorMessage`                      | Fix the program. Do not retry the same invalid source.                                                                                                                                                                                           |
| Invalid variable                                  | The declared type and the string in `script.vars`                         | Encode accounts without `@`, monetary values as `ASSET amount`, and portions in a supported format.                                                                                                                                              |
| Insufficient funds                                | The asset, required amount, and available balance in the structured error | Fund another source, lower the amount, or change the documented funding policy. The current Numscript error does not identify which resolved account or color ran short.                                                                         |
| Invalid account address or account-type rejection | The account variables and the ledger's account-type rules                 | Correct the variable or use an address accepted by the chart of accounts. A new valid destination account is created by the transaction and does not need a separate setup step.                                                                 |
| `409` idempotency conflict                        | The key was already used with different request content                   | Restore the original body for a retry, or use a new key for a genuinely new operation.                                                                                                                                                           |
| `503`                                             | Inspect `errorCode`; the status alone does not identify the cause         | Retry `STALE_INPUTS_RESOLUTION` with the same body and key. Retry `PRELOAD_UNAVAILABLE` only a bounded number of times, then validate the program and variables. Treat `NO_LEADER` or a failing health check as a cluster-availability incident. |

## Retry or change the program

Bound your 503 retries

Some interpreter and variable errors are reported as `PRELOAD_UNAVAILABLE`. If the same response persists after bounded backoff, stop the workflow and correct the input or investigate the cluster. Do not retry a `503` indefinitely.

Changing the source, a variable, or the program changes the logical operation. Use a new idempotency key and, when appropriate, a new business reference. A committed Numscript transaction is immutable; correct it with a revert or a new compensating transaction.

Continue with [Reuse and Version Numscript Programs](https://docs.formance.com/v4.0/modules/ledger/transactions/numscript-library) when several callers must share the same program.
