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

# Filters

Describe a chain event once, then read it from Index, Streams, Webhooks or Subgraphs in the shape each expects. Every export and its types: [SDK reference](https://www.secondlayer.tools/docs/sdk.md#filters-package).

```ts filters.ts
import { on } from "@secondlayer/stacks/filters";

const sbtcMints = on.ftMint({
  assetIdentifier: "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token::sbtc-token",
  minAmount: 100_000n,
});

await sl.index.events.list(sbtcMints.toIndexParams({ limit: 50 }));
await sl.streams.events.list(sbtcMints.toStreamsParams());
await sl.webhooks.create({ name: "sbtc-mints", url, triggers: [sbtcMints.toChainTrigger()] });
```

## One Filter, Four Shapes

The surfaces disagree, and a spread hides it. Each projection converts explicitly:

| Difference | Where |
| --- | --- |
| Print event is `print` on Index, `print_event` on Subgraphs | Index, Subgraphs |
| `contract_call` and `contract_deploy` live on a different Index endpoint than events | Index |
| Amounts are strings: a `bigint` in a `JSON.stringify` body throws, so `toChainTrigger()` turns `100_000n` into `"100000"` | Webhooks |
| `trait` scoping exists | Index, Subgraphs, not Streams |

### Unsupported Members

A filter type a surface doesn't support lacks that method, so the error names the problem. Field gating comes second: `trait` is absent from `toStreamsParams()`, and wildcards are Webhooks and Subgraphs only.

```ts
on.sbtcDeposit({}).toChainTrigger();   // ok: trigger-only event
on.sbtcDeposit({}).toIndexParams();
```

### Principals

A contract id where an asset identifier belongs is the most common copy-paste mistake, and it used to return zero rows. The factory now throws at construction, naming the field, though the fields are still typed `string`.

```ts
on.ftTransfer({ assetIdentifier: "SP…token" });
on.ftTransfer({ assetIdentifier: "SP…token::token" }); // ok
```

### Subgraph Sources

`toSubgraphSource()` and `fromSubgraphSource()` round-trip a source, and the `abi` literal survives, so `event.input` stays typed in a handler.

```ts
import { fromSubgraphSource } from "@secondlayer/stacks/filters";

const source = fromSubgraphSource(subgraph.sources.swaps);
const same = source.toSubgraphSource();
```

## Query Params

Subgraph tables filter on any column, validated against the table's schema. Index and Streams take a fixed set per endpoint; the [Streams filter table](https://www.secondlayer.tools/docs/streams.md#read-it-directly) lists the ones on `/v1/streams/events`.

```bash
curl "$SECONDLAYER_API_URL/v1/subgraphs/sbtc-flows/transfers" \
  -H "Authorization: Bearer $SECONDLAYER_API_KEY" \
  -G \
  -d "sender=SP3PE7Q9...X44J" \
  -d "_order=desc"
```

An unrecognized param is a `400`, and the error suggests the closest valid one. Paging params: [Cursors and Pages](https://www.secondlayer.tools/docs/cursors.md#page-through-it).

### Several Concerns, One Cursor

On Streams, `filters` names each concern and the server ORs them into one scan, so tracking sBTC mints and treasury spends takes one loop, one cursor and one checkpoint.

```ts
await sl.streams.events.consume({
  filters: {
    peg: { types: ["ft_transfer"], assetIdentifier: `${SBTC}::sbtc-token` },
    treasury: { types: ["stx_transfer"], sender: TREASURY },
  },
  on: {
    peg: (events) => events.map((event) => event.payload.asset_identifier),
    treasury: (events) => events.map((event) => event.payload.sender),
  },
});
```

| Rule | Detail |
| --- | --- |
| Types | Each label's declared types narrow its handler, so `event.payload` is typed without a guard; a label missing from `on` is a compile error |
| Order | A label's events arrive in cursor order; labels don't interleave within a page. Add `onBatch` for strict global order |
| Cursor | Computed over the block's full event set, so you can add or drop labels between restarts and keep the checkpoint |
| REST | One JSON query param: `filters={"peg":{"types":["ft_transfer"]}}`; each event echoes `"matched": ["peg"]`. SSE takes the same param |

## Aggregates

Scalar aggregates run over the same filtered set as the list and count endpoints.

```bash
curl "$SECONDLAYER_API_URL/v1/subgraphs/sbtc-flows/transfers/aggregate" \
  -H "Authorization: Bearer $SECONDLAYER_API_KEY" \
  -G \
  -d "status=active" \
  -d "_count=true" \
  -d "_sum=amount" \
  -d "_min=amount" \
  -d "_countDistinct=sender"
```

```json response.json status=200
{
  "count": 42,
  "countDistinct": { "sender": 7 },
  "sum": { "amount": "12300000000" },
  "min": { "amount": "1000000" }
}
```

| Param | Effect |
| --- | --- |
| `_count=true` | `COUNT(*)` |
| `_countDistinct=col1,col2` | Distinct count per column |
| `_sum=col`, `_min=col`, `_max=col` | Comma-separated; numeric columns only (`uint`, `int`, and `_block_height`) |

| Result | Type |
| --- | --- |
| `count`, `countDistinct.col` | JSON numbers |
| `sum`, `min`, `max` | Lossless strings |
| `sum` over an empty set | `"0"`; `min` and `max` are `null` |
| No aggregate param | `{ "count": <n> }` |

| Status / code | Cause |
| --- | --- |
| `400 NON_NUMERIC_COLUMN` | A non-numeric `_sum`, `_min` or `_max` column |
| `400 INVALID_COLUMN` | An unknown column |
| `400 TOO_MANY_AGGREGATES` | Past 32 aggregate columns per request |

The SDK types it as `sl.subgraphs.typed(def).<table>.aggregate(spec)`, or untyped as `sl.subgraphs.aggregate(name, table, params)`: [SDK reference](https://www.secondlayer.tools/docs/sdk.md).

## Read next

- [SDK](https://www.secondlayer.tools/docs/sdk.md)
- [Streams](https://www.secondlayer.tools/docs/streams.md)
- [Cursors and Pages](https://www.secondlayer.tools/docs/cursors.md)

## Notes for agents

- Import from '@secondlayer/stacks/filters'. 'on.<event>(fields)' returns a filter with toIndexParams, toStreamsParams, toChainTrigger and toSubgraphSource.
- A field a surface cannot express throws at projection time; it never matches silently wider.
- Aggregates: '/v1/subgraphs/<name>/<table>/aggregate' with _count, _sum, _min, _countDistinct. Results are lossless strings.

## 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`
