# Revert Transactions

Source: https://docs.formance.com/v4.0/modules/ledger/transactions/revert

Stack: v4.0

A revert creates a new transaction whose postings reverse the original transaction. Ledger keeps the original record, marks it as reverted, and links the two transactions.

Use a revert when the whole accounting effect must be undone. Create a separate correcting transaction when only part of the amount or destination changes.

## Prerequisites

You need an existing normal ledger and a token with `ledger:write` for the create and revert operations plus `ledger:read` for the transaction and account checks. The virtual scopes assume the default scope mapping.

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 wallet with an address that matches its configured patterns.

```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 WALLET_ACCOUNT="wallets:revert-demo:$RUN_ID"
export DEPOSIT_REFERENCE="deposit:revert-demo:$RUN_ID"
export REVERT_CASE_ID="case:$RUN_ID"
```

The example creates a USD 25.00 deposit that can be reverted safely:

```bash
CREATE_RESPONSE=$(curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $DEPOSIT_REFERENCE:create" \
  --data "$(jq --compact-output --null-input \
    --arg reference "$DEPOSIT_REFERENCE" \
    --arg destination "$WALLET_ACCOUNT" \
    '{
      reference: $reference,
      postings: [
        {source: "world", destination: $destination, amount: 2500, asset: "USD/2"}
      ]
    }')")

TRANSACTION_ID=$(jq -er \
  '.data.transaction.id | tostring | select(test("^[1-9][0-9]*$"))' \
  <<<"$CREATE_RESPONSE")
```

## Revert the transaction

Send a new idempotency key for the revert. Metadata belongs to the compensating transaction, not to the original one.

```bash
jq --null-input \
  --arg caseId "$REVERT_CASE_ID" \
  '{
    metadata: {
      reason: "customer_refund",
      case_id: $caseId
    }
  }' \
  | curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$TRANSACTION_ID/revert" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $DEPOSIT_REFERENCE:revert" \
  --data @- \
  > /tmp/reverted-transaction.json
```

Ledger returns `201 Created`. Inspect the relationship and the new postings:

```bash
jq '.data | {
  revertedTransactionId,
  revertTransaction: {
    id: .revertTransaction.id,
    revertsTransactionId: .revertTransaction.revertsTransactionId,
    timestamp: .revertTransaction.timestamp,
    metadata: .revertTransaction.metadata,
    postings: .revertTransaction.postings,
    postCommitVolumes: .revertTransaction.postCommitVolumes
  }
}' /tmp/reverted-transaction.json
```

Expected result:

- `revertedTransactionId` equals the original transaction ID;
- `revertTransaction.revertsTransactionId` also points to the original;
- the new posting sends `2500` units of `USD/2` from `$WALLET_ACCOUNT` to `world`;
- the new transaction contains the refund metadata;
- the wallet returns to a zero balance.

## Verify both records

Read the original transaction:

```bash
curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$TRANSACTION_ID" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e --arg id "$TRANSACTION_ID" '
      .data.transaction
      | select(
          (.id | tostring) == $id
          and .reverted == true
          and (.revertedByTransactionId | tostring | test("^[1-9][0-9]*$"))
        )
      | {id, reverted, revertedAt, revertedByTransactionId}'
```

`reverted` must be `true`, and `revertedByTransactionId` must identify the compensating transaction.

Then verify the balance independently:

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

Expected volume:

```json
{
  "input": "2500",
  "output": "2500",
  "balance": "0"
}
```

## Choose the effective timestamp

By default, the compensating transaction uses the time of the revert. Set `atEffectiveDate` when reports must place the compensation at the original transaction's effective timestamp:

```json
{
  "atEffectiveDate": true,
  "metadata": {
    "reason": "effective_date_correction"
  }
}
```

`insertedAt` still shows when Ledger recorded the revert. Review historical reports and date-based reconciliation rules before choosing the original effective date.

## Revert when funds have moved

A normal revert fails when reversing the postings would take an account below its allowed balance. Investigate where the funds moved first. A separate correction may represent the business event more accurately.

