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 Accounts.Go to v3.2
Ledger

Account Types and Enforcement

Validate account-address patterns and choose how each account's volumes are stored.

Account types turn a chart of accounts into rules Ledger can enforce. Each type combines a name, an address pattern, optional variable constraints, and a volume persistence mode.

Use them to reject address typos before those typos create new balance buckets.

Before you start#

The STRICT rollout commands below change account-type configuration and create two probe transactions: one write to an address that must match an active type, and one write to an address that must match no type at all. Together they prove that enforcement accepts what it should and rejects what it should. Neither is meant to leave value behind: the first is reverted as soon as it succeeds, and the second is expected to be rejected.

Rehearse before production

Introduce account types in AUDIT mode first: adding the first type while the default STRICT mode is active can immediately reject every address that the type does not cover. Run these commands against a dedicated ledger that contains a representative copy of your address patterns and transaction flows, and do not point LEDGER_NAME at production until you have reviewed each write.

Checkpoint commands and request signing

This rollout uses ledgerctl query-checkpoint create and delete. If mandatory request signing is enabled, both commands fail: in the current 3.0 preview they submit unsigned mutations. Complete this rollout and its checkpoint cleanup before you enable that policy, or wait for a release with a tested signed checkpoint-management path.

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.

This rollout also needs ledgerctl, and targets an existing ledger rather than a disposable one:

bash
export LEDGER_NAME="account-types-rehearsal"
export LEDGERCTL_SERVER="ledger-grpc.example.com:443"
export LEDGERCTL_AUTH_TOKEN="$LEDGER_TOKEN"

The token needs these granular scopes:

OperationScope
List accounts and account typesledger:AccountRead
List historical transactionsledger:TransactionRead
Read the active enforcement modeledger:LedgerRead
Add or remove account types, or change enforcement, through HTTPledger:MetadataWrite
Add or remove account types, or change enforcement, through the current ledgerctl gRPC commandsledger:OpsWrite
Create and revert probe transactionsledger:TransactionWrite
Create, inspect, and delete the inventory checkpointledger:ClusterWrite, ledger:ClusterRead

Your deployment may map the virtual ledger:read and ledger:write scopes to some of these permissions. Confirm the effective mapping in Authentication and Authorization. Configure the gRPC endpoint and TLS settings as described in Choose Read Consistency and Use Checkpoints. See Read Ledger Data for the read routes and Create Transactions with Postings for the write contract.

Define an address pattern#

A pattern has colon-separated fixed and variable segments:

customers:{customerId}:wallets:{wallet}
merchants:{merchantId}:earnings
platform:fees

Variables use {name} and match one non-empty segment. A pattern must match the full address, not only its prefix.

You can constrain a variable with one of these segment types:

ConstraintAccepted value
regexA value matching the supplied regular expression
uuidAn RFC 4122 UUID string
uint64A non-empty decimal unsigned integer
bytesAn even-length hexadecimal string

Add a type through the HTTP API:

bash
curl --fail-with-body -X POST \
  "${CURL_AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "customer-wallet",
    "pattern": "customers:{customerId}:wallets:{wallet}",
    "persistence": "NORMAL",
    "segmentTypes": {
      "customerId": { "type": "uuid" },
      "wallet": { "type": "regex", "regex": "main|rewards" }
    }
  }' \
  "${LEDGER_URL}/v3/${LEDGER_NAME}/account-types"

The CLI supports account types without segment constraints:

bash
ledgerctl account-types add merchant-earnings \
  'merchants:{merchantId}:earnings' \
  --ledger "${LEDGER_NAME}" \
  --persistence normal

Do not put a regular expression inside {...}. The pattern contains only the variable name; HTTP segmentTypes carries its constraint.

Understand overlapping patterns#

When several types can match an address, Ledger selects the pattern with the greatest number of fixed segments. This permits a general pattern and a more specific exception:

wallets:{id}
wallets:treasury

Ledger rejects patterns that can match the same address with the same specificity. For example, users:{id} and users:{name} conflict because neither pattern is more specific.

The built-in world account is always accepted and does not require an account type.

Choose a persistence mode#

Every account type also carries a persistence mode. It controls whether Ledger keeps a stored volume row for the accounts that match the type, and whether those accounts may still hold value once a batch ends. A volume row is the per-asset, per-color input/output pair that account reads report; no mode affects transaction history.

