Preview. Stack v4.0 has not been released, and what is documented here can still change before it does. The current release is v3.2, which covers this as Quick Start.Go to v3.2
Ledger

Hands-on walkthrough

Run one Ledger 3.0 session end to end: amounts and volumes, colors, metadata, reads, and aggregation.

Ledger 3.0 has three behaviors that decide how you model a product: cumulative volumes that a reversal never rewinds, colors that segregate balances inside a single asset, and typed metadata that makes a key queryable. This page proves all three against a live server, so you can see the semantics before committing to a design.

Every command runs against one disposable ledger, in one shell session, in order. Each part proves one behavior and links to the page that explains it.

If you have not recorded a transaction yet, start with the Quick Start first — it creates a ledger, records one transaction, and proves that retrying the write does not record it twice. This page assumes that ground.

Ledger's base URL depends on how it is deployed. A Ledger server you run yourself answers at the root of its host. Behind a Formance Stack, requests pass through the Stack Gateway, which serves Ledger under /api/ledger. If you reach Ledger through your Stack's domain you are going through the Gateway; if you started the server yourself, you are not.

Run the commands for your deployment in a shell, and keep that same shell for the rest of the guide. set -eo pipefail stops the shell at the first failing command instead of carrying on with an empty value:

bash
set -eo pipefail

export LEDGER_URL="https://stack.example.com/api/ledger"
export LEDGER_TOKEN="<bearer-token>"
CURL_AUTH=(-H "Authorization: Bearer $LEDGER_TOKEN")

The token needs ledger:read and ledger:write. ledger is the default auth service name. If your deployment uses another service name, replace ledger with your configured name.

Create one run identifier, then the disposable ledger every part below uses. Deriving names from RUN_ID makes the walkthrough safe to repeat:

bash
export RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$"
export WORK_DIR="${TMPDIR:-/tmp}/formance-ledger-$RUN_ID"
mkdir -p "$WORK_DIR"

export LEDGER_NAME="handson-$RUN_ID"

curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: handson:$RUN_ID:create-ledger" \
  --data '{}'

Generate a new RUN_ID when you repeat this page. Idempotency keys identify a write across the complete Ledger service until their configured retention period expires, even after the disposable ledger is deleted.

Amounts, balances, and volumes#

Record three movements in EUR/2, then read the cumulative volumes they produce. world sends 10000 to Alice, Alice sends 2500 to a merchant, and the merchant sends 500 to platform fees.

bash
create_movement() {
  local reference="$1"
  local source="$2"
  local destination="$3"
  local amount="$4"
  local output="$5"

  curl --fail-with-body --silent --show-error \
    --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
    "${CURL_AUTH[@]}" \
    --header "Content-Type: application/json" \
    --header "Idempotency-Key: $RUN_ID:$reference:create" \
    --data "$(jq -n \
      --arg reference "$reference" \
      --arg source "$source" \
      --arg destination "$destination" \
      --argjson amount "$amount" \
      '{
        reference: $reference,
        postings: [{
          source: $source,
          destination: $destination,
          asset: "EUR/2",
          amount: $amount
        }]
      }')" \
    > "$output"
}

create_movement \
  "amounts:seed-alice" \
  "world" \
  "customers:alice:wallets:main" \
  10000 \
  "$WORK_DIR/amounts-seed-alice.json"

create_movement \
  "amounts:alice-to-acme" \
  "customers:alice:wallets:main" \
  "merchants:acme:earnings" \
  2500 \
  "$WORK_DIR/amounts-alice-to-acme.json"

create_movement \
  "amounts:acme-fee" \
  "merchants:acme:earnings" \
  "platform:fees" \
  500 \
  "$WORK_DIR/amounts-acme-fee.json"

Read all three accounts and assert the expected state, rather than relying only on the write responses:

bash
read_account() {
  curl --fail-with-body --silent --show-error \
    "${CURL_AUTH[@]}" \
    "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$1"
}

read_account "customers:alice:wallets:main" > "$WORK_DIR/amounts-alice.json"
read_account "merchants:acme:earnings" > "$WORK_DIR/amounts-acme.json"
read_account "platform:fees" > "$WORK_DIR/amounts-fees.json"

jq -e '
  any(.data.volumes[];
    .asset == "EUR/2" and .color == ""
    and .volumes == {input:"10000", output:"2500", balance:"7500"}
  )
' "$WORK_DIR/amounts-alice.json"

jq -e '
  any(.data.volumes[];
    .asset == "EUR/2" and .color == ""
    and .volumes == {input:"2500", output:"500", balance:"2000"}
  )
' "$WORK_DIR/amounts-acme.json"

jq -e '
  any(.data.volumes[];
    .asset == "EUR/2" and .color == ""
    and .volumes == {input:"500", output:"0", balance:"500"}
  )
