# Design a Chart of Accounts

Source: https://docs.formance.com/v4.0/modules/ledger/modeling/chart-of-accounts

Stack: v4.0

A chart of accounts maps business responsibilities to stable account addresses. A reader should be able to look at `merchants:acme:settlement` and understand who owns the value and why the account exists.

Ledger creates an account when a transaction or metadata operation first refers to its address. There is no separate account-creation step, so the address itself is part of your application contract.

## Choose the ledger boundary first

A ledger is a logical namespace for accounts, transactions, metadata, and sequence numbers. Multiple ledgers in the same cluster share the cluster's ordering, storage estate, availability, and capacity.

Use another ledger when you need a distinct accounting book but can accept the same operational boundary. Use another cluster when the workload needs independent capacity, maintenance, backup, security, or failure boundaries.

| Requirement                                                           | Model it as             |
| --------------------------------------------------------------------- | ----------------------- |
| Another customer, merchant, wallet, or internal pool in the same book | Another account address |
| A logically separate book with its own transactions and sequences     | Another ledger          |
| Independent availability, capacity, or operational ownership          | Another cluster         |
| Searchable context that does not change the balance identity          | Metadata                |

Do not create one ledger per user only to separate balances. That also separates transaction history and makes every new user part of cluster-level ledger management.

## Build addresses from stable segments

Account addresses consist of non-empty segments separated by colons. Use broad business ownership first and more specific purpose later:

```text
customers:{customerId}:wallets:main
customers:{customerId}:wallets:rewards
merchants:{merchantId}:earnings
merchants:{merchantId}:settlement
platform:fees
platform:clearing:card
```

The resulting hierarchy keeps related accounts visible together and gives prefix queries a predictable boundary:

```mermaid
flowchart TD
    Ledger["marketplace ledger"] --> Customers["customers"]
    Ledger --> Merchants["merchants"]
    Ledger --> Platform["platform"]
    Customers --> Alice["alice"]
    Alice --> Main["wallets:main"]
    Alice --> Rewards["wallets:rewards"]
    Merchants --> Acme["acme"]
    Acme --> Earnings["earnings"]
    Acme --> Settlement["settlement"]
    Platform --> Fees["fees"]
    Platform --> Clearing["clearing:card"]
```

Ledger accepts ASCII letters, digits, `_`, and `-` inside an address segment. An address can be at most 256 bytes. Leading, trailing, and repeated colons create empty segments and are rejected.

Prefix matching operates on the raw address string, not on parsed segments. The prefix `customers:1` also matches `customers:10`. Include a trailing colon when you intend to select a hierarchy, for example `customers:1:`.

## Put identity in the address and attributes in metadata

An address should contain the fields that define which balance bucket a posting changes. Metadata should contain descriptive or queryable context that can change without creating another balance.

| Question                                                              | Address segment             | Metadata       |
| --------------------------------------------------------------------- | --------------------------- | -------------- |
| Would changing the value move future postings to a different balance? | Yes                         | No             |
| Must the value be visible in every transaction posting?               | Yes                         | Usually no     |
| Can the value change while the account keeps the same identity?       | Usually no                  | Yes            |
| Example                                                               | `merchants:acme:settlement` | `region: "eu"` |

Avoid embedding labels such as a customer's display name in the address. Prefer an immutable application identifier in the address and keep the display name in metadata.

## Decide what `world` means

`world` is the built-in boundary between the value modeled inside the ledger and value outside it. It can source funds without a balance check and can receive funds leaving the modeled system.

For a product ledger that tracks customer and merchant claims, a deposit can enter from `world`:

```text
world -> customers:alice:wallets:main
```

If the ledger also represents treasury positions, name the internal asset-side account instead:

```text
treasury:bank:eu -> customers:alice:wallets:main
```

The second model carries more reconciliation detail, but it couples product transactions to treasury topology. Choose the smallest boundary that still supports the reconciliations you must perform.

## Model temporary business states explicitly

Temporary does not mean unimportant. Pending payments, settlement positions, fee accruals, and clearing balances often need their own accounts because they answer different operational questions.

```text
payments:{paymentId}:authorization
payments:{paymentId}:capture
settlements:{settlementId}:pending
settlements:{settlementId}:completed
```

Use an account only when you need a distinct balance. Use transaction metadata for state that describes a movement without owning a balance.

## Retire accounts instead of closing them

Ledger has no operation that closes, freezes, or deletes an individual account. An account exists from the first transaction or metadata operation that refers to its address, and it stays in the ledger afterwards. Its postings stay in transaction history, and any later transaction that names the address moves value into or out of it again.

When a customer leaves, a card is cancelled, or a settlement cycle ends, retire the account in your application:

1. **Drain the balance.** Read the account's balances, then record a transaction that moves each remaining asset to where it belongs, such as a payout account, a write-off account, or `world`. Without `force`, Ledger rejects a posting that would take the account below zero, but it never rejects a posting _into_ an account.
2. **Mark the account.** Save account metadata such as `status: "closed"` and `closedAt`. Ledger stores this metadata but does not read it when admitting postings.
3. **Stop writers.** Make every service and Numscript program that builds this address check the status before it writes. Ledger only enforces this if you also use the account-type controls described below.
4. **Filter it out of reads.** Exclude retired accounts with a filter such as `not metadata[status] == "closed"`. To filter accounts on metadata, the key needs a [declared type and a ready index](https://docs.formance.com/v4.0/modules/ledger/modeling/metadata#declare-types-for-indexed-queries).

### Design short-lived accounts to disappear from balances

[Account types](https://docs.formance.com/v4.0/modules/ledger/modeling/account-types) are specific to Ledger 3.0 and let you choose how an account's volumes are stored. If a family of accounts is meant to be emptied and forgotten, such as per-payment authorization or clearing accounts, a persistence mode can make a drained account behave much like a closed one:

| Persistence | What happens when the account is emptied                                                                                               |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `EPHEMERAL` | When input equals output at commit, Ledger removes the volume row, so direct reads stop reporting balances and volumes for that asset. |
| `TRANSIENT` | Ledger never stores volumes, and it rejects any atomic batch that leaves the account with a non-zero balance.                          |

These modes remove stored volumes, not the account. The address still resolves, its metadata remains, and its transactions stay in history. A new posting to an `EPHEMERAL` account stores volumes for it again while it holds value. A `TRANSIENT` account never reports volumes. Read [Choose a persistence mode](https://docs.formance.com/v4.0/modules/ledger/modeling/account-types#choose-a-persistence-mode) before adopting either mode, because the removed input and output totals can no longer be read from the account.

### Block whole address families with STRICT enforcement

In `STRICT` mode, Ledger rejects any posting or account-metadata write whose address matches no active account type, with the error `ACCOUNT_NOT_MATCHING_TYPE`. Removing a type therefore blocks every address that only that type covered, as long as at least one other type remains. Ledger skips this check when a ledger has no account types, so removing the last type lets every address through, even in `STRICT` mode.

This control works on address patterns, not on individual accounts. A type such as `customers:{id}:wallets:main` covers every customer, and no type can exclude one customer from it. The control also applies to reverts: once the type is removed, Ledger rejects reverting any past transaction that touched those addresses. Use it to retire an entire product line or naming convention, as described in [Evolve the chart without rewriting history](#evolve-the-chart-without-rewriting-history), not to close one customer's account.

## Test the model with real flows

Before you enforce the chart, write down the accounts touched by each critical flow:

| Flow                      | Accounts that should move                              |
| ------------------------- | ------------------------------------------------------ |
| Customer funding          | `world` or treasury account -> customer wallet         |
| Purchase                  | customer wallet -> merchant earnings and platform fees |
| Merchant payout           | merchant earnings -> settlement or `world`             |
| Refund                    | merchant or platform liability -> customer wallet      |
| Reconciliation adjustment | named clearing account -> target account               |

For every flow, verify:

1. the address identifies the owner and purpose without external lookup;
2. the same business entity always produces the same address;
3. a prefix selects the intended group without selecting siblings accidentally;
4. the asset and precision are canonical;
5. every external boundary movement has a reconciliation owner.

## Evolve the chart without rewriting history

Recorded postings retain their original account addresses. If you introduce a new naming convention, old and new addresses will coexist in reads and reports.

Plan an evolution as an application rollout:

1. add the new [account types](https://docs.formance.com/v4.0/modules/ledger/modeling/account-types) in `AUDIT` mode;
2. update writers to emit the new addresses;
3. update readers and reconciliations to cover both conventions;
4. move balances with explicit transactions when the business requires it;
5. keep historical address mappings documented.

Do not rename an address by changing metadata. Metadata does not move its volumes or rewrite its postings.

## Common failure modes

| Symptom                                                   | Likely modeling issue                               | Correction                                                             |
| --------------------------------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------- |
| Reports require many metadata joins to identify a balance | The address is too generic                          | Put stable ownership and purpose in address segments.                  |
| A customer rename requires moving balances                | A mutable label is part of the address              | Use an immutable ID and store the label as metadata.                   |
| Prefix totals include unrelated accounts                  | The prefix ends mid-segment                         | End hierarchical prefixes with `:`.                                    |
| Product code changes whenever a bank account changes      | Treasury details are embedded too deeply            | Use `world` or a stable treasury pool boundary when appropriate.       |
| Old refunds or reverts fail after enforcement             | New account types do not cover historical addresses | Keep compatible types until historical operations no longer need them. |

Next, define the [assets, amounts, balances, and volumes](https://docs.formance.com/v4.0/modules/ledger/modeling/assets-amounts-and-balances) carried by these accounts.
