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.

filters.tsts
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()] });

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

DifferenceWhere
Print event is print on Index, print_event on SubgraphsIndex, Subgraphs
contract_call and contract_deploy live on a different Index endpoint than eventsIndex
Amounts are strings: a bigint in a JSON.stringify body throws, so toChainTrigger() turns 100_000n into "100000"Webhooks
trait scoping existsIndex, 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.

on.sbtcDeposit({}).toChainTrigger(); // ok: trigger-only event
on.sbtcDeposit({}).toIndexParams();
✗ Property 'toIndexParams' does not exist

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.

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.

import { fromSubgraphSource } from "@secondlayer/stacks/filters";
const source = fromSubgraphSource(subgraph.sources.swaps);
const same = source.toSubgraphSource();

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 lists the ones on /v1/streams/events.

$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.

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.

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),
},
});
RuleDetail
TypesEach label's declared types narrow its handler, so event.payload is typed without a guard; a label missing from on is a compile error
OrderA label's events arrive in cursor order; labels don't interleave within a page. Add onBatch for strict global order
CursorComputed over the block's full event set, so you can add or drop labels between restarts and keep the checkpoint
RESTOne JSON query param: filters={"peg":{"types":["ft_transfer"]}}; each event echoes "matched": ["peg"]. SSE takes the same param

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

$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"
200response.jsonjson
{
"count": 42,
"countDistinct": { "sender": 7 },
"sum": { "amount": "12300000000" },
"min": { "amount": "1000000" }
}
ParamEffect
_count=trueCOUNT(*)
_countDistinct=col1,col2Distinct count per column
_sum=col, _min=col, _max=colComma-separated; numeric columns only (uint, int, and _block_height)
ResultType
count, countDistinct.colJSON numbers
sum, min, maxLossless strings
sum over an empty set"0"; min and max are null
No aggregate param{ "count": <n> }
Status / codeCause
400 NON_NUMERIC_COLUMNA non-numeric _sum, _min or _max column
400 INVALID_COLUMNAn unknown column
400 TOO_MANY_AGGREGATESPast 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.

Edit on GitHub

Quick Start

Copy this prompt into your agent.

Set up Secondlayer Index in this project. It reads Stacks chain data, decoded, from block 1.

1. Install `@secondlayer/sdk` with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Ask me for a Secondlayer API key (`sk-sl_...`, from https://www.secondlayer.tools/signin) and put it in `.env` as `SECONDLAYER_API_KEY`. Never commit it. If I self-host, use `INSTANCE_TOKEN` and my instance URL instead. Until I give you one, read with a free trial key: `curl -X POST https://api.secondlayer.tools/api/public/trial-key` returns `{ key }`, read-only for Streams and Index, good for 24 hours and 100,000 rows. Keep it out of git too.
3. Add a note to `AGENTS.md`, creating it if needed: before using Secondlayer, follow the secondlayer skill if it's installed, and read https://www.secondlayer.tools/llms.txt. Before writing code, read https://www.secondlayer.tools/docs/index.md. Any docs page opens as Markdown when you add `.md` to its URL.
4. If you support skills, run: `bunx skills add ryanwaits/secondlayer --skill secondlayer -y`