' "$WORK_DIR/amounts-fees.json"

Now revert the fee transaction and read the two affected accounts again. The balances recover, but input and output keep both movements — a reversal adds compensating postings rather than subtracting from cumulative volumes:

bash
FEE_TRANSACTION_ID="$(jq -er '.data.transaction.id' "$WORK_DIR/amounts-acme-fee.json")"

REVERT_STATUS="$(curl --silent --show-error \
  --output "$WORK_DIR/amounts-acme-fee-revert.json" \
  --write-out '%{http_code}' \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $RUN_ID:amounts:acme-fee:revert" \
  --data '{"metadata":{"reason":"handson_check"}}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$FEE_TRANSACTION_ID/revert")"

test "$REVERT_STATUS" = "201"

read_account "merchants:acme:earnings" > "$WORK_DIR/amounts-acme-after-revert.json"
read_account "platform:fees" > "$WORK_DIR/amounts-fees-after-revert.json"

jq -e '
  any(.data.volumes[];
    .asset == "EUR/2" and .color == ""
    and .volumes == {input:"3000", output:"500", balance:"2500"}
  )
' "$WORK_DIR/amounts-acme-after-revert.json"

jq -e '
  any(.data.volumes[];
    .asset == "EUR/2" and .color == ""
    and .volumes == {input:"500", output:"500", balance:"0"}
  )
' "$WORK_DIR/amounts-fees-after-revert.json"

Finally, total a set of accounts with the aggregate endpoint. filter is the only account selector it accepts — an unrecognized parameter is ignored rather than rejected, so a misspelled selector returns a successful total over every account in the ledger, world included:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  --get --data-urlencode 'filter=address ^= "customers:"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/volumes" \
  > "$WORK_DIR/customer-volumes.json"

curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/volumes" \
  > "$WORK_DIR/all-volumes.json"

jq -e '.data.volumes | length > 0' "$WORK_DIR/customer-volumes.json" >/dev/null

The response sums per asset and color across the selected accounts; it carries no addresses, so nothing in it says which accounts were selected. Prove the filter took effect by comparing it with the unfiltered aggregate, using the asset this section created. world sent 10000, Alice sent 2500, the fee movement sent 500, and reverting that fee added a compensating 500 — so the whole ledger holds 13500 of output while the customers: selection reports Alice's 2500:

bash
sum_output() {
  jq -r '[.data.volumes[] | select(.asset == "EUR/2") | .output | tonumber] | add // 0' "$1"
}

SCOPED_OUTPUT="$(sum_output "$WORK_DIR/customer-volumes.json")"
TOTAL_OUTPUT="$(sum_output "$WORK_DIR/all-volumes.json")"

test "$SCOPED_OUTPUT" -lt "$TOTAL_OUTPUT"

If those two are equal, the selector was ignored and the "scoped" total is the whole ledger.

Account Types and Enforcement

How address patterns are validated, what AUDIT and STRICT enforcement do, and how a persistence mode changes what an account read returns. This walkthrough does not create account types; that rollout needs its own ledger.

Assets, Amounts, Balances, and Volumes

Why amounts are unsigned integers, how precision is encoded in the asset, what input, output, and balance each answer, and the aggregate query parameters.

Colors: isolated balances within one asset#

Create three balances on one account in a single transaction — one uncolored, two colored. Color follows the value from source to destination, so a posting cannot debit one color and credit another.

bash
curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $RUN_ID:color:dataset" \
  --data '{
    "reference": "color-dataset-001",
    "postings": [
      {
        "source": "world",
        "destination": "customers:alice:wallets:main",
        "asset": "USD/2",
        "amount": 10000
      },
      {
        "source": "world",
        "destination": "customers:alice:wallets:main",
        "asset": "USD/2",
        "amount": 5000,
        "color": "GRANTS"
      },
      {
        "source": "world",
        "destination": "customers:alice:wallets:main",
        "asset": "USD/2",
        "amount": 2500,
        "color": "OPS"
      }
    ]
  }'

Read the account without a collapse option. Ledger returns one volume row per (asset, color), including color: "" for the uncolored bucket:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main"

Now prove the buckets are isolated. Attempt to spend 5001 from GRANTS, which holds 5000. Capture both accounts before the request so you can show the rejection changed neither:

bash
account_state() {
  local address="$1"
  local body
  local status

  body="$(mktemp)"
  status="$(curl --silent --show-error \
    --output "$body" \
    --write-out '%{http_code}' \
    "${CURL_AUTH[@]}" \
    "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$address")"

  case "$status" in
    200)
      jq -cS '{
        status: 200,
        volumes: (.data.volumes | sort_by([.asset, .color]))
      }' "$body"
      ;;
    404)
      printf '{"status":404}\n'
      ;;
    *)
      rm -f "$body"
      return 1
      ;;
  esac

  rm -f "$body"
}