PersistenceBehaviorUse it when
NORMALKeep cumulative volumes, including after the balance returns to zero.Direct account reads must retain input and output totals.
EPHEMERALKeep a non-zero volume and remove its row when input equals output at commit.The account only needs a stored volume while it holds value.
TRANSIENTDo not keep a volume row and require the account to finish the atomic Apply batch at zero.The account is an intermediary that must not retain value beyond one atomic batch.

EPHEMERAL removes the zero-balance volume row, not transaction history. TRANSIENT checks the final net balance across the entire atomic Apply batch (the proposal), not after each transaction request inside that batch. A regular create-transaction request is a one-request batch, so the account must still finish that transaction at zero. In a multi-request atomic batch, a later request can return it to zero before the batch ends. Every asset and color touched on the intermediary must end at zero.

An account read assembles its volumes from the stored rows and from nothing else, which is what makes the mode visible to callers. Under NORMAL, a drained account still reports its cumulative input and output alongside a zero balance. Under EPHEMERAL, the purged asset and color is absent from the response once input equals output, so those totals are no longer readable even though the transactions that produced them remain in history. Under TRANSIENT, the account never reports volumes at all. The address itself still resolves in every mode: a direct read of an account with no remaining rows returns its metadata and no volumes.

Do not choose EPHEMERAL or TRANSIENT only to reduce storage. First confirm that direct reads, indexes, reconciliations, and recovery procedures do not depend on the volume row.

Move from AUDIT to STRICT#

The ledger's default enforcement mode controls addresses that match no type:

ModeBehavior
AUDITAccept unmatched addresses.
STRICTReject unmatched addresses with ACCOUNT_NOT_MATCHING_TYPE.

If no account types exist, address-type enforcement is inactive. As soon as the first type exists, the default mode applies to every unmatched non-world address.

AUDIT accepts an unmatched address without returning a warning list. Ledger also has no endpoint that reports which type matched an existing address. Treat AUDIT as a permissive mode while you build and review your own coverage report.

1. Set AUDIT and prove the active mode#

Set AUDIT before adding the first type, then read the ledger configuration independently:

bash
set_enforcement_mode() {
  curl --fail-with-body --silent --show-error \
    --request PUT \
    "${CURL_AUTH[@]}" \
    --header "Content-Type: application/json" \
    --data "{\"enforcementMode\":\"$1\"}" \
    "$LEDGER_URL/v3/$LEDGER_NAME/account-types/default-enforcement-mode"
}

read_enforcement_mode() {
  curl --fail-with-body --silent --show-error \
    "${CURL_AUTH[@]}" \
    "$LEDGER_URL/v3/$LEDGER_NAME" \
    | jq -er '.data.defaultEnforcementMode'
}

set_enforcement_mode AUDIT
test "$(read_enforcement_mode)" = "CHART_ENFORCEMENT_AUDIT"

Add the required types while this check still passes. List them and keep the response as STRICT rollout evidence:

bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/account-types" \
  > /tmp/ledger-account-types.json

jq -e '.data.types | length > 0' /tmp/ledger-account-types.json

2. Inventory addresses that must remain valid#

For the final production check, pause application writers before creating the inventory and keep them paused until the STRICT probes pass or you return to AUDIT. Without that pause, a writer can introduce a new address after the inventory and before the mode switch.

Create a query checkpoint so the account and transaction exports come from the same committed dataset:

bash
CHECKPOINT_JSON="$(ledgerctl query-checkpoint create --json)"
CHECKPOINT_ID="$(jq -er '.checkpointId | tostring' <<<"$CHECKPOINT_JSON")"

cleanup_checkpoint() {
  if [ -n "${CHECKPOINT_ID:-}" ]; then
    ledgerctl query-checkpoint delete "$CHECKPOINT_ID" >/dev/null 2>&1 || true
  fi
}
trap cleanup_checkpoint EXIT INT TERM

ledgerctl query-checkpoint info "$CHECKPOINT_ID" --json \
  | jq -e --arg id "$CHECKPOINT_ID" \
      '(.checkpointId | tostring) == $id'

