# Read Ledger Data

Source: https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data

Stack: v4.0

Ledger exposes several records for different questions. Read an account for its current volumes, read a transaction for an accepted movement, use logs for committed changes, and use the audit trail to investigate both accepted and rejected proposals (a proposal is a write batch submitted to Ledger).

- A running Ledger endpoint, from a Stack deployment or a local server

- A bearer token with read and write access, if authentication is enabled

- Bash, curl and jq in your shell

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:

Formance Stack

```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.

Local server, no auth

```bash
set -eo pipefail

export LEDGER_URL="http://localhost:9000"
CURL_AUTH=()
```

`CURL_AUTH` stays empty, so every command below works unchanged whether or not authentication is enabled.

These reads target a ledger that already holds the records you want to inspect:

```bash
export LEDGER_NAME="main"
```

Grant each application only the scopes needed by the routes it calls. See [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

| HTTP read                      | Required scope           |
| ------------------------------ | ------------------------ |
| Accounts and volumes           | `ledger:AccountRead`     |
| Transactions                   | `ledger:TransactionRead` |
| Per-ledger logs and statistics | `ledger:LedgerRead`      |
| Bucket-wide audit entries      | `ledger:AuditRead`       |

The gRPC `ListLogs` method used by `ledgerctl logs list` requires the same `ledger:LedgerRead` scope as the HTTP log route.

## Choose the record

| Question                                                          | Record to read    | Data boundary    |
| ----------------------------------------------------------------- | ----------------- | ---------------- |
| What does this account hold now?                                  | Account           | One ledger       |
| Which postings and metadata were committed?                       | Transaction       | One ledger       |
| Which successful mutations changed this ledger?                   | Ledger log        | One ledger       |
| Why was a proposal accepted or rejected?                          | Audit entry       | The whole bucket |
| How many transactions, postings, logs, and related records exist? | Ledger statistics | One ledger       |

Logs and audit entries are related, but they are not interchangeable. Each fresh proposal that reaches Ledger's state machine produces one audit entry, whether it succeeds or fails. A successful proposal can produce several logs or none. An idempotent replay produces neither another log nor another audit entry, and a request rejected before application is not part of this audit trail.

## Read an account

Retrieve one account by its full address:

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

The response contains the address, typed metadata, and volumes. Volumes are separated by asset and color. Add `?collapseColors=true` only when the caller intentionally wants one total per asset and does not need the color boundary.

List accounts when the application does not know the complete address:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=address ^= "users:"' \
  --data-urlencode 'pageSize=100' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Account lists are ordered alphabetically. See [Filter and Paginate Results](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination) before using a list route for an unbounded export.

## Read a transaction

Retrieve a transaction by its numeric ID:

```bash
: "${TRANSACTION_ID:?set this to the ID returned for a committed transaction}"

curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$TRANSACTION_ID"
```

The response contains the committed transaction.

List transactions to search by reference, account, metadata, or date:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$match":{"reference":"order-2026-0042"}}' \
  --data-urlencode 'pageSize=100' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

The default transaction order is newest first. Pass `reverse=true` for oldest first. Reference and date filters require their corresponding indexes to be ready. The structured reference match is exact. The textual filter grammar does not expose a reference condition.

## Trace a successful transaction

Use this sequence when an application needs to explain what happened to a successful write. It correlates a business reference with the transaction, the global log sequence, and the bucket-wide audit entry, in three hops:

1. `reference` to the transaction `id`, from the transaction list;
2. transaction `id` to the global `sequence`, from the ledger logs, at `payload.apply.log.data.transaction.id` on a `NEW_TRANSACTION` log;
3. global `sequence` to the audit entry, with `filter=log_seq == <sequence>`.

Start with the business reference and idempotency key recorded by the caller, then wait for one exact transaction. A filtered HTTP list can briefly lag behind a fresh write, so an empty result is not yet a negative result:

```bash
export REFERENCE="order-2026-0042"
export EXPECTED_IDEMPOTENCY_KEY="create-order-2026-0042"
export TRANSACTION_WAIT_SECONDS="${TRANSACTION_WAIT_SECONDS:-30}"

