SDK reference
Every export of @secondlayer/sdk, extracted from its TypeScript source.
Start with the guide
This is the index. SDK explains the client, consumers, proofs, and signature verification in the order you'd actually use them.
Client
Compact API-key view for {@link ContextSnapshot} — never the plaintext.
Compact project view for {@link ContextSnapshot}.
A point-in-time orientation snapshot for an agent: who you are, the live tips, and what you own.
resolveApiKey(apiKey?: string): null | stringResolve the credential a client should use.
SecondLayer(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): unknownFields 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).
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…
Superset of the columns the decoded_events table holds.
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`.
The checkpoint for a reorg rollback.
StreamsServerError(message: string, status: number, body?: object): unknownThrown on a 5xx from the Streams API.
StreamsSignatureError(message?: string): unknownThrown when response signature verification is enabled and fails.
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 subscription on a reorg (`type: "chain.reorg.rollback"`).
Delivered once per affected subscription 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 /subscriptions/: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-subscription webhook delivery, as sent to a `format: "standard-webhooks"` subscription (the default) — `{ type, timestamp, data }`.
Any chain-subscription webhook body.
decodeChainWebhook(rawBody: string): ChainWebhookDeliveryDecode + narrow a chain-subscription webhook delivery body into a typed {@link ChainWebhookDelivery}.
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
Polymorphic subscription mode (mirrors db/types `SubscriptionKind`).
Subscriptions(options?: object): unknownErgonomic chain-trigger constructors for `subscriptions.create({ triggers })`.
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`, …).
verifyStandardWebhooksHeaders(body: string, headers: StandardWebhooksHeaders | object, secret: string, opts?: VerifyOptions): booleanverifyWebhookSignature(rawBody: string, headers: WebhookHeaderInput, secret: string, toleranceSeconds?: number): booleanVerify a Secondlayer webhook delivery signature.
Account
ApiKeys(options?: object): unknownA key as seen by {@link ApiKeys.list} — metadata only, never the plaintext.
Typed client for project management (`/api/projects/*`).
Projects(options?: object): unknownScope of a minted read key.
Clarity
decodeClarityValue(hex: string): objectDecode a hex-encoded Clarity value to JSON-safe JS (uints as strings, buffers as `0x…` hex, tuples as objects).
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.
Contracts
Errors
ApiError(status: number, message: string, body?: object, code?: string, options?: SecondLayerErrorOptions): unknownError thrown by {@link SecondLayer} when an API request fails.
AuthError(message?: string): unknownThrown on a 401 — by both the platform clients and Streams.
Structured payload carried on a refused BYO breaking-change deploy.
ByoBreakingChangeError(message: string, details: ByoBreakingChangeDetails): unknownThrown when a BYO subgraph deploy is refused for a breaking schema change.
parseRetryAfter(value?: null | string): null | numberParse a `Retry-After` header: delta-seconds or an HTTP-date.
RateLimitError(message?: string, retryAfter?: string): unknownThrown on a 429 — by both the platform 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): unknownThrown on a 4xx the caller can fix (bad cursor, bad params).
VersionConflictError(currentVersion: string, expectedVersion: string, message?: string): unknownThrown on optimistic-concurrency conflict when a deploy supplies an `expectedVersion` that no longer matches the server's stored version.
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.
x402
buildSignedX402Payment(opts: BuildSignedX402PaymentOptions): objectBuild a signed, base64 `PAYMENT-SIGNATURE` header for one `accepts[]` entry.
createX402Client(opts: X402ClientOptions): X402ClientA small client over {@link withX402}: `.get/.post` against `baseUrl`, returning parsed JSON plus the settlement receipt.
Bitcoin-native first — sBTC is the compelling micropay asset; USDCx the dollar peg; STX the fallback.
payAndRetry(doFetch: X402FetchFn, opts: PayAndRetryOptions): objectLow-level: run a request via a caller-controlled fetch; if it 402s, pay and retry once.
readX402Challenge(res: Response): objectRead the x402 challenge from a 402 response — prefer the wire header, fall back to the JSON body.
readX402Receipt(res: Response): null | X402ReceiptRead the settlement receipt from a paid 200 response.
resolveAccountNonce(address: string, nodeUrl?: string): objectFetch the payer account's next nonce from a Stacks node (`/v2/accounts`).
selectOffer(challenge: X402Challenge, opts?: SelectOfferOptions): objectChoose an `accepts[]` entry by preference order, skipping any that exceed the per-asset spend cap.
withX402(baseFetch: object, opts: WithX402Options): X402FetchWrap a `fetch` so requests transparently pay on 402: select an offer (by `preferAssets` + `maxAmountPerCall`), resolve the nonce, sign origin-only, and retry once with `PAYMENT-SIGNATURE`.
Client for the x402 pay-per-request rail.
Decoded `PAYMENT-RESPONSE` settlement receipt.
X402SpendGuardError(message: string): unknownThrown when no offered asset is within the caller's spend guard / preferences.
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.
shutdownSignal(options?: object): AbortSignalAn `AbortSignal` wired to SIGTERM/SIGINT (redeploys arrive as SIGTERM).
The transaction type a sink hands to `onBatch` (`ctx.tx`).
`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 …