A checkpoint can take a short time to become readable on the contacted replica. Retry only CHECKPOINT_NOT_READY, then export every account and transaction:

bash
CHECKPOINT_READY=false

for attempt in $(seq 1 30); do
  if ledgerctl accounts list \
    --ledger "$LEDGER_NAME" \
    --all \
    --checkpoint-id "$CHECKPOINT_ID" \
    --json \
    > /tmp/ledger-accounts.json \
    2> /tmp/ledger-checkpoint-read.err
  then
    CHECKPOINT_READY=true
    break
  fi

  if ! grep -q 'CHECKPOINT_NOT_READY' /tmp/ledger-checkpoint-read.err; then
    cat /tmp/ledger-checkpoint-read.err >&2
    exit 1
  fi

  sleep 2
done

test "$CHECKPOINT_READY" = true

TRANSACTIONS_READY=false

for attempt in $(seq 1 30); do
  if ledgerctl transactions list \
    --ledger "$LEDGER_NAME" \
    --all \
    --reverse \
    --checkpoint-id "$CHECKPOINT_ID" \
    --json \
    > /tmp/ledger-transactions.json \
    2> /tmp/ledger-checkpoint-read.err
  then
    TRANSACTIONS_READY=true
    break
  fi

  if ! grep -q 'CHECKPOINT_NOT_READY' /tmp/ledger-checkpoint-read.err; then
    cat /tmp/ledger-checkpoint-read.err >&2
    exit 1
  fi

  sleep 2
done


test "$TRANSACTIONS_READY" = true

{
  jq -r '.[].address | select(. != "world")' /tmp/ledger-accounts.json
  jq -r \
    '.[].postings[]? | .source, .destination | select(. != "world")' \
    /tmp/ledger-transactions.json
} | sort -u > /tmp/ledger-account-addresses.txt

wc -l /tmp/ledger-account-addresses.txt

The transaction export matters because EPHEMERAL and TRANSIENT accounts may not appear in current account results, while a later revert still validates their original addresses. Also add addresses from:

  • every transaction template and metadata writer that is still active;
  • bulk jobs, repair tools, imports, and scheduled workflows;
  • planned account shapes that will appear after switching to STRICT.

The team that owns each writer should confirm the type expected for every address it can produce.

Ledger does not produce this match report for you. Store the review result as JSON so switching to STRICT has a concrete gate:

json
[
  {
    "address": "customers:8bfcf61d-14ea-4e41-bb11-f064b8949758:wallets:main",
    "matchedType": "customer-wallet",
    "source": "current-account"
  }
]

Save the complete report as /tmp/account-type-coverage.json. The following gate checks that every current account appears in the report and that every reviewed row names a type:

bash
jq -e '
  length > 0
  and all(.[];
    ((.address | type) == "string" and (.address | length) > 0)
    and ((.matchedType | type) == "string" and (.matchedType | length) > 0)
    and ((.source | type) == "string" and (.source | length) > 0)
  )
' /tmp/account-type-coverage.json

MISSING_CURRENT="$(
  comm -23 \
    /tmp/ledger-account-addresses.txt \
    <(jq -r '.[].address' /tmp/account-type-coverage.json | sort -u)
)"

test -z "$MISSING_CURRENT"

UNKNOWN_TYPES="$(
  comm -23 \
    <(jq -r '.[].matchedType' /tmp/account-type-coverage.json | sort -u) \
    <(jq -r '.data.types[].name' /tmp/ledger-account-types.json | sort -u)
)"

test -z "$UNKNOWN_TYPES"

This gate proves that the review is complete and refers only to active type names. The application owner must still confirm that each address matches the named type's full pattern and segment constraints; Ledger does not expose that check through HTTP or ledgerctl.

3. Switch to STRICT and run positive and negative probes#

Switch to STRICT only after the inventory gate passes:

bash
set_enforcement_mode STRICT
test "$(read_enforcement_mode)" = "CHART_ENFORCEMENT_STRICT"

Choose a NORMAL or EPHEMERAL address that must match an active type. Generate a fresh run identifier every time you repeat the probes: references are immutable and idempotency outcomes are retained, so reusing either value could return an earlier result instead of testing the current rules.

The positive probe deposits one unit and immediately reverts it:

