<!-- source: https://www.secondlayer.tools/docs/checkpoints -->

# Checkpoints

Commit your rows and the cursor together, and a crash resumes where it stopped.

## The Loop

Name the event, commit rows and the checkpoint together, and delete from the fork height when a reorg lands.

```ts consumer.ts
import { Index } from "@secondlayer/sdk";

const index = new Index();
await index.events.consume({
  eventType: "ft_transfer",
  fromCursor: await db.loadCheckpoint(),
  fromHeight: 0,
  onBatch: async (events, ctx) => {
    await db.transaction(async (tx) => {
      for (const row of events) await tx.upsert(row);
      await tx.saveCheckpoint(ctx.cursor);
    });
    return ctx.cursor;
  },
  onReorg: (reorg) => db.deleteFromHeight(reorg.fork_point_height),
});
```

- `fromCursor` is `null` on the first run, and `fromHeight: 0` backfills as far as your instance holds. Older history is restored from the archive, free.
- A reorg rewinds the cursor to the fork point and fires `onReorg`. Delete inclusive of the fork block: [Reorgs](https://www.secondlayer.tools/docs/reorgs.md).
- Fold running balances in a sink's `onRollback`: [Sinks](https://www.secondlayer.tools/docs/sinks.md#rollback-is-height-stamped).
- Where to run it: [Deploy](https://www.secondlayer.tools/docs/deploy.md).

## Options

`consume` is on `sl.streams.events`, `sl.index.events` and `sl.index.contractCalls`. Every signature is in the [SDK reference](https://www.secondlayer.tools/docs/sdk.md).

| Option | Effect |
| --- | --- |
| `eventType` | A literal narrows the rows: `"ft_transfer"` hands `onBatch` typed `amount` and `sender`, `"print"` hands it `payload.topic` |
| `contractId` | One id, or up to 20 to follow a protocol on one cursor. Mutually exclusive with `trait` |
| `txContext: true` | Joins the submitting transaction into each event (`tx_sender`, `tx_type`, ...). Same on `walk` and `list` |
| `finalizedOnly: true` | Holds delivery to rows at or below `tip.finalized_height`, so `onReorg` is unnecessary |
| `signal` | Abort, checked between batches and never mid-commit; see [Deploy](https://www.secondlayer.tools/docs/deploy.md#handle-sigterm) |
| `index.contractCalls.consume()` | The same loop for decoded calls. Already carries `sender` and `function_name`, so it needs no `txContext` |

`finalizedOnly` trades freshness for safety, and can put you hundreds of blocks behind the tip.

## Progress

`ctx` says where the sweep has reached, so liveness needs no bookkeeping of its own.

| Field | Is |
| --- | --- |
| `cursor` | The checkpoint to commit with your rows |
| `height` | Highest canonical block a row was delivered from; parks on a quiet filter |
| `scannedHeight` | Highest block verified; an empty page proves nothing matches up to the tip. Rolled back on a reorg |
| `tipHeight` | Chain tip as of this page's read |
| `blocksBehind` | `tipHeight - scannedHeight`, floored at `0`; about `0` for a caught-up tail even when `height` is old |

## Which Verb

Every feed offers three verbs. They are not interchangeable.

```ts
const { rows, next_cursor } = await sl.index.blocks.list({ limit: 10 });
for await (const t of sl.index.ftTransfers.walk({ contractId })) {}
await sl.index.events.consume({ eventType: "ft_transfer", onBatch });
```

| Verb | Gives you | Follows cursors | Checkpoints | Reorgs | Ends |
| --- | --- | --- | --- | --- | --- |
| `list()` | One page plus the envelope | No; you pass `cursor` back | No | Reports `reorgs[]`; you act | Immediately |
| `walk()` | An async iterable of rows | Yes | No | Ignored | On catching the tip |
| `consume()` | A loop calling your `onBatch` | Yes | Yes; you commit the cursor | Rewinds and fires `onReorg` | Never; tails until aborted |

`walk()` into a database is a trap: a crash restarts from zero, a fork leaves orphaned rows behind, and it stops at the tip. Writing rows you intend to keep is `consume()`.

## Read next

- [Reorgs](https://www.secondlayer.tools/docs/reorgs.md)
- [Sinks](https://www.secondlayer.tools/docs/sinks.md)
- [Deploy a Consumer](https://www.secondlayer.tools/docs/deploy.md)
- [SDK](https://www.secondlayer.tools/docs/sdk.md)

## Notes for agents

- Commit rows and the cursor in one transaction, then return ctx.cursor from onBatch. Resume with fromCursor; null on the first run.
- onReorg: delete from fork_point_height inclusive. Delivery is at least once, so keep writes idempotent.
- walk() never checkpoints or handles reorgs; use consume() for anything you keep.

## Setup

Ensure setup once, skipping any step already done:
- CLI: `bun add -g @secondlayer/cli`
- Instance: `secondlayer init` writes `INSTANCE_TOKEN`. Loopback `/v1` reads need no key.
- Hosted reads: export `SECONDLAYER_API_KEY` (`sk-sl_*`) or buy credits with `secondlayer credits buy` (`balance`, `refill`), then `secondlayer whoami`