If policy requires a full reversal despite the resulting negative balance, the REST request accepts `force: true`:

```json
{
  "force": true,
  "metadata": {
    "reason": "operator_approved_forced_revert",
    "case_id": "case-0045"
  }
}
```

A forced revert bypasses the normal balance check. It can create negative balances in accounts that spent the original funds. Require explicit approval, capture the case ID in metadata, and verify every account in the returned `revertTransaction.postCommitVolumes`.

## Handle errors

| Result                                    | Meaning                                                               | Action                                                                                                                                                                                             |
| ----------------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`                                     | Invalid body or the reversal violates a balance or account rule       | Inspect the structured reason. Correct the request or follow the approved forced-revert procedure.                                                                                                 |
| `401` / `403`                             | Missing credentials or insufficient scope                             | Repair authentication or grant `ledger:write`.                                                                                                                                                     |
| `404`                                     | The ledger or original transaction cannot be found                    | Check the environment and ID.                                                                                                                                                                      |
| `409` with `IDEMPOTENCY_KEY_CONFLICT`     | The key was already used with different content                       | Restore the exact original body for an unchanged retry. If the original operation record is unavailable, stop; reading the target transaction does not identify the outcome stored under that key. |
| `409` with `TRANSACTION_ALREADY_REVERTED` | A compensating transaction already exists                             | Read the original and verify `revertedByTransactionId`. Do not issue another correction automatically.                                                                                             |
| `503`                                     | Ledger cannot currently accept the revert; the outcome may be unknown | Retry the identical request with the same idempotency key, over HTTP or direct gRPC.                                                                                                               |

## Recover after a timeout or lost response

Read the original after the cluster is healthy enough to serve a fresh read:

```bash
ORIGINAL=$(curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$TRANSACTION_ID" \
  --header "Authorization: Bearer $LEDGER_TOKEN")

jq -e --arg id "$TRANSACTION_ID" '
  .data.transaction
  | select((.id | tostring) == $id)
  | {id, reverted, revertedAt, revertedByTransactionId}' \
  <<<"$ORIGINAL"
```

If `reverted` is `true`, the revert committed. Read the compensating transaction identified by `revertedByTransactionId`; do not send another revert:

```bash
(
REVERT_TRANSACTION_ID=$(jq -er \
  '.data.transaction.revertedByTransactionId // 0 | tostring' \
  <<<"$ORIGINAL")

if [[ -z "$REVERT_TRANSACTION_ID" || "$REVERT_TRANSACTION_ID" == "0" ]]; then
  echo "No compensating transaction is linked; do not retry yet." >&2
  exit 1
fi

curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions/$REVERT_TRANSACTION_ID" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e --arg original "$TRANSACTION_ID" '
      .data.transaction
      | select((.revertsTransactionId | tostring) == $original)
      | {id, revertsTransactionId, postings, metadata}'
)
```

Then read every account affected by the original postings. For the example on this page:

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

Use these outcomes to decide what happens next:

- If the original is reverted, the compensating transaction points back to it, and balances match the reversal, record success and stop.
- If the original is not reverted, wait for the cluster to recover, read it and the affected balances again, then make an explicit retry decision.
- If the transaction link or balances are inconsistent, or a fresh read is unavailable, stop the workflow and investigate. A new revert or correction would make the accounting state harder to reconcile.

For the HTTP example earlier on this page, keep the same `Idempotency-Key` and body after a timeout or `503`. For direct gRPC automation, keep the same `ApplyBatch.idempotency_key` and batch. Never replace the key while the first outcome is unknown.

## Correct a completed revert

A revert is itself an immutable transaction. Ledger does not delete it or restore the original transaction to an unreverted state. If a revert was incorrect, model the required business correction as a new reviewed transaction and preserve the complete audit trail.

Continue with [Process Operations in Bulk](https://docs.formance.com/v4.0/modules/ledger/transactions/bulk) when several independent corrections are submitted together.
