SDK reference
Every export of @secondlayer/sdk, extracted from its TypeScript source.
Start with the guide
This is the index. SDK explains the client, checkpointed consumers, and signature verification, and routes you to whichever surface owns the rest.
Client
Hosted account key (`sk-sl_*`) for api.secondlayer.tools.
contextField(read: object): objectFold one read into a {@link ContextField}: the value, or `null` with the failure described.
One snapshot field: the value, or `null` plus the error that produced it.
Why one snapshot field could not be read.
A point-in-time orientation snapshot for an agent: the live tips and what this instance holds.
Default per-request budget.
Instance credential.
Product default: the local one-box API.
Per-call options every `request*` method accepts.
resolveAccountKey(accountKey?: string): null | stringResolve the hosted account key for archive quote/fetch/credits.
resolveApiKey(apiKey?: string): null | stringResolve the instance credential.
resolveBaseUrl(explicit?: string): stringSecondLayer(options?: object): unknownIndex
consumeIndexFeed(opts: object): objectCheckpointed pull loop over a cursor-paginated Index feed — the Index port of `consumeStreamsEvents`, sharing its contract: at-least-once delivery, client-owned checkpoints (`onBatch` may return th…
FtTransfersResource(params: object): object`index.ftTransfers` — callable shorthand for `.list()`, with `.list`/`.walk` still available: `await sl.index.ftTransfers({ contractId })`.
Index(options?: object): unknownLargest page any Index list route serves.
Fields every read returns regardless of `fields` — the consume contract (`cursor`, `block_height`) plus the union discriminant.
A block resource.
One canonical block in the sync map.
Consumer options shared by `index.events.consume` and `index.contractCalls.consume`.
The `GET /v1/index` discovery doc — live endpoint + filter vocabulary.
Decoded chain event, discriminated by `event_type`.
An event row narrowed to a `fields` selection (plus what always ships).
The single decoded-event member matching one `event_type` literal.
IndexEventsResource(params: object): object`index.events` — callable shorthand for `.list()`; `eventType` is required.
Per-event-type filter vocabulary in the {@link IndexDiscovery} doc.
Minimum envelope shape of a consumable Index feed page.
One page fetch.
Minimum shape a consumed Index row must expose.
A pending (unconfirmed) transaction.
A raw decoded PoX-5 print event.
The decoded `pox-5` boot-contract print topics (SIP-045 Bitcoin Staking) — one source of truth in `@secondlayer/stacks/pox5` (already a dependency; the old "SDK owns its own dependency surface" rat…
Aggregate stats for one PoX reward cycle — distinct from `index.stacking` (decoded per-call PoX-4 actions); this is the reward-cycle rollup.
Per-function action count within a reward cycle.
A chain reorg overlapping a returned page's height range.
A completed sBTC peg-in, keyed by `bitcoin_txid` (deposits carry no `request_id`).
A deposit fetched by Bitcoin txid — always terminal, hence `status`.
A raw decoded sBTC protocol-state event — the full `sbtc_events` row, one per event across all topics.
The peg "scoreboard" — a single all-time canonical aggregate.
A peg-out collapsed to one row per `request_id`, with lifecycle `status` derived from the latest accept/reject.
A single peg-out's full assembled lifecycle, fetched by `request_id`.
One phase of a withdrawal's lifecycle (the on-Stacks event that drove it).
A decoded PoX-4 stacking action (one per stacking contract call).
Full transaction document: columnar fields plus `raw_tx`-decoded enrichment.
NftTransfersResource(params: object): object`index.nftTransfers` — callable shorthand for `.list()` (see {@link FtTransfersResource}).
`index.pox5` — decoded PoX-5 print events, the staking primitive from the epoch 4.0 hard fork onward (PoX-4's `index.stacking` stream ends there).
`index.pox` — PoX reward-cycle aggregates.
Empirical per-topic print payload schema for a contract, inferred from sampled on-chain events.
`index.sbtc` — the decoded sBTC peg surface (deposits, withdrawals, raw events, scoreboard).
Options every `walk*` feed shares on top of its list filters.
Subgraphs
getSubgraph(def: object, options?: Subgraphs | SecondLayer | object): InferSubgraphClientReturns a typed client for a subgraph defined with `defineSubgraph()`.
Status of a tracked reindex/backfill operation (poll until terminal).
Subgraphs(options?: object): unknownStreams
What the loop knows at the end of a page, handed to `onBatch`.
createStreamsClient(options: CreateStreamsClientOptions): StreamsClientHelpers for Streams cursors.
decode(event: StreamsEvent): IndexEventDecode a raw Streams event into the SAME flat, `event_type`-discriminated row shape Index serves — so Streams consumption reads identically to Index consumption, with one call instead of eleven gua…
decodeClarityValue(hex: string): objectDecode a hex-encoded Clarity value to JSON-safe JS (uints as strings, buffers as `0x…` hex, tuples as objects).
Superset of the columns the decoded_events table holds.
Union of every decoded DB-row shape the guard+decode pairs produce — exactly what the `decoded_events` table stores.
Decoded form of a Clarity `print` event: - `topic`: the print topic, when the contract emits a `{ topic, ...
decodeFtBurn(event: StreamsEvent): DecodedFtBurndecodeFtMint(event: StreamsEvent): DecodedFtMintdecodeFtTransfer(event: StreamsEvent): DecodedFtTransferdecodeNftBurn(event: StreamsEvent): DecodedNftBurndecodeNftMint(event: StreamsEvent): DecodedNftMintdecodeNftTransfer(event: StreamsEvent): DecodedNftTransferdecodePrint(event: StreamsEvent): DecodedPrintdecodeStxBurn(event: StreamsEvent): DecodedStxBurndecodeStxLock(event: StreamsEvent): DecodedStxLockdecodeStxMint(event: StreamsEvent): DecodedStxMintdecodeStxTransfer(event: StreamsEvent): DecodedStxTransferisFtBurn(event: StreamsEvent): booleanisFtMint(event: StreamsEvent): booleanisFtTransfer(event: StreamsEvent): booleanisNftBurn(event: StreamsEvent): booleanisNftMint(event: StreamsEvent): booleanisNftTransfer(event: StreamsEvent): booleanisPrint(event: StreamsEvent): booleanisStxBurn(event: StreamsEvent): booleanisStxLock(event: StreamsEvent): booleanisStxMint(event: StreamsEvent): booleanisStxTransfer(event: StreamsEvent): booleanOne yielded page from {@link StreamsClient.consume} — the `GET /v1/streams/events` envelope verbatim, with `next_cursor` renamed to `cursor` (the checkpoint to persist and resume from).
One bulk parquet file in the dumps manifest.
A raw Streams event.
Union of every Streams payload shape, discriminated by `event_type` on the parent `StreamsEvent`.
`cursor` is the rewind position the loop resumes from after `onReorg`: the foot of the fork point, or `null` for a fork at genesis.
StreamsServerError(message: string, status: number, body?: object, code?: string): unknownThrown on a 5xx from the Streams API, and on a failed signing-key fetch.
StreamsSignatureError(message?: string): unknownThrown when response signature verification is enabled and fails.
Handle for a live subscription: call it to unsubscribe.
toJsonSafe(value: object): objectMake a cvToValue result JSON-serializable: Clarity (u)ints decode to bigint, which JSON.stringify can't handle — convert recursively to strings.
Subscriptions and webhooks
One delivery body, generic over its trigger literal + matched-event shape.
Delivered when a matched chain event lands in a canonical block (`event_type: "chain.<trigger>.apply"`).
One `apply` envelope, generic over its trigger literal + matched-event shape.
Wrapper around an event-level trigger's matched event.
`event.data` for an `ft_burn` delivery.
`event.data` for an `ft_mint` delivery.
`event.data` for an `ft_transfer` delivery.
`event.data` for an `nft_burn` delivery.
`event.data` for an `nft_mint` delivery.
`event.data` for an `nft_transfer` delivery.
`event.data` for a `print_event` delivery.
One orphaned delivery recalled by a reorg rollback.
Delivered once per affected webhook on a reorg (`type: "chain.reorg.rollback"`).
Delivered once per affected webhook on a reorg (`event_type: "chain.reorg.rollback"`).
`event.data` for a `stx_burn` delivery.
`event.data` for a `stx_lock` delivery.
`event.data` for a `stx_mint` delivery.
`event.data` for a `stx_transfer` delivery.
The `POST /webhooks/:id/test` ping (`type: "chain.test.apply"`) — not a real chain event.
JSON mirror of the subgraph runtime's `SubgraphFilter` union.
A tx-level trigger's matched event (`contract_call` / `contract_deploy`) — flat, no nested `data` key.
The full wire body of a chain-webhook webhook delivery, as sent to a `format: "standard-webhooks"` webhook (the default) — `{ type, timestamp, data }`.
Any chain-webhook webhook body.
Payload for `sbtc_deposit` (topic: completed-deposit).
Payload for `sbtc_withdrawal_create`, `sbtc_withdrawal_accept`, `sbtc_withdrawal_reject` — the on-Stacks lifecycle events.
Payload for `sbtc_withdrawal_swept_confirmed` — fired once when a peg-out's committed BTC sweep crosses the confirmation threshold on Bitcoin.
Standard Webhooks signing helpers — https://standardwebhooks.com
Ergonomic chain-trigger constructors for `webhooks.create({ triggers })`.
verifyStandardWebhooksHeaders(body: string, headers: StandardWebhooksHeaders | object, secret: string, opts?: VerifyOptions): booleanPolymorphic webhook mode (mirrors db/types `WebhookKind`).
Result of a one-off test delivery (`POST /:id/test`).
Contracts
Errors
ApiError(status: number, message: string, body?: object, code?: string, options?: SecondLayerErrorOptions): unknownError thrown by {@link SecondLayer} when an API request fails.
ArchiveAuthError(message?: string): unknownThrown on a 401 from the archive ops host (quote/fetch/credits).
ArchiveGateNotConfiguredError(message?: string): unknownThrown on a 503 when the archive fetch gate is unconfigured.
ArchiveSignatureError(message?: string): unknownThrown when an archive manifest signature is missing or does not verify.
AuthError(message?: string, body?: object, code?: string): unknownThrown on a 401 by both the instance clients and Streams.
InsufficientArchiveCreditsError(message?: string, shortfallUsdMicros?: number): unknownThrown on a 402 from archive fetch — prepaid credits do not cover the quote.
parseRetryAfter(value?: null | string): null | numberParse a `Retry-After` header: delta-seconds or an HTTP-date.
RateLimitError(message?: string, retryAfter?: string, body?: object, code?: string): unknownThrown on a 429 by both the instance clients and Streams.
SecondLayerError(shortMessage: string, options?: SecondLayerErrorOptions): unknownRoot of the SDK error family.
Options accepted by every error in the family.
ValidationError(message: string, status: number, body?: object, code?: string): unknownThrown on a 4xx the caller can fix (bad cursor, bad params).
Proofs
fetchRewardSet(opts: object): objectResolve a reward set directly from a stacks-node (`/v3/stacker_set/{cycle}`), so a caller can verify the consensus layer against a node IT trusts rather than the reward set Secondlayer embedded in …
Trustless transaction-inclusion proof verification.
verifyTransactionProof(proof: TransactionProof, opts?: object): TransactionProofVerifyResultVerify a transaction-inclusion proof.
Other
consumerHealth(options?: object): ConsumerHealthLiveness for a consume loop.
The two pieces every "deploy a consumer" guide leaves out, packaged: a liveness endpoint and a graceful-shutdown signal.
A consumer sink: the destination adapter a consume loop writes through.
createArchiveClient(options?: CreateArchiveClientOptions): ArchiveClientdecodeChainWebhook(rawBody: string): ChainWebhookDeliveryDecode + narrow a chain webhook delivery body into a typed {@link ChainWebhookDelivery}.
Structural `/public/status` payload.
The subset of `/status` a diagnosis reads.
Hosted archive client plus instance `verify`.
shutdownSignal(options?: object): AbortSignalAn `AbortSignal` wired to SIGTERM/SIGINT (redeploys arrive as SIGTERM).
The transaction type a sink hands to `onBatch` (`ctx.tx`).
verifySecondlayerSignature(rawBody: string, headers: WebhookHeaderInput, publicKeyPem: string): booleanVerify the universal Secondlayer authenticity signature that every delivery carries, regardless of body format (`raw`, `cloudevents`, `standard-webhooks`, …).
verifyWebhookSignature(rawBody: string, headers: WebhookHeaderInput, secret: string, toleranceSeconds?: number): booleanVerify a Secondlayer webhook delivery signature.
Webhooks(options?: object): unknown`ctx` gains `tx` exactly when a sink is attached; without one the shape is unchanged (an intersection with `unknown` is an identity, so contextual typing of `onBatch` callbacks never degrades to a …