bash
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-${BASHPID:-$$}-${RANDOM}"
export VALID_ACCOUNT="customers:8bfcf61d-14ea-4e41-bb11-f064b8949758:wallets:main"

POSITIVE_STATUS="$(curl --silent --show-error \
  --output /tmp/account-type-positive.json \
  --write-out '%{http_code}' \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: account-type-positive:$RUN_ID:create" \
  --data "$(jq -n \
    --arg destination "$VALID_ACCOUNT" \
    --arg reference "account-type-positive:$RUN_ID" '{
    reference: $reference,
    postings: [{
      source: "world",
      destination: $destination,
      asset: "USD/2",
      amount: 1
    }]
  }')")"

test "$POSITIVE_STATUS" = "201"
POSITIVE_TRANSACTION_ID="$(jq -er '.data.transaction.id' /tmp/account-type-positive.json)"

REVERT_STATUS="$(curl --silent --show-error \
  --output /tmp/account-type-positive-revert.json \
  --write-out '%{http_code}' \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: account-type-positive:$RUN_ID:revert" \
  --data '{"metadata":{"reason":"account_type_validation"}}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$POSITIVE_TRANSACTION_ID/revert")"

test "$REVERT_STATUS" = "201"

The deposit exists between those two requests, and nothing reverts it automatically. If the run stops before the revert returns 201, take the transaction ID from /tmp/account-type-positive.json and revert it by hand before you repeat the probes.

Next, choose an address that you have confirmed cannot match any active pattern. The rejected request must not create a transaction:

bash
export INVALID_ACCOUNT="qa:strict-rejection-probe"

NEGATIVE_STATUS="$(curl --silent --show-error \
  --output /tmp/account-type-negative.json \
  --write-out '%{http_code}' \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: account-type-negative:$RUN_ID:create" \
  --data "$(jq -n \
    --arg destination "$INVALID_ACCOUNT" \
    --arg reference "account-type-negative:$RUN_ID" '{
    reference: $reference,
    postings: [{
      source: "world",
      destination: $destination,
      asset: "USD/2",
      amount: 1
    }]
  }')")"

if [ "$NEGATIVE_STATUS" = "201" ]; then
  UNEXPECTED_ID="$(jq -r '.data.transaction.id // empty' /tmp/account-type-negative.json)"

  if [ -z "$UNEXPECTED_ID" ]; then
    printf 'negative probe committed a transaction; read its id from %s and revert it by hand\n' \
      /tmp/account-type-negative.json >&2
  else
    printf 'negative probe committed transaction %s; reverting\n' "$UNEXPECTED_ID" >&2

    CLEANUP_STATUS="$(curl --silent --show-error \
      --output /tmp/account-type-negative-revert.json \
      --write-out '%{http_code}' \
      --request POST \
      "${CURL_AUTH[@]}" \
      --header "Content-Type: application/json" \
      --header "Idempotency-Key: account-type-negative:$RUN_ID:revert" \
      --data '{"metadata":{"reason":"unexpected_negative_probe"}}' \
      "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$UNEXPECTED_ID/revert" || true)"

    if [ "$CLEANUP_STATUS" = "201" ]; then
      printf 'reverted transaction %s\n' "$UNEXPECTED_ID" >&2
    else
      printf 'REVERT FAILED (status %s) for transaction %s; revert it by hand before repeating the rollout\n' \
        "$CLEANUP_STATUS" "$UNEXPECTED_ID" >&2
    fi
  fi
fi

test "$NEGATIVE_STATUS" = "400"
jq -e --arg account "$INVALID_ACCOUNT" '
  .errorCode == "ACCOUNT_NOT_MATCHING_TYPE"
  and .errorMessage ==
    ("account does not match any account type pattern: " + $account)
' \
  /tmp/account-type-negative.json

The 201 branch runs before the assertion on purpose. set -eo pipefail is active from the runnable setup, so a bare failing assertion would stop the shell with the probe's unit still in the ledger and no chance to act on remediation further down the page. The revert captures its own HTTP status and asserts 201, the same way the positive probe does, because --fail-with-body treats every status below 400 as success — a redirect or a 200 would otherwise be reported as a revert that never happened. Neither the request nor a missing ID can stop the shell, so the transaction ID reaches stderr whichever way it goes.