if ! [[ "$TRANSACTION_WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
  echo "TRANSACTION_WAIT_SECONDS must be a positive integer" >&2
  exit 2
fi

REFERENCE_FILTER="$(
  jq -nc --arg reference "$REFERENCE" \
    '{"$match":{"reference":$reference}}'
)"

TRANSACTION_ID=""
TRANSACTION_DEADLINE=$((SECONDS + TRANSACTION_WAIT_SECONDS))

while (( SECONDS < TRANSACTION_DEADLINE )); do
  TRANSACTION_RESULTS="$(curl --fail-with-body --silent --show-error --get \
    "${CURL_AUTH[@]}" \
    --data-urlencode "filter=$REFERENCE_FILTER" \
    --data-urlencode 'pageSize=2' \
    "$LEDGER_URL/v3/$LEDGER_NAME/transactions")"

  TRANSACTION_MATCH_COUNT="$(jq --arg reference "$REFERENCE" \
    '[.data[] | select(.reference == $reference)] | length' \
    <<<"$TRANSACTION_RESULTS")"

  case "$TRANSACTION_MATCH_COUNT" in
    0)
      sleep 1
      ;;
    1)
      TRANSACTION_ID="$(jq -er --arg reference "$REFERENCE" '
        [.data[] | select(.reference == $reference)][0].id | tostring
      ' <<<"$TRANSACTION_RESULTS")"
      break
      ;;
    *)
      echo "More than one transaction matched reference $REFERENCE" >&2
      exit 1
      ;;
  esac
done

if [ -z "$TRANSACTION_ID" ]; then
  echo "Transaction index did not expose reference $REFERENCE within ${TRANSACTION_WAIT_SECONDS}s; correlation is still unknown" >&2
  exit 1
fi
```

The loop waits for a positive match and reports an **unknown** correlation after its deadline. `pageSize=2` is intentional: references are unique, and a second exact match would reveal a violated assumption instead of silently choosing one.

Next, traverse the ledger logs until the created-transaction payload contains that transaction ID. The HTTP log list can also briefly lag behind a fresh write. Follow each page's `next` token and, at the end of the visible logs, poll from the last log returned until the target arrives or the wait expires. The page token is keyed by the ledger-local log ID, while `LOG_SEQUENCE` comes from the enclosing global log:

```bash
export LOG_WAIT_SECONDS="${LOG_WAIT_SECONDS:-30}"

if ! [[ "$LOG_WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
  echo "LOG_WAIT_SECONDS must be a positive integer" >&2
  exit 2
fi

LOG_PAGE_SIZE=1000
LOG_CURSOR=""
LOG_SEQUENCE=""
LOG_DEADLINE=$((SECONDS + LOG_WAIT_SECONDS))

while (( SECONDS < LOG_DEADLINE )); do
  log_curl_args=(
    curl --fail-with-body --silent --show-error --get
    "${CURL_AUTH[@]}"
    --data-urlencode "pageSize=$LOG_PAGE_SIZE"
  )

  if [ -n "$LOG_CURSOR" ]; then
    log_curl_args+=(--data-urlencode "cursor=$LOG_CURSOR")
  fi

  log_curl_args+=("$LEDGER_URL/v3/$LEDGER_NAME/logs")
  LOG_PAGE="$("${log_curl_args[@]}")"

  LOG_SEQUENCE="$(jq -r --arg transactionId "$TRANSACTION_ID" '
    [.data[]
      | select(
          .payload.apply.log.type == "NEW_TRANSACTION"
          and (.payload.apply.log.data.transaction.id | tostring) == $transactionId
        )
      | (.sequence | tostring)]
    | if length == 0 then ""
      elif length == 1 then .[0]
      else error("found more than one creation log for this transaction")
      end
  ' <<<"$LOG_PAGE")"

  if [ -n "$LOG_SEQUENCE" ]; then
    break
  fi

  LOG_NEXT="$(jq -r '.next // empty' <<<"$LOG_PAGE")"
  if [ -n "$LOG_NEXT" ]; then
    LOG_CURSOR="$LOG_NEXT"
    continue
  fi

  # No next token: this is the end of the visible logs. Build a forward
  # token from the last log returned so the next poll resumes after it.
  if (( $(jq '.data | length' <<<"$LOG_PAGE") > 0 )); then
    LOG_CURSOR="$(
      jq -er '.data[-1].payload.apply.log.id
        | {key: tostring} | tojson | @base64' <<<"$LOG_PAGE" \
        | tr '+/' '-_' | tr -d '='
    )"
  fi

  sleep 1
done

if [ -z "$LOG_SEQUENCE" ]; then
  echo "Log index did not expose the creation log for transaction $TRANSACTION_ID within ${LOG_WAIT_SECONDS}s; correlation is still unknown" >&2
  exit 1
fi
```

Resuming after the last log returned is safe because ledger logs become visible in ledger-local ID order, without gaps. The hand-built token is the base64url form, without padding, of `{"key": "<log ID>"}`, the same token a `next` link would carry. A page without `next` means “no more logs are visible yet,” not “the creation log does not exist.” The loop waits there for more logs and never turns the timeout into an absence claim.

Finally, use the global log sequence to locate and retrieve the audit entry. The HTTP audit filter reads an asynchronous secondary index, so wait for that index instead of treating an empty first response as proof that the audit entry is missing:

```bash
export AUDIT_WAIT_SECONDS="${AUDIT_WAIT_SECONDS:-30}"

if ! [[ "$AUDIT_WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
  echo "AUDIT_WAIT_SECONDS must be a positive integer" >&2
  exit 2
fi

AUDIT_SEQUENCE=""
AUDIT_DEADLINE=$((SECONDS + AUDIT_WAIT_SECONDS))

while (( SECONDS < AUDIT_DEADLINE )); do
  AUDIT_RESULTS="$(curl --fail-with-body --silent --show-error --get \
    "${CURL_AUTH[@]}" \
    --data-urlencode "filter=log_seq == $LOG_SEQUENCE" \
    --data-urlencode 'pageSize=100' \
    "$LEDGER_URL/v3/_/audit-entries")"

  AUDIT_MATCH_COUNT="$(jq '.data | length' <<<"$AUDIT_RESULTS")"
  case "$AUDIT_MATCH_COUNT" in
    0)
      sleep 1
      ;;
    1)
      AUDIT_SEQUENCE="$(jq -er '.data[0].sequence | tostring' \
        <<<"$AUDIT_RESULTS")"
      break
      ;;
    *)
      echo "More than one audit entry matched log sequence $LOG_SEQUENCE" >&2
      exit 1
      ;;
  esac
