Build Your First Index
Copy every sBTC transfer into a SQLite file on your machine, reorg-safe and resumable, in four steps.
The SDK reads two variables. Hosted reads use an account key from Keys and Billing; on your own box, see Use these docs on your box.
The sink commits rows and the checkpoint together and rolls back when a reorg lands, so a crash resumes where it stopped.
import { Database } from "bun:sqlite";
import { Index } from "@secondlayer/sdk";
import { bunSqliteSink } from "@secondlayer/sdk/sinks/bun-sqlite";
const db = new Database("transfers.db");
db.exec(
"CREATE TABLE IF NOT EXISTS transfers (cursor TEXT PRIMARY KEY, block_height INTEGER, tx_id TEXT, sender TEXT, recipient TEXT, amount TEXT)",
);
await new Index().events.consume({
eventType: "ft_transfer",
assetIdentifier: "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token::sbtc-token",
fromHeight: 9_340_000,
sink: bunSqliteSink(db, { id: "sbtc-transfers", tables: ["transfers"], height: "block_height" }),
onBatch: (events, ctx) => {
for (const event of events) {
ctx.tx.run("INSERT OR IGNORE INTO transfers VALUES (?, ?, ?, ?, ?, ?)", [
event.cursor, event.block_height, event.tx_id, event.sender, event.recipient, event.amount,
]);
}
},
});
, (fromHeight: 0 backfills from genesis) and . Run it with bun index.ts.
The count grows until the loop catches up with the chain. Stop it and run it again: it resumes from the committed checkpoint.
Index hands you rows in the shape we decode. For your own API shape and a hosted table, use Subgraphs; to run the loop somewhere permanent, see Deploy a Consumer.
Edit on GitHub