# Track Fund Origin with Colors

Source: https://docs.formance.com/v4.0/modules/ledger/modeling/color-of-money

Stack: v4.0

A color adds an origin or restriction to a posting. Ledger then keeps a separate balance for each `(account, asset, color)` instead of grouping everything by account and asset.

Use colors when funds with the same asset must not satisfy each other's spending rules. Examples include restricted grants, promotional balances, reserved funds, or funds tied to a specific source program.

Do not use colors as display labels. Use [metadata](https://docs.formance.com/v4.0/modules/ledger/modeling/metadata) when values may be grouped together for spending and only need descriptive context.

To create colored balances and watch isolation enforced against a live ledger, follow [Colors](https://docs.formance.com/v4.0/modules/ledger/hands-on#colors-isolated-balances-within-one-asset) in the hands-on walkthrough.

Read [Create Transactions with Postings](https://docs.formance.com/v4.0/modules/ledger/transactions/create-with-postings) for retry rules and [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data#read-an-account) for the account response contract.

## Balance buckets are isolated

Suppose Alice holds three `USD/2` buckets:

| Color    | Balance | Meaning                |
| -------- | ------: | ---------------------- |
| `""`     |   10000 | Uncolored funds        |
| `GRANTS` |    5000 | Restricted grant funds |
| `OPS`    |    2500 | Operations budget      |

A posting that requests `GRANTS` can spend only the `GRANTS` balance. It cannot fall back to the uncolored or `OPS` buckets, even when their combined balance would cover the amount.

The empty string is a real bucket. Omitting `color` on a posting selects the uncolored bucket; it does not mean “use any color.”

## Write a colored posting

Color follows the value from source to destination. One posting cannot debit `GRANTS` and credit `OPS`; changing color in place would break conservation inside each bucket.

Color identifiers must contain only uppercase ASCII letters (`A` through `Z`) and can contain at most 32 characters. The empty string remains valid for uncolored funds.

## Balances are returned per bucket

Ledger returns one volume row per `(asset, color)`, including `color: ""` for the uncolored bucket:

```json
{
  "data": {
    "address": "customers:alice:wallets:main",
    "volumes": [
      {
        "asset": "USD/2",
        "color": "",
        "volumes": { "input": "10000", "output": "0", "balance": "10000" }
      },
      {
        "asset": "USD/2",
        "color": "GRANTS",
        "volumes": { "input": "5000", "output": "0", "balance": "5000" }
      },
      {
        "asset": "USD/2",
        "color": "OPS",
        "volumes": { "input": "2500", "output": "0", "balance": "2500" }
      }
    ]
  }
}
```

Ledger enforces sufficiency per bucket: spending `5001` from a `GRANTS` bucket holding `5000` is rejected with `INSUFFICIENT_FUNDS`, and the rejection is atomic — neither the source nor the destination account changes. The [hands-on walkthrough](https://docs.formance.com/v4.0/modules/ledger/hands-on#colors-isolated-balances-within-one-asset) runs that probe and asserts both accounts are untouched.

## Use collapsed views only for reporting

Set `collapseColors=true` when a report needs one total per asset; the same option works on aggregate volume queries. Collapsed responses sum the colored rows and return the result with `color: ""`. They do not merge or recolor stored balances. Never use a collapsed balance to authorize a spend that must respect color restrictions.

Treat `collapseColors=true` as a presentation choice. The returned empty color represents a summary across buckets, while an uncollapsed empty color represents the actual uncolored bucket.

## Spend a color with Numscript

Numscript can restrict a source to one color. The current syntax requires the asset-colors feature directive:

```numscript
#![feature("experimental-asset-colors")]

send [USD/2 1000] (
  source = @customers:alice:wallets:main \ "GRANTS"
  destination = @merchants:acme:earnings
)
```

The emitted posting carries `color: "GRANTS"`, and the destination receives the same color. A source without a color restriction reads only the uncolored bucket: `@account \ ""` and `@account` name the same source.

There is no "any color" source. A script that may draw from more than one bucket lists those buckets in an ordered source, and each posting it emits carries the color of the bucket the funds came from.

Ledger keeps each color as a separate balance even though the current Numscript syntax requires an explicit feature directive.

## Reversals keep the original color

Reverting a colored transaction creates reverse postings with the same color. Funds return to the bucket from which they moved; they do not return as uncolored value.

Verify this behavior in tests that read the original source after a reversal. Its matching colored balance should recover, while other colors remain unchanged.

## Change a business classification explicitly

Ledger has no in-place recoloring primitive. Reclassify value with one transaction that contains two equal postings:

1. retire the old color by sending it to `world`;
2. issue the same amount from `world` with the new color.

Keeping both postings in one transaction is mandatory. Ledger commits both or neither, and one idempotency key protects the whole exchange. Crediting the new color in a separate transaction can temporarily double the customer's value if the old-color debit fails or is delayed.

The [hands-on walkthrough](https://docs.formance.com/v4.0/modules/ledger/hands-on#reclassify-value-between-colors) moves `1000 USD/2` from `GRANTS` to `OPS` and asserts both bucket changes plus the invariant total.

Production clients must parse Ledger's balance strings with arbitrary-precision integer arithmetic.

Do not replace `world` with a two-posting clearing hop. `GRANTS` and `OPS` are separate balances, so they cannot cancel each other inside the clearing account. A clearing design needs additional postings that return every `(asset, color)` bucket to zero in the same transaction. Keep the approval reference in transaction metadata so reviewers can explain why the classification changed.

## Current limits

- List-accounts and list-transactions do not expose a native color filter. Read the relevant account or aggregate volumes and filter the returned rows in your application.
- Color is not derived from account or transaction metadata. Every posting that must remain separate must carry the intended color.
- There is no primitive that changes the color of existing funds in place.
- A direct-posting insufficient-funds error identifies the exact color bucket. A Numscript insufficient-funds error cannot yet identify which color was short and omits the color from its error metadata.

When Numscript error metadata has no color field, read it as “color unresolved,” not as “the uncolored bucket failed.” Direct-posting errors can identify the empty uncolored bucket explicitly.

## Common failure modes

| Symptom                                                         | Cause                                                                              | Correction                                                                        |
| --------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| A spend fails although the account total is sufficient          | The requested color bucket is short                                                | Read uncollapsed volumes and fund the intended bucket.                            |
| A posting is rejected as invalid                                | The color contains lowercase letters, digits, separators, or exceeds 32 characters | Use a stable uppercase identifier such as `GRANTS`.                               |
| A recipient gets an unexpected colored balance                  | Color follows the posting to the destination                                       | Include color handling in the destination's spending and reconciliation logic.    |
| A collapsed response appears to lose provenance                 | The response intentionally summed buckets under `color: ""`                        | Remove `collapseColors=true` when provenance matters.                             |
| A Numscript error has no `color` metadata                       | The interpreter cannot resolve the failing bucket in that error path               | Inspect the script source and uncollapsed source balances.                        |
| Reports cannot list every transaction for one color server-side | Native list filtering by color is not available                                    | Filter posting colors client-side or store a separate lookup in your application. |

Before production use, test direct postings, Numscript, reversals, collapsed reads, and insufficient-funds behavior with at least one uncolored and two colored buckets.
