> ## Documentation Index
> Fetch the complete documentation index at: https://sonar-cf3aeac7.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cursors and resuming

> Per-pair cursors on the multi-events stream, resuming with since, checkpoints, RESUME_EXPIRED, gaps and a reconnect recipe.

Every [pair](https://sonar-cf3aeac7.mintlify.site/streams/subscribing.md#pairs) of a subscription (one chain and one event kind) has its own cursor. Store the newest cursor of each pair. When you reconnect, send them back as `since` and the server replays the matching trades you missed, then continues live.

## Cursor format

| Form | Example | Meaning |
| - | - | - |
| Entry cursor | `26745120-0` | A whole block: everything up to and including block 26745120 |
| Item cursor | `26745120-0:3` | One trade inside block 26745120 |

* The number before `-0` is the block number.
* The index after `:` is the trade's position in that block's list of swaps. That list also contains swaps that aren't trades, so indexes can skip numbers.
* `cursor` checkpoints carry entry cursors, and so does `subscribed` for a pair that starts live. For a pair you resume, `subscribed` echoes the cursor you sent, which can be an item cursor. Events carry item cursors.
* Cursors are ordered: by block, then by index. An entry cursor sorts after every item cursor of the same block.

Treat cursors as opaque strings that you store and send back. Don't build them yourself.

The same trade delivered as both `swap` and `swap-enriched` has the **same cursor value under two different pairs**, for example `swap|evm:1` and `swap-enriched|evm:1`. Store cursors per pair, not per trade.

## Where cursors come from

Keep the newest cursor of each pair from any of these messages:

| Message | Field | Pair |
| - | - | - |
| `subscribed` | `cursor` (one pair) or `cursors` (several pairs) | Implied, or the keys of `cursors` |
| `event` | `cursor` | `pair` (left out when the subscription has one pair) |
| `cursor` | `cursor` | `pair` (left out when the subscription has one pair) |

Within a pair, messages arrive in order, so the last cursor you received is the newest.

### Checkpoints

Every 30 seconds, each live pair whose chain has moved on since its last cursor gets a checkpoint:

```json theme={null}
{ "type": "cursor", "id": "big-trades", "pair": "swap|evm:1", "cursor": "26745135-0" }
```

A checkpoint means every block up to and including that one has been processed for your subscription, even if nothing matched your filter. It lets a sparse filter, one that matches only a few trades an hour, resume after a quiet period without falling behind the stream's history. Sampled subscriptions don't get checkpoints.

## Resuming with `since`

Subscribe again with the same `params` and add `since`. You can use a new id or the same one on a new connection.

> [tab] One pair
>
> `since` is a cursor string:
>
> ```json theme={null}
> {
>   "op": "subscribe",
>   "id": "weth-whales",
>   "channel": "multi-events",
>   "params": { "chains": ["evm:1"], "events": ["swap"], "filters": { "gte": ["tokenAmountUsd", 100000] } },
>   "since": "26745135-0"
> }
> ```
>
> Sending a string when the subscription has several pairs fails with `INVALID_PARAMETERS`, message `This subscription has several pairs, since must map each pair to its cursor`, and `details.pairs` listing the pair names.

> [tab] Several pairs
>
> `since` is an object from pair name to cursor, with at least one entry:
>
> ```json theme={null}
> {
>   "op": "subscribe",
>   "id": "big-trades",
>   "channel": "multi-events",
>   "params": {
>     "chains": ["evm:1", "evm:8453"],
>     "events": ["swap"],
>     "filters": { "gte": ["tokenAmountUsd", 100000] }
>   },
>   "since": {
>     "swap|evm:1": "26745135-0",
>     "swap|evm:8453": "55410388-0:12"
>   }
> }
> ```
>
> * Pairs you leave out start live, with no replay.
> * A pair name that the subscription doesn't have fails with `INVALID_PARAMETERS`, message `Unknown pairs in since`, and `details.pairs` listing the unknown names.

What happens next:

1. The server sends `subscribed`. For resumed pairs, the cursor echoes the one you sent.
2. It replays every trade **after** your cursor that matches the filter. With an item cursor, that starts with the rest of the same block; with an entry cursor, with the next block. Gaps in that range are replayed too.
3. It hands over to live delivery, with no duplicates and no reordering.

Always resume from a cursor the server gave you. A cursor ahead of the stream skips everything up to it.

## `RESUME_EXPIRED`

The stream keeps a limited history per chain: **about 10 minutes today**. Don't design for more. The history is kept as a number of blocks, so the exact time varies by chain.

If any `since` cursor is older than that, the **whole subscription is refused**, including pairs whose cursors were still valid:

```json One pair theme={null}
{
  "type": "error",
  "id": "weth-whales",
  "code": "RESUME_EXPIRED",
  "message": "Cursor is older than the stream history",
  "details": { "retainedFrom": "26745300" }
}
```

```json Several pairs theme={null}
{
  "type": "error",
  "id": "big-trades",
  "code": "RESUME_EXPIRED",
  "message": "Cursor is older than the stream history",
  "details": {
    "pairs": {
      "swap|evm:1": { "retainedFrom": "26745300" }
    }
  }
}
```

* `retainedFrom` is a block number as a string: the oldest block the stream still holds for that chain.
* With several pairs, `details.pairs` lists only the expired pairs.

To recover:

1. Subscribe again without the expired pairs in `since` (or without `since` at all). Those pairs start live.
2. If you need the trades you missed, fetch them from [`GET /trades`](https://sonar-cf3aeac7.mintlify.site/api-reference/trades/get-trades) for the tokens or pools you follow.

## Gaps

Blocks are released to the stream strictly in order. If a block's trades are stuck for more than about 15 seconds, the stream skips ahead and records a gap:

```json theme={null}
{
  "type": "gap",
  "id": "big-trades",
  "channel": "multi-events",
  "pair": "swap|evm:8453",
  "fromBlock": 55410390,
  "toBlock": 55410394
}
```

* `fromBlock` to `toBlock` is an **inclusive** block range. Trades in those blocks are not streamed, now or later.
* Every subscriber of that chain gets the gap, **whatever its filter**, including sampled subscriptions. A gap doesn't mean that a trade matching your filter was lost, only that one might have been.
* `pair` follows the same rule as for events: present only with several pairs.
* The gap message has no `cursor`. If you resume from a cursor older than the gap, the gap is sent again during replay.

If you need complete data, backfill the range from REST. [`GET /trades`](https://sonar-cf3aeac7.mintlify.site/api-reference/trades/get-trades) takes a token or pool address and a time window in milliseconds (`from`, `to`), not block numbers. Use the `timestamp` of the last event before the gap and of the first event after it as the window. A token query only covers the token's top two pools, so backfill by pool address when you can.

## Restarts and disconnects

When a server restarts, it sends every client:

```json theme={null}
{ "type": "reconnect" }
```

then closes the connection with code `1012` and reason `Server restarting, reconnect and resume`. Closes are spread over about 20 seconds so clients don't all reconnect at once. Reconnect to the same URL; any server instance can resume your cursors.

Subscriptions don't survive a disconnect. On every new connection, subscribe again with `since`. The same applies to the other closes listed in [Limits and subscription cost](https://sonar-cf3aeac7.mintlify.site/streams/limits-and-cost.md#close-codes), such as `4008` for a client that reads too slowly and `1006` for a missed heartbeat.

## Reconnect recipe

This client keeps one cursor per pair, resumes after any disconnect with exponential backoff, and drops expired pairs on `RESUME_EXPIRED`. Persist `cursors` (to a file or database) if you want to resume after your process restarts too.

```js JavaScript theme={null}
const URL = "wss://api.example.com/streams/v1/ws";
const SUB_ID = "big-trades";
const params = {
  chains: ["evm:1", "evm:8453"],
  events: ["swap"],
  filters: { gte: ["tokenAmountUsd", 100000] },
};
const pairs = params.chains.flatMap((c) => params.events.map((e) => `${e}|${c}`));
const single = pairs.length === 1;
const cursors = {}; // pair -> newest cursor; persist this

function since() {
  const entries = Object.entries(cursors);
  if (entries.length === 0) return undefined;
  return single ? entries[0][1] : Object.fromEntries(entries);
}

function subscribe(ws) {
  ws.send(JSON.stringify({ op: "subscribe", id: SUB_ID, channel: "multi-events", params, since: since() }));
}

let attempt = 0;
function connect() {
  const ws = new WebSocket(URL);
  ws.onopen = () => subscribe(ws);
  ws.onmessage = ({ data }) => {
    const msg = JSON.parse(data);
    const pair = msg.pair ?? pairs[0];
    switch (msg.type) {
      case "subscribed":
        attempt = 0;
        if (msg.cursors) Object.assign(cursors, msg.cursors);
        else if (msg.cursor) cursors[pairs[0]] = msg.cursor;
        break;
      case "event":
        cursors[pair] = msg.cursor;
        handleTrade(msg.data);
        break;
      case "cursor":
        cursors[pair] = msg.cursor;
        break;
      case "gap":
        console.warn(`gap on ${pair}: blocks ${msg.fromBlock}-${msg.toBlock}`);
        break;
      case "error":
        if (msg.code === "RESUME_EXPIRED") {
          const expired = single ? pairs : Object.keys(msg.details.pairs);
          for (const p of expired) delete cursors[p]; // these start live
          subscribe(ws); // the id is free again after an error
        } else {
          console.error(msg.code, msg.message, msg.details);
        }
        break;
    }
  };
  ws.onclose = () => setTimeout(connect, Math.min(30_000, 1000 * 2 ** attempt++));
}

function handleTrade(swap) {
  console.log(swap.chainId, swap.hash, swap.amountUSD);
}

connect();
```

```python Python theme={null}
# pip install websockets
import asyncio, json
import websockets

URL = "wss://api.example.com/streams/v1/ws"
SUB_ID = "big-trades"
PARAMS = {
    "chains": ["evm:1", "evm:8453"],
    "events": ["swap"],
    "filters": {"gte": ["tokenAmountUsd", 100000]},
}
PAIRS = [f"{e}|{c}" for c in PARAMS["chains"] for e in PARAMS["events"]]
SINGLE = len(PAIRS) == 1
cursors = {}  # pair -> newest cursor; persist this

def subscribe_message():
    msg = {"op": "subscribe", "id": SUB_ID, "channel": "multi-events", "params": PARAMS}
    if cursors:
        msg["since"] = next(iter(cursors.values())) if SINGLE else dict(cursors)
    return json.dumps(msg)

def handle_trade(swap):
    print(swap["chainId"], swap["hash"], swap["amountUSD"])

async def run():
    delay = 1
    while True:
        try:
            async with websockets.connect(URL) as ws:
                await ws.send(subscribe_message())
                async for raw in ws:
                    msg = json.loads(raw)
                    pair = msg.get("pair", PAIRS[0])
                    kind = msg["type"]
                    if kind == "subscribed":
                        delay = 1
                        if "cursors" in msg:
                            cursors.update(msg["cursors"])
                        elif "cursor" in msg:
                            cursors[PAIRS[0]] = msg["cursor"]
                    elif kind == "event":
                        cursors[pair] = msg["cursor"]
                        handle_trade(msg["data"])
                    elif kind == "cursor":
                        cursors[pair] = msg["cursor"]
                    elif kind == "gap":
                        print(f"gap on {pair}: blocks {msg['fromBlock']}-{msg['toBlock']}")
                    elif kind == "error":
                        if msg["code"] == "RESUME_EXPIRED":
                            expired = PAIRS if SINGLE else list(msg["details"]["pairs"])
                            for p in expired:
                                cursors.pop(p, None)
                            await ws.send(subscribe_message())
                        else:
                            print("error", msg["code"], msg["message"], msg.get("details"))
        except (websockets.WebSocketException, OSError):
            pass
        await asyncio.sleep(delay)
        delay = min(delay * 2, 30)

asyncio.run(run())
```

If you change `params` between connections, only send `since` for pairs that still exist. A pair you add starts live, and a pair you send that the new params don't produce fails with `Unknown pairs in since`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.