If your chart intentionally has a pattern that matches every possible address, there is no negative address to test. Record that decision explicitly: STRICT cannot reject an unmatched address when every address matches by design.

After the required probes pass, delete the captured checkpoint and verify that its ID is absent. Resume application writers only after this check:

bash
ledgerctl query-checkpoint delete "$CHECKPOINT_ID"

ledgerctl query-checkpoint list --json \
  | jq -e --arg id "$CHECKPOINT_ID" \
      'all(.[]; (.checkpointId | tostring) != $id)'

CHECKPOINT_ID=""
trap - EXIT INT TERM

4. Roll back admission when a canary fails#

If an expected application write starts returning ACCOUNT_NOT_MATCHING_TYPE, restore permissive admission before changing any type:

bash
set_enforcement_mode AUDIT
test "$(read_enforcement_mode)" = "CHART_ENFORCEMENT_AUDIT"

Changing the mode affects future writes only. It does not alter committed transactions, and a request rejected in STRICT made no accounting change. Add the missing coverage, repeat the inventory gate on the same dataset, then switch to STRICT again.

Ledger remembers a final failure under its idempotency key. After correcting coverage, retry a rejected business operation with a new idempotency key; reusing the rejected key returns the stored failure even in AUDIT.

If the negative probe returned 201, the block above reports the transaction ID and attempts the revert. Read its stderr output: reverted transaction <id> means the revert returned 201 and the ledger is clean, while REVERT FAILED (status ...) means that transaction is still committed and needs reverting by hand. Either way, correct the overly broad pattern or the probe address before repeating the rollout — a 201 there means an address you expected STRICT to reject is matching an active type.

Before switching a production ledger to STRICT, also exercise standalone account-metadata saves, reversals, bulk operations, transient zero-balance checks, and ephemeral reads with representative application requests. A metadata deletion does not prove address matching, and accountMetadata attached to a transaction is not a replacement for the posting-address probes above.

Verify the active rules#

List account types through HTTP:

bash
curl --fail-with-body \
  "${CURL_AUTH[@]}" \
  "${LEDGER_URL}/v3/${LEDGER_NAME}/account-types"

Or through the CLI:

bash
ledgerctl account-types list --ledger "${LEDGER_NAME}"

The HTTP response contains the stored pattern, persistence, and segment constraints:

json
{
  "data": {
    "types": [
      {
        "name": "customer-wallet",
        "pattern": "customers:{customerId}:wallets:{wallet}",
        "persistence": "NORMAL",
        "segmentTypes": {
          "customerId": { "type": "uuid" },
          "wallet": { "type": "regex", "regex": "main|rewards" }
        }
      }
    ]
  }
}

Test both sides of every rule: one address that must match and one that must fail. For persistence modes, also test the zero-balance boundary.

Change or remove a type#

Account types have add, get, list, and remove operations. There is no in-place update operation. To evolve a chart, add compatible new types before removing old coverage whenever possible.

bash
ledgerctl account-types remove legacy-wallet --ledger "${LEDGER_NAME}"

Removing a type does not rewrite or delete existing accounts and transactions. In STRICT, it can make future metadata changes or reversals fail when they refer to an address that no remaining type covers.

Common failure modes#

SymptomCauseCorrection
Most writes fail after the first type is addedDefault enforcement was still STRICT and the chart is incompleteSet AUDIT, add complete coverage, then repeat the STRICT rollout.
Adding a second type returns a conflictTwo patterns overlap with equal specificityMerge them or add a genuinely more specific fixed pattern.
A valid-looking ID does not matchThe segment constraint rejects its formatTest UUID, uint64, bytes, or regex values independently.
A transient transaction fails at commitAn intermediary retains a balance for an asset or colorAdd the missing outgoing posting or use NORMAL when value may remain.
An ephemeral account disappears from account-volume reads at zeroIts zero-balance volume row was removed as configuredUse NORMAL when a stored zero-balance row is required.
A historical reversal fails in STRICTIts original address no longer matches any active typeKeep historical patterns covered while those operations remain possible.
AUDIT returns no warning arrayThe mode is permissive but does not emit per-write violationsValidate addresses from representative traffic before switching to STRICT.

When funds from different origins must remain separate inside one matching account and asset, add colors. Account types do not separate balances by themselves.