SOURCE_ACCOUNT="customers:alice:wallets:main"
DESTINATION_ACCOUNT="merchants:qa:overspend"

SOURCE_BEFORE="$(account_state "$SOURCE_ACCOUNT")"
DESTINATION_BEFORE="$(account_state "$DESTINATION_ACCOUNT")"

OVERSPEND_STATUS="$(curl --silent --show-error \
  --output "$WORK_DIR/color-overspend.json" \
  --write-out '%{http_code}' \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $RUN_ID:color:overspend" \
  --data '{
    "reference": "color:overspend:expected-failure",
    "postings": [{
      "source": "customers:alice:wallets:main",
      "destination": "merchants:qa:overspend",
      "asset": "USD/2",
      "amount": 5001,
      "color": "GRANTS"
    }]
  }')"

test "$OVERSPEND_STATUS" = "400"
jq -e '.errorCode == "INSUFFICIENT_FUNDS"' "$WORK_DIR/color-overspend.json"

SOURCE_AFTER="$(account_state "$SOURCE_ACCOUNT")"
DESTINATION_AFTER="$(account_state "$DESTINATION_ACCOUNT")"

test "$SOURCE_AFTER" = "$SOURCE_BEFORE"
test "$DESTINATION_AFTER" = "$DESTINATION_BEFORE"

The status code proves which rule rejected the request. The two independent reads prove the rejection was atomic.

Collapse the colored rows for a reporting view. This sums the buckets and returns the result with color: ""; it does not merge or recolor stored balances:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main?collapseColors=true"

curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  --get --data-urlencode 'filter=address ^= "customers:"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/volumes?collapseColors=true"

Never authorize a spend from a collapsed balance when the spend must respect color restrictions. A collapsed empty color is a summary across buckets; an uncollapsed empty color is the real uncolored bucket.

Reclassify value between colors#

There is no in-place recoloring primitive. Move value with one transaction holding two equal postings — retire the old color to world, issue the new color from world. Both postings must be in the same transaction so Ledger commits both or neither.

Read the starting balances first:

bash
color_balance() {
  local color="$1"

  jq -er --arg color "$color" '
    [
      .data.volumes[]
      | select(.asset == "USD/2" and .color == $color)
      | .volumes.balance
      | tonumber
    ]
    | if length == 0 then 0
      elif length == 1 then .[0]
      else error("duplicate color bucket")
      end
  '
}

usd_total() {
  jq -er '
    [.data.volumes[] | select(.asset == "USD/2") | .volumes.balance | tonumber]
    | add // 0
  '
}

BEFORE_RECLASSIFICATION="$(read_account customers:alice:wallets:main)"
GRANTS_BEFORE="$(color_balance GRANTS <<<"$BEFORE_RECLASSIFICATION")"
OPS_BEFORE="$(color_balance OPS <<<"$BEFORE_RECLASSIFICATION")"
TOTAL_BEFORE="$(usd_total <<<"$BEFORE_RECLASSIFICATION")"

test "$GRANTS_BEFORE" -ge 1000

Submit both postings in one request:

bash
RECLASSIFICATION_STATUS="$(curl --silent --show-error \
  --output "$WORK_DIR/color-reclassification.json" \
  --write-out '%{http_code}' \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $RUN_ID:color:reclassify" \
  --data '{
    "reference": "color:reclassify:grants-to-ops:001",
    "metadata": {
      "reason": "approved_budget_reclassification",
      "approvalId": "approval-001"
    },
    "postings": [
      {
        "source": "customers:alice:wallets:main",
        "destination": "world",
        "asset": "USD/2",
        "amount": 1000,
        "color": "GRANTS"
      },
      {
        "source": "world",
        "destination": "customers:alice:wallets:main",
        "asset": "USD/2",
        "amount": 1000,
        "color": "OPS"
      }
    ]
  }')"

test "$RECLASSIFICATION_STATUS" = "201"

Read the account again and assert both bucket changes and the invariant total:

bash
AFTER_RECLASSIFICATION="$(read_account customers:alice:wallets:main)"
GRANTS_AFTER="$(color_balance GRANTS <<<"$AFTER_RECLASSIFICATION")"
OPS_AFTER="$(color_balance OPS <<<"$AFTER_RECLASSIFICATION")"
TOTAL_AFTER="$(usd_total <<<"$AFTER_RECLASSIFICATION")"

test "$GRANTS_AFTER" -eq "$((GRANTS_BEFORE - 1000))"
test "$OPS_AFTER" -eq "$((OPS_BEFORE + 1000))"
test "$TOTAL_AFTER" -eq "$TOTAL_BEFORE"