done

if [ -z "$AUDIT_SEQUENCE" ]; then
  echo "Audit index did not expose log sequence $LOG_SEQUENCE within ${AUDIT_WAIT_SECONDS}s; correlation is still unknown" >&2
  exit 1
fi

AUDIT_ENTRY="$(curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/_/audit-entries/$AUDIT_SEQUENCE")"

jq -e \
  --arg ledger "$LEDGER_NAME" \
  --arg logSequence "$LOG_SEQUENCE" \
  --arg idempotencyKey "$EXPECTED_IDEMPOTENCY_KEY" '
    .data.success != null
    and ((.data.ledgers | index($ledger)) != null)
    and any(.data.items[]; (.logSequence | tostring) == $logSequence)
    and .data.idempotency.key == $idempotencyKey
  ' <<<"$AUDIT_ENTRY"

jq \
  --arg transactionId "$TRANSACTION_ID" \
  --arg logSequence "$LOG_SEQUENCE" '{
    transactionId: $transactionId,
    logSequence: $logSequence,
    auditSequence: (.data.sequence | tostring),
    idempotencyKey: (.data.idempotency.key // null),
    callerSubject: (.data.callerSnapshot.identity.subject // null)
  }' <<<"$AUDIT_ENTRY"
```

The loop waits for a positive match and fails with an **unknown** result after its deadline; it never turns temporary audit-index lag into a missing-record conclusion. The first `jq` prints `true` only when all three records agree on the ledger, global log sequence, and expected idempotency key. The second prints the correlation summary. The audit entry's `sequence` is its own identifier; it is not the global log sequence. The caller snapshot is the identity and permissions Ledger recorded when it admitted the proposal.

The audit API cannot filter by idempotency key. If the key is the only available clue, narrow an audit list by ledger, caller, time, and outcome, then retrieve candidate details and compare `.data.idempotency.key` in the client.

## Investigate failed proposals

A failed proposal has no transaction or committed log to follow. Query the audit trail directly by outcome, ledger, caller, proposal, or time. A date filter on the ledger log route additionally requires the opt-in log-date index; see [Create and Manage Indexes](https://docs.formance.com/v4.0/modules/ledger/querying/indexes).

For a recently failed proposal, use its idempotency key as the final correlation check. The filter narrows the candidate set, but the HTTP audit index can lag, so retry for a bounded period and retrieve each compact candidate before deciding:

```bash
export FAILED_AUDIT_WAIT_SECONDS="${FAILED_AUDIT_WAIT_SECONDS:-30}"

: "${EXPECTED_FAILED_IDEMPOTENCY_KEY:?set this to the idempotency key of the failed request}"
if ! [[ "$FAILED_AUDIT_WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
  echo "FAILED_AUDIT_WAIT_SECONDS must be a positive integer" >&2
  exit 2
fi

FAILED_AUDIT_SEQUENCE=""
FAILED_AUDIT_ENTRY=""
FAILED_AUDIT_DEADLINE=$((SECONDS + FAILED_AUDIT_WAIT_SECONDS))

while (( SECONDS < FAILED_AUDIT_DEADLINE )); do
  FAILED_AUDIT_RESULTS="$(curl --fail-with-body --silent --show-error --get \
    "${CURL_AUTH[@]}" \
    --data-urlencode "filter=ledger == \"$LEDGER_NAME\" and outcome == failure" \
    --data-urlencode 'pageSize=100' \
    --data-urlencode 'reverse=true' \
    "$LEDGER_URL/v3/_/audit-entries")"

  while IFS= read -r FAILED_CANDIDATE_SEQUENCE; do
    [ -n "$FAILED_CANDIDATE_SEQUENCE" ] || continue
    FAILED_CANDIDATE_ENTRY="$(curl --fail-with-body --silent --show-error \
      "${CURL_AUTH[@]}" \
      "$LEDGER_URL/v3/_/audit-entries/$FAILED_CANDIDATE_SEQUENCE")"

    if jq -e --arg key "$EXPECTED_FAILED_IDEMPOTENCY_KEY" \
      '.data.idempotency.key == $key' \
      <<<"$FAILED_CANDIDATE_ENTRY" >/dev/null; then
      FAILED_AUDIT_SEQUENCE="$FAILED_CANDIDATE_SEQUENCE"
      FAILED_AUDIT_ENTRY="$FAILED_CANDIDATE_ENTRY"
      break
    fi
  done < <(jq -r '.data[].sequence | tostring' <<<"$FAILED_AUDIT_RESULTS")

  [ -z "$FAILED_AUDIT_SEQUENCE" ] || break
  sleep 1
done

if [ -z "$FAILED_AUDIT_SEQUENCE" ]; then
  echo "No current audit match after ${FAILED_AUDIT_WAIT_SECONDS}s; the failed proposal remains uncorrelated, not proven absent" >&2
  exit 1
fi

jq -e \
  --arg ledger "$LEDGER_NAME" \
  --arg key "$EXPECTED_FAILED_IDEMPOTENCY_KEY" '
    .data.failure != null
    and ((.data.ledgers | index($ledger)) != null)
    and (.data.idempotency.key == $key)
  ' <<<"$FAILED_AUDIT_ENTRY"

jq '.data | {
  sequence: (.sequence | tostring),
  idempotencyKey: .idempotency.key,
  failure,
  items
}' <<<"$FAILED_AUDIT_ENTRY"
```

An audit item has `logSequence: 0` when its order produced no log. If the candidate volume can exceed 100 entries during the wait window, narrow the filter further with the known caller, proposal, or time range, or page through all candidates. A timeout is an observability result, not proof that Ledger never admitted the failed proposal.

Audit routes are bucket-scoped because one proposal can contain orders for more than one ledger. Select a ledger with the audit `filter`; do not add a ledger name to the URL.

## Use ledgerctl over gRPC

`ledgerctl` exposes the gRPC read surface and can print machine-readable output:

```bash
ledgerctl accounts get users:alice --ledger "$LEDGER_NAME" --json
ledgerctl transactions get "$TRANSACTION_ID" --ledger "$LEDGER_NAME" --json
ledgerctl logs list --ledger "$LEDGER_NAME" --page-size 100 --json
ledgerctl audit list --filter "ledger == \"$LEDGER_NAME\" and outcome == failure" --json
ledgerctl ledgers stats --ledger "$LEDGER_NAME" --json
```

Use gRPC or `ledgerctl` when the read must wait for a minimum log sequence or target a query checkpoint. HTTP reads use the default linearizable consistency for each request, but the direct list routes do not expose those additional controls. A linearizable barrier confirms committed cluster state; it does not by itself make an asynchronous secondary index current. See [Choose Read Consistency and Use Checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints).

## Verify the result

- A direct lookup returns `404` when the record does not exist in the selected ledger or bucket.
- A list returning no rows is not proof that a recent write failed. First check the selected ledger, filter, index readiness, and read-consistency choice.
- A transaction proves that Ledger committed the movement. An audit failure explains why Ledger rejected a proposal before it became a transaction.
- Statistics are not an instant write receipt. `transactionCount` and `logCount` advance synchronously, while the [seven usage counters](https://docs.formance.com/v4.0/modules/ledger/querying/analyze-and-aggregate#read-ledger-statistics) can briefly lag on the replica that serves the request.

See [Verify Ledger Integrity](https://docs.formance.com/v4.0/modules/ledger/operations/integrity) for an integrity assessment of stored state; query results are not an integrity proof.

Continue with [Filter and Paginate Results](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination) when one read must return a subset larger than a single response.
