# Create Transactions with Postings

Source: https://docs.formance.com/v4.0/modules/ledger/transactions/create-with-postings

Stack: v4.0

Use explicit postings when your application has already decided every source, destination, asset, and amount. Ledger commits the postings as one transaction or rejects the request without applying a partial transaction.

Use [Numscript](https://docs.formance.com/v4.0/modules/ledger/transactions/numscript) instead when the result depends on balances, fallback accounts, or percentage splits that Ledger should resolve at execution time.

## Prerequisites

You need:

- an existing ledger in normal mode;
- a token with `ledger:write` for the transaction and `ledger:read` for the account checks;
- the base URL of the Ledger HTTP service, without a trailing slash;
- amounts converted to integer minor units.

These HTTP write examples assume that the cluster accepts unsigned requests. If your cluster requires Ed25519 request signatures, follow [Configure Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing) and use a signed gRPC client or `ledgerctl` configured with a signing key; the HTTP write handlers submit unsigned requests.

If the ledger enforces account types, replace the demo addresses with values that match its configured patterns.

The examples use these environment variables:

```bash
set -eo pipefail

export LEDGER_URL="https://ledger.example.com"
export LEDGER_NAME="main"
export LEDGER_TOKEN="replace-with-an-access-token"
export RUN_ID=${RUN_ID:-"$(date +%s)$$"}

export CLEARING_ACCOUNT="payments:clearing:$RUN_ID"
export MERCHANT_ACCOUNT="merchants:merchant:$RUN_ID"
export FEE_ACCOUNT="platform:fees:$RUN_ID"
export PAYMENT_REFERENCE="postings-payment:$RUN_ID"
```

Amounts are integers

Ledger stores amounts as integers. The `/2` precision in `USD/2` means that `10000` represents USD 100.00. Do not send a floating-point amount.

## Create a multi-posting transaction

This transaction receives USD 100.00 into a clearing account, sends USD 97.00 to a merchant, and records a USD 3.00 fee. The clearing account ends at zero.

```bash
HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/ledger-transaction.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $PAYMENT_REFERENCE:create" \
  --data @- <<JSON
{
  "reference": "$PAYMENT_REFERENCE",
  "metadata": {
    "kind": "card_payment",
    "order_id": "$RUN_ID"
  },
  "postings": [
    {
      "source": "world",
      "destination": "$CLEARING_ACCOUNT",
      "amount": 10000,
      "asset": "USD/2"
    },
    {
      "source": "$CLEARING_ACCOUNT",
      "destination": "$MERCHANT_ACCOUNT",
      "amount": 9700,
      "asset": "USD/2"
    },
    {
      "source": "$CLEARING_ACCOUNT",
      "destination": "$FEE_ACCOUNT",
      "amount": 300,
      "asset": "USD/2"
    }
  ]
}
JSON
)

test "$HTTP_STATUS" = "201"
```

The response contains the generated transaction ID, the three postings, and the post-commit volumes captured at this transaction's sequence. Ledger always returns them; no request field switches them on or off.

Inspect the fields that matter to this operation:

```bash
jq --arg clearing "$CLEARING_ACCOUNT" '{
  postingCount: (.data.transaction.postings | length),
  clearingVolumes: .data.transaction.postCommitVolumes[$clearing]
}' /tmp/ledger-transaction.json
```

Expected result:

```json
{
  "postingCount": 3,
  "clearingVolumes": [
    {
      "asset": "USD/2",
      "color": "",
      "input": "10000",
      "output": "10000"
    }
  ]
}
```

Ledger also returns a generated transaction ID in `.data.transaction.id`. Post-commit volume amounts are strings because they can exceed the safe integer range of JavaScript.

## Verify the balances independently

Read each account instead of relying only on the write response:

```bash
curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$CLEARING_ACCOUNT" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      .data.volumes[]
      | select(.asset == "USD/2" and .color == "")
      | .volumes.input == "10000"
        and .volumes.output == "10000"
        and .volumes.balance == "0"' &&

curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$MERCHANT_ACCOUNT" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      .data.volumes[]
      | select(.asset == "USD/2" and .color == "")
      | .volumes.input == "9700"
        and .volumes.output == "0"
        and .volumes.balance == "9700"' &&

curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$FEE_ACCOUNT" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      .data.volumes[]
      | select(.asset == "USD/2" and .color == "")
      | .volumes.input == "300"
        and .volumes.output == "0"
        and .volumes.balance == "300"'
```

Each assertion prints `true` and exits successfully. The clearing account returns to zero, while the merchant and fee accounts receive `9700` and `300` minor units respectively.

## Control the transaction record

The request accepts exactly one content source: `postings`, `script`, or `scriptReference`. Do not combine them.

| Field             | Use it for                                                | Boundary                                                                                                                                                                                                                                                                                                   |
| ----------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `reference`       | A stable business identifier                              | Unique within one ledger. A duplicate returns a conflict.                                                                                                                                                                                                                                                  |
| `timestamp`       | The business-effective time                               | RFC 3339. If omitted, Ledger uses the current time. `insertedAt` still records when Ledger accepted the write.                                                                                                                                                                                             |
| `metadata`        | Data attached to the transaction                          | Use strings, booleans, or JSON integers in the interoperable safe range. `null` omits the key rather than storing a null value; use the metadata delete endpoints to remove a key that is already stored. Fractional numbers are rejected, and large identifiers that must remain exact should be strings. |
| `accountMetadata` | Metadata updates for accounts involved in the transaction | Keys are account addresses; apply only changes required by the same operation.                                                                                                                                                                                                                             |
| `color`           | A segregation key on a posting                            | Optional; `A-Z` only, at most 32 characters. Omitted means the uncolored bucket.                                                                                                                                                                                                                           |
| `force`           | Bypass the normal balance floor                           | Optional boolean. It can create negative source balances; keep it `false` for normal writes.                                                                                                                                                                                                               |

The HTTP and gRPC create surfaces, and `ledgerctl transactions create --force`, support forced writes. `force: true` bypasses balance checks and can create negative balances. Reserve it for a controlled correction or import, record the approval context in metadata, and verify every affected account afterward.

## Handle errors

| Result        | Meaning                                                                                         | Action                                                                                                                                                  |
| ------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`         | Invalid body, more than one content source, malformed posting, or a business validation failure | Read `errorCode`, correct the request, and use a new idempotency key if the logical operation changes.                                                  |
| `401` / `403` | Missing credentials or insufficient scope                                                       | Refresh the token or grant `ledger:write`. Do not retry unchanged credentials.                                                                          |
| `404`         | The ledger does not exist                                                                       | Check `LEDGER_NAME` and the target environment.                                                                                                         |
| `409`         | The reference is already claimed or the idempotency key conflicts                               | Determine whether the existing transaction is the intended result before creating another operation.                                                    |
| `503`         | Ledger cannot currently accept the write, or concurrent state invalidated proposal inputs       | Honor `Retry-After` when present; otherwise use bounded exponential backoff. Retry with the same key and identical body while the outcome is uncertain. |

## Retry or correct the operation

Keep the same `Idempotency-Key` and the same request body when a timeout or `503` leaves the outcome uncertain. Ledger returns the original outcome instead of creating a second transaction while the key remains in its retention window.

A definitive balance or account-rule rejection that Ledger recorded as the operation's outcome is also retained with its key. If you fund an account, change `force`, or otherwise correct the logical operation, send the corrected content with a new idempotency key. The HTTP status alone does not prove whether a rejection was retained; see [Retry Writes Safely](https://docs.formance.com/v4.0/modules/ledger/transactions/idempotency-and-references) for the boundary.

A committed transaction is immutable. Do not attempt to delete or edit its postings. Use [Revert Transactions](https://docs.formance.com/v4.0/modules/ledger/transactions/revert) to record a compensating movement, or create a separate correcting transaction when a full reversal does not match the business event.

Continue with [Retry Writes Safely](https://docs.formance.com/v4.0/modules/ledger/transactions/idempotency-and-references) before adding this call to a production client.