These arithmetic assertions rely on the small values in this dataset. Production clients must parse Ledger's balance strings with arbitrary-precision integer arithmetic.

Track Fund Origin with Colors

When to reach for colors, why conservation holds per bucket, how Numscript spends a color, what reversals preserve, and the current limits.

Metadata and typed values#

Save account metadata with its own idempotency key. Note externalSequence: a bare JSON integer above 2^53 - 1 loses precision in the HTTP parser, so the exact value goes over the wire as a string.

bash
curl --fail-with-body --silent --show-error \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $RUN_ID:account-alice-metadata" \
  --data '{
    "customerId": "cus_01J2Y8M9D8",
    "country": "FR",
    "riskTier": 2,
    "active": true,
    "externalSequence": "9007199254740993",
    "reviewNote": "remove-after-verification"
  }' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main/metadata"

Read the account back through a separate request and assert what was stored:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main" \
  > "$WORK_DIR/metadata-account-after-save.json"

jq -e '
  .data.metadata.customerId == "cus_01J2Y8M9D8"
  and .data.metadata.country == "FR"
  and .data.metadata.riskTier == 2
  and .data.metadata.active == true
  and .data.metadata.externalSequence == "9007199254740993"
  and .data.metadata.reviewNote == "remove-after-verification"
' "$WORK_DIR/metadata-account-after-save.json"

A save merges keys; it never removes ones you omitted. Delete a key explicitly, then prove the others survived:

bash
curl --fail-with-body --silent --show-error \
  --request DELETE \
  "${CURL_AUTH[@]}" \
  --header "Idempotency-Key: $RUN_ID:account-alice-review-note-delete" \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main/metadata/reviewNote"

curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/customers:alice:wallets:main" \
  > "$WORK_DIR/metadata-account-after-delete.json"

jq -e '
  (.data.metadata | has("reviewNote") | not)
  and .data.metadata.customerId == "cus_01J2Y8M9D8"
  and .data.metadata.riskTier == 2
  and .data.metadata.externalSequence == "9007199254740993"
' "$WORK_DIR/metadata-account-after-delete.json"

Do not rely on null in a save request to delete a key — the HTTP parser skips null entries. Use the DELETE .../metadata/{key} route so the deletion is explicit and auditable.

Declare types for indexed queries#

Declaring a type tells Ledger how to interpret a key when it builds and queries a metadata index. Declare riskTier as a bounded integer, the HTTP-safe externalSequence string as uint64, and a transaction timestamp for range queries:

bash
curl --fail-with-body --silent --show-error \
  --request PUT "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --data '{"type":"uint8"}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/metadata-schema/account/riskTier"

curl --fail-with-body --silent --show-error \
  --request PUT "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --data '{"type":"uint64"}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/metadata-schema/account/externalSequence"

curl --fail-with-body --silent --show-error \
  --request PUT "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --data '{"type":"datetime"}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/metadata-schema/transaction/settledAt"

Retrieve the declarations currently stored on the ledger:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/metadata-schema"

Remove a declaration when the key no longer has one query type. Stored values are untouched, but the typed interpretation and its index are dropped, so update dependent queries first:

bash
curl --fail-with-body --silent --show-error \
  --request DELETE "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/metadata-schema/account/riskTier"

A declaration does not create an index, and an index is not ready the moment it is registered. Building one and gating on every read replica needs direct per-pod URLs, so it stays with the operational guidance in Metadata and Typed Values.

Metadata and Typed Values

Which target to use, how JSON maps to stored types, the large-integer precision trap, what a declaration changes, and how to validate historical values before a type change.

Clean up#

Delete the disposable ledger, then the working directory. Everything this page created derives from RUN_ID, so nothing outside this run is touched:

bash
status="$(curl --fail-with-body --silent --show-error \
  --request DELETE "$LEDGER_URL/v3/$LEDGER_NAME" \
  "${CURL_AUTH[@]}" \
  --header "Idempotency-Key: handson:$RUN_ID:delete-ledger" \
  --output "$WORK_DIR/delete-ledger.json" \
  --write-out '%{http_code}')"

test "$status" = "204"

read_status="$(curl --silent --show-error \
  "${CURL_AUTH[@]}" \
  --output "$WORK_DIR/ledger-after-delete.json" \
  --write-out '%{http_code}' \
  "$LEDGER_URL/v3/$LEDGER_NAME")"

test "$read_status" = "404"

rm -rf "$WORK_DIR"

If the delete response is lost, repeat the same DELETE with handson:$RUN_ID:delete-ledger, then run the 404 read check again.

Deleting a ledger is not a way to correct history. To undo a recorded business event, use Revert a Transaction.