> For the complete documentation index, see [llms.txt](https://docs-unified.crypto-chief.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-unified.crypto-chief.com/guides/deposit-reconciliation.md). Agents can also search and read this documentation through its [MCP server](https://docs-unified.crypto-chief.com/~gitbook/mcp).

# Deposit Reconciliation with EventStream

## Deposit Reconciliation with EventStream

A new EventStream subscription sees blocks from the moment it starts. Deposits made before that are history. This guide feeds one ledger from both — history from the Unified API, then the live stream — with no gap at the boundary, no deposit credited twice, and every reorganization reversing exactly the credit it affects.

It works because both sides name a transfer the same way: the Unified API `id` of a transfer or event is the EventStream `occurrence_id` of the same on-chain movement, on every network and whatever the data source. A transfer read twice — once from history, once from the stream — is one key in your ledger.

### The plan

1. Create the subscription and start buffering its deliveries.
2. Read, per network, the first block the subscription evaluates.
3. Wait until the history up to that block, plus an overlap, has reached your crediting stage.
4. Read that history with the subscription's own `selection`.
5. Apply history, then the buffer, then live deliveries, through one function keyed by `(network, id)`.

### 1. Subscribe and buffer

Create the subscription as usual ([EventStream: Your First Stream](https://crypto-chief.gitbook.io/chief-event-stream/guides/first-stream)). Select the stage you credit on and `reorged`:

| Family                  | `stages`                   | `confirmations`                                |
| ----------------------- | -------------------------- | ---------------------------------------------- |
| EVM, UTXO               | `["final", "reorged"]`     | Network default, or higher                     |
| TRON                    | `["confirmed", "reorged"]` | Your depth, for example `{"TRON_MAINNET": 19}` |
| Solana, TON, XRP Ledger | `["final", "reorged"]`     | Network default                                |

```json
{
  "name": "USDT deposits",
  "selection": {
    "networks": ["TRON_MAINNET"],
    "types": ["transfer.token"],
    "watchlists": [{ "watchlist_id": "019a0000-0000-7000-8000-000000000010", "version": 1, "follow_updates": true }],
    "directions": ["in"],
    "assets": [{ "network": "TRON_MAINNET", "kind": "token", "id": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" }],
    "minimum_raw": "1000000",
    "include_zero": false
  },
  "stages": ["confirmed", "reorged"],
  "confirmations": { "TRON_MAINNET": 19 },
  "sink_ids": ["019a0000-0000-7000-8000-000000000001"]
}
```

From the first delivery on, store every envelope you receive — verified, deduplicated by `event_id`, answered with `2xx` — but do not credit yet.

### 2. Find where the stream starts

`subscriptions/get` returns `activation[]` per network. Once a network is `active`, its `from_height` is the first block the subscription evaluates:

```json
"activation": [
  { "network": "TRON_MAINNET", "state": "active", "from_height": "77120251", "until_height": null }
]
```

Everything from `from_height` up arrives through the stream. Everything below it is history.

### 3. Wait for the boundary to settle

Read history a little past the boundary: `to_block = from_height + overlap`, for example an overlap of 100 blocks. The overlap protects you from an off-by-one in your own boundary handling; it cannot double-credit, because the overlapping transfers have the same ids on both sides.

History read with `min_stage` returns only what has reached that stage. So wait until block `to_block − 1` has reached your crediting stage before reading:

* **Networks with `final`**: until [`GET /v1/blocks/{network}/finalized`](https://docs-unified.crypto-chief.com/api-reference/blocks.md) returns a `height` of at least `to_block − 1`.
* **TRON**: until [`GET /v1/blocks/TRON_MAINNET/latest`](https://docs-unified.crypto-chief.com/api-reference/blocks.md) returns a `height` with `height − (to_block − 1) + 1 ≥ 19` — your depth.

### 4. Read the history

[`POST /v1/events/search`](https://docs-unified.crypto-chief.com/api-reference/events.md) takes the subscription's `selection` and returns the events that subscription would have delivered — with the same `id`, `block`, `stage` and `payload`. Two changes before you send it: replace `watchlists` with the watchlist's addresses in `addresses` (the search does not read watchlists), and narrow the selection to one network, because a block range takes one network — its `addresses` and its `assets`.

```json
{
  "selection": {
    "networks": ["TRON_MAINNET"],
    "types": ["transfer.token"],
    "addresses": [{ "network": "TRON_MAINNET", "address": "TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL" }],
    "directions": ["in"],
    "assets": [{ "network": "TRON_MAINNET", "kind": "token", "id": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" }],
    "minimum_raw": "1000000",
    "include_zero": false
  },
  "range": { "from_block": "70000000", "to_block": "77120351" },
  "min_stage": "confirmed",
  "order": "asc",
  "limit": 1000
}
```

`from_block` is where your earlier records end — the block an address was handed out, or the network's `history_from`. A range below the network's history is `422 HISTORY_OUT_OF_COVERAGE` with the first available block in `details.history_from`.

For one address with a payment reference — an XRP Ledger destination tag or a TON comment — [`GET /v1/addresses/{address}/transfers`](https://docs-unified.crypto-chief.com/api-reference/address-history.md#transfers) with `destination_tag` or `memo` does the same per address.

### 5. One function for both sources

History events and stream envelopes carry the same fields under the same names, except the id: `id` in the Unified API, `occurrence_id` in EventStream.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
// Keep both in your database, updated in the same transaction as the credit.
const ledger = new Map();     // "network:id" -> { blockHash, credited }
const seenEvents = new Set(); // EventStream event_id, against redeliveries

const creditStage = (network) => (network.startsWith("TRON_") ? "confirmed" : "final");

function apply({ network, id, stage, block, payload }) {
  const key = `${network}:${id}`;
  const entry = ledger.get(key);

  if (stage === "reorged") {
    // A reversal of the credit made in this block — not a duplicate.
    if (entry?.credited && entry.blockHash === block.hash) {
      reverseCredit(network, id, payload);
      entry.credited = false;
    }
    return;
  }
  if (stage !== creditStage(network)) return;
  if (payload.direction !== "in") return;
  if (entry?.credited) return; // the overlap, or the same transfer from the other source

  credit(network, id, payload); // payload.asset, payload.amount.raw, payload.to, payload.source
  ledger.set(key, { blockHash: block.hash, credited: true });
}

// History: every page of POST /v1/events/search for one network.
async function backfill(selection, network, fromBlock, toBlock) {
  let cursor = null;
  do {
    const { http, data } = await api("POST", "/events/search", {}, {
      selection,
      range: { from_block: fromBlock, to_block: toBlock },
      min_stage: creditStage(network),
      order: "asc",
      limit: 1000,
      cursor,
    });
    if (http === 409 && data.error === "SNAPSHOT_REORGED") {
      // Blocks above safe_height changed while paging: read them again.
      return backfill(selection, network, data.details.safe_height, toBlock);
    }
    if (http !== 200) throw new Error(`${http} ${data.error}: ${data.message}`);
    for (const n of data.networks ?? []) {
      if (n.status !== "ok") throw new Error(`${n.network}: ${n.error}, retry in ${n.retry_after}s`);
    }
    for (const e of data.items) apply(e);
    cursor = data.next_cursor;
  } while (cursor);
}

// Stream: every envelope, buffered first, then live.
function onDelivery(envelope) {
  if (seenEvents.has(envelope.event_id)) return;
  seenEvents.add(envelope.event_id);
  apply({
    network: envelope.network,
    id: envelope.occurrence_id,
    stage: envelope.stage,
    block: envelope.block,
    payload: envelope.payload,
  });
}

await backfill(tronSelection, "TRON_MAINNET", "70000000", "77120351");
for (const envelope of buffered.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence)))) {
  onDelivery(envelope);
}
// From here on, call onDelivery() for each incoming webhook.
```

{% endtab %}

{% tab title="Python" %}

```python
ledger = {}          # (network, id) -> {"block_hash": ..., "credited": bool}; keep it in your database
seen_events = set()  # EventStream event_id, against redeliveries

def credit_stage(network):
    return "confirmed" if network.startswith("TRON_") else "final"

def apply(network, id, stage, block, payload):
    entry = ledger.get((network, id))
    if stage == "reorged":
        # A reversal of the credit made in this block — not a duplicate.
        if entry and entry["credited"] and entry["block_hash"] == block["hash"]:
            reverse_credit(network, id, payload)
            entry["credited"] = False
        return
    if stage != credit_stage(network) or payload["direction"] != "in":
        return
    if entry and entry["credited"]:
        return  # the overlap, or the same transfer from the other source
    credit(network, id, payload)  # payload["asset"], payload["amount"]["raw"], payload["to"], payload["source"]
    ledger[(network, id)] = {"block_hash": block["hash"], "credited": True}

def backfill(selection, network, from_block, to_block):
    cursor = None
    while True:
        status, data, _ = api("POST", "/events/search", body={
            "selection": selection,
            "range": {"from_block": from_block, "to_block": to_block},
            "min_stage": credit_stage(network),
            "order": "asc",
            "limit": 1000,
            "cursor": cursor,
        })
        if status == 409 and data.get("error") == "SNAPSHOT_REORGED":
            return backfill(selection, network, data["details"]["safe_height"], to_block)
        if status != 200:
            raise RuntimeError(f"{status} {data.get('error')}: {data.get('message')}")
        for n in data.get("networks", []):
            if n["status"] != "ok":
                raise RuntimeError(f"{n['network']}: {n.get('error')}, retry in {n.get('retry_after')}s")
        for e in data["items"]:
            apply(e["network"], e["id"], e["stage"], e["block"], e["payload"])
        cursor = data["next_cursor"]
        if not cursor:
            return

def on_delivery(envelope):
    if envelope["event_id"] in seen_events:
        return
    seen_events.add(envelope["event_id"])
    apply(envelope["network"], envelope["occurrence_id"], envelope["stage"], envelope["block"], envelope["payload"])

backfill(tron_selection, "TRON_MAINNET", "70000000", "77120351")
for envelope in sorted(buffered, key=lambda e: int(e["sequence"])):
    on_delivery(envelope)
# From here on, call on_delivery() for each incoming webhook.
```

{% endtab %}
{% endtabs %}

What the function guarantees:

* **No double credit.** A transfer in the overlap arrives from both sides with the same `(network, id)`; the second is skipped. A redelivered webhook has the same `event_id`; it is skipped before that.
* **No gap.** History covers everything below `to_block`; the stream covers everything from `from_height`, and `from_height < to_block`.
* **Reorganizations reverse.** `reorged` names the block that was removed. It reverses the credit made in that block, and only that one. If the transaction comes back on the new branch, it arrives again at your crediting stage with a new `block.hash` and is credited again.

### Rules by family

#### EVM and TRON

A token transfer is a log. If the transaction returns in a new block with a different log index, the transfer gets a **new id**: the old id is reversed by `reorged`, the new one credited. Nothing to do beyond the function above.

On TRON there is no `final`; credit at `confirmed` with your own depth, the same depth in the subscription and in your wait (step 3).

#### XRP Ledger

* `payload.amount` is the amount **delivered**, not the amount sent. A partial payment credits what arrived.
* The customer is identified by `payload.source.destination_tag`. History by tag: `GET /v1/addresses/{address}/transfers?networks=XRP_MAINNET&destination_tag=104233`. An X-address given to a customer is the classic address plus that tag ([Addresses](https://docs-unified.crypto-chief.com/api-reference/addresses.md)).
* An account with `requires_memo: true` in its [state](https://docs-unified.crypto-chief.com/api-reference/addresses.md#state) rejects payments without a tag.

#### TON

* A transfer is the incoming message **executed** on the recipient's transaction. A bounced message is not a transfer: nothing arrives, nothing to credit.
* The customer's comment is `payload.source.memo`. History by comment: `GET /v1/addresses/{address}/transfers?networks=TON_MAINNET&memo=order-5521`.
* A Jetton deposit is `transfer.token` with `asset.id` the Jetton master and `from`/`to` the wallet owners, not the Jetton wallets.

#### UTXO networks

* **One transfer per output.** `payload.utxo.output_index` is the output, `source.path` is `vout/<n>`, and the `id` differs per output.
* Two outputs to your addresses in one transaction are two deposits. Never key a credit on the transaction hash.
* Credit at `final`; for large amounts raise the subscription's `confirmations` and wait for the same depth.

#### Solana

The Unified API reads the Memo program text into `source.memo`. EventStream payloads may carry `source.memo: null` on Solana ([EventStream payloads](https://crypto-chief.gitbook.io/chief-event-stream/webhooks/event-payloads)), so identify Solana deposits by the receiving address, not by memo.

### Checklist

* The ledger key is `(network, id)`; the stored `block.hash` decides which credit a `reorged` reverses.
* Stream deliveries are deduplicated by `event_id` before they reach the ledger.
* History is read only after `to_block − 1` has reached the crediting stage.
* `409 SNAPSHOT_REORGED` restarts the history read from `details.safe_height`.
* A network with `status: "error"` in `networks[]` is read again; its absence is not an empty result.
