@secondlayer/sdk 10.4.3 → 10.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,241 +1,3 @@
1
- import { ReindexResponse, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGapsResponse, SubgraphQueryParams, SubgraphSummary } from "@secondlayer/shared/schemas";
2
- import { DeploySubgraphRequest, DeploySubgraphResponse } from "@secondlayer/shared/schemas/subgraphs";
3
- import { SubgraphAgentSchema, SubgraphSpecOptions } from "@secondlayer/shared/subgraphs/spec";
4
- import { InferSubgraphClient } from "@secondlayer/subgraphs";
5
- type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
6
- interface SecondLayerOptions {
7
- /** Base URL of the instance API (trailing slashes are stripped). */
8
- baseUrl: string;
9
- /** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */
10
- apiKey?: string;
11
- /** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by
12
- * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */
13
- accountKey?: string;
14
- /** Fetch implementation. Tests and edge runtimes can provide their own. */
15
- fetchImpl?: FetchLike;
16
- /** Public base URL for Streams bulk parquet dumps (the cold backfill plane).
17
- * Required for `streams.dumps.*`; without it the dumps client falls back to
18
- * its built-in default. */
19
- dumpsBaseUrl?: string;
20
- /** Public base URL for the signed canonical archive tree. Defaults to
21
- * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */
22
- archiveBaseUrl?: string;
23
- /** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,
24
- * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */
25
- archiveOpsUrl?: string;
26
- /** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */
27
- origin?: "cli" | "mcp" | "session";
28
- /** Check the ed25519 signature on every Streams read. Omit for lenient
29
- * (verify when signed, pass through unsigned self-host responses), `true`
30
- * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */
31
- verify?: boolean | {
32
- publicKey: string;
33
- };
34
- /** Check the dumps manifest signature before trusting any file hash
35
- * (default on). Reaches `sl.streams.dumps`. */
36
- verifyDumpsManifest?: boolean;
37
- /** How long one request may take, headers and body, before it fails with a
38
- * retryable `ApiError` (default 30 000 ms). A hung socket then trips the
39
- * retry policy instead of stalling a walk or consume loop forever. `0`
40
- * disables the timeout. */
41
- requestTimeoutMs?: number;
42
- }
43
- /** Default per-request budget. Long enough for a 1000-row filtered page on a
44
- * cold cache, short enough that a half-open connection surfaces as a retry. */
45
- declare const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
46
- /** Per-call options every `request*` method accepts. */
47
- type RequestOptions = {
48
- /** Cancels the in-flight request (and its body read). The rejection is the
49
- * signal's reason, an `AbortError` by default, never an `ApiError`. */
50
- signal?: AbortSignal;
51
- };
52
- /** Product default: the local one-box API. Override with `baseUrl` or
53
- * `SECONDLAYER_API_URL`. */
54
- declare const LOCAL_API_URL = "http://127.0.0.1:3800";
55
- /** Instance credential. `secondlayer init` writes this. */
56
- declare const INSTANCE_TOKEN_ENV = "INSTANCE_TOKEN";
57
- /** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */
58
- declare const ACCOUNT_KEY_ENV = "SECONDLAYER_API_KEY";
59
- declare function resolveBaseUrl(explicit?: string): string;
60
- /** Resolve the instance credential. Precedence: explicit `apiKey` (including
61
- * `""` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key
62
- * env vars. Guarded for browsers and edge runtimes. */
63
- declare function resolveApiKey(apiKey?: string): string | undefined;
64
- /** Resolve the hosted account key for archive quote/fetch/credits.
65
- * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY` → `SL_API_KEY` /
66
- * `SL_ARCHIVE_API_KEY` (one-release warn-fallbacks). Does not read
67
- * `INSTANCE_TOKEN`. */
68
- declare function resolveAccountKey(accountKey?: string): string | undefined;
69
- declare abstract class BaseClient {
70
- protected baseUrl: string;
71
- protected apiKey?: string;
72
- protected origin: "cli" | "mcp" | "session";
73
- protected fetchImpl: FetchLike;
74
- protected requestTimeoutMs: number;
75
- constructor(options?: Partial<SecondLayerOptions>);
76
- static authHeaders(apiKey?: string): Record<string, string>;
77
- protected request<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
78
- /** Like `request`, but maps a 404 to `null` instead of throwing — the one
79
- * place that owns the "absent resource" rule for `get*` accessors. */
80
- protected requestOrNull<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T | null>;
81
- protected requestText(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<string>;
82
- /** Run one request under the caller's signal plus the per-request timeout.
83
- * One combined signal covers the fetch and the body read, so a socket that
84
- * stalls mid-body times out the same way one that never answers does. A
85
- * timeout rejects with a retryable `ApiError`; a caller abort rejects with
86
- * the signal's reason so loops can tell "stop" from "try again". */
87
- private withRequestBudget;
88
- /** Issue the HTTP request and map non-2xx statuses onto the error family.
89
- * `signal` is the combined caller-plus-timeout signal from `request*`;
90
- * subclasses that stream a body call this directly and read it themselves. */
91
- protected fetchResponse(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<Response>;
92
- }
93
- interface SubgraphSource {
94
- name: string;
95
- version: string;
96
- sourceCode: string | null;
97
- readOnly: boolean;
98
- reason?: string;
99
- updatedAt: string;
100
- }
101
- /** Status of a tracked reindex/backfill operation (poll until terminal). */
102
- interface SubgraphOperationStatus {
103
- id: string;
104
- subgraphName: string;
105
- kind: "reindex" | "backfill";
106
- status: "queued" | "running" | "completed" | "failed" | "cancelled";
107
- fromBlock: number | null;
108
- toBlock: number | null;
109
- processedBlocks: number | null;
110
- /** 0–1 fraction; null when no denominator is known yet. 1 when completed. */
111
- progress: number | null;
112
- error: string | null;
113
- startedAt: string | null;
114
- finishedAt: string | null;
115
- createdAt: string;
116
- updatedAt: string;
117
- }
118
- /** /v1 cursor envelope for subgraph table reads. */
119
- interface SubgraphRowsEnvelope<T = unknown> {
120
- rows: T[];
121
- next_cursor: string | null;
122
- tip: {
123
- block_height: number;
124
- subgraph_height: number;
125
- blocks_behind: number;
126
- };
127
- }
128
- interface BundleSubgraphResponse {
129
- ok: true;
130
- name: string;
131
- version: string | null;
132
- description: string | null;
133
- sources: Record<string, Record<string, unknown>>;
134
- schema: Record<string, unknown>;
135
- handlerCode: string;
136
- sourceCode: string;
137
- bundleSize: number;
138
- }
139
- declare class Subgraphs extends BaseClient {
140
- list(): Promise<{
141
- data: SubgraphSummary[];
142
- }>;
143
- /**
144
- * The subgraph's current state — health, sync position, tables. The verify
145
- * step after a deploy, reindex, or backfill: poll it until `sync` catches
146
- * the tip.
147
- */
148
- status(name: string): Promise<SubgraphDetail>;
149
- openapi(name: string, options?: SubgraphSpecOptions): Promise<Record<string, unknown>>;
150
- schema(name: string, options?: SubgraphSpecOptions): Promise<SubgraphAgentSchema>;
151
- markdown(name: string, options?: SubgraphSpecOptions): Promise<string>;
152
- /**
153
- * Reindex always drops and rebuilds the whole subgraph, so it takes no
154
- * block range; the API rejects one with `REINDEX_RANGE_NOT_SUPPORTED`.
155
- * Use {@link backfill} to process a specific range. While a reindex or
156
- * backfill is already running the API answers 409 with code
157
- * `OPERATION_IN_PROGRESS`; poll {@link operations} until it finishes.
158
- */
159
- reindex(name: string): Promise<ReindexResponse>;
160
- stop(name: string): Promise<{
161
- message: string;
162
- operationId?: string;
163
- status?: string;
164
- }>;
165
- /** Process one block range. 409 `OPERATION_IN_PROGRESS` while another
166
- * reindex or backfill runs on this subgraph. */
167
- backfill(name: string, options: {
168
- fromBlock: number;
169
- toBlock: number;
170
- }): Promise<ReindexResponse>;
171
- gaps(name: string, opts?: {
172
- limit?: number;
173
- offset?: number;
174
- resolved?: boolean;
175
- }): Promise<SubgraphGapsResponse>;
176
- delete(name: string, options?: {
177
- force?: boolean;
178
- }): Promise<{
179
- message: string;
180
- }>;
181
- /**
182
- * Open /v1 read: cursor-paginated rows. Anon works on an open instance;
183
- * pass an apiKey on the client where reads are closed. Resume with the
184
- * returned `next_cursor`.
185
- */
186
- rows<T = unknown>(name: string, table: string, params?: Omit<SubgraphQueryParams, "offset" | "sort"> & {
187
- cursor?: string;
188
- }): Promise<SubgraphRowsEnvelope<T>>;
189
- /** Recent reindex/backfill operations for a subgraph, newest first. */
190
- operations(name: string): Promise<{
191
- operations: SubgraphOperationStatus[];
192
- }>;
193
- /** Status of a single operation (poll the `operationId` returned by
194
- * reindex/backfill/stop until `status` is terminal). */
195
- getOperation(name: string, operationId: string): Promise<SubgraphOperationStatus>;
196
- /** Create or update a subgraph. A deploy that needs a rebuild queues one;
197
- * if a reindex or backfill is already running the API answers 409 with
198
- * code `OPERATION_IN_PROGRESS` (an `ApiError`, not a dedicated class). */
199
- deploy(data: DeploySubgraphRequest): Promise<DeploySubgraphResponse>;
200
- getSource(name: string): Promise<SubgraphSource>;
201
- /**
202
- * Bundle a TypeScript subgraph source on the server. Used by the web chat
203
- * authoring loop so Vercel's serverless runtime doesn't have to run esbuild.
204
- */
205
- bundle(data: {
206
- code: string;
207
- }): Promise<BundleSubgraphResponse>;
208
- queryTable(name: string, table: string, params?: SubgraphQueryParams): Promise<unknown[]>;
209
- queryTableCount(name: string, table: string, params?: SubgraphQueryParams): Promise<{
210
- count: number;
211
- }>;
212
- queryTableAggregate(name: string, table: string, params?: SubgraphAggregateParams): Promise<SubgraphAggregateResponse>;
213
- /**
214
- * Returns a typed client for a subgraph defined with `defineSubgraph()`.
215
- * Row types are inferred from the subgraph's schema literal types.
216
- *
217
- * @example
218
- * ```ts
219
- * import mySubgraph from './subgraphs/my-token-subgraph'
220
- * const client = sl.subgraphs.typed(mySubgraph)
221
- * const rows = await client.transfers.findMany({ where: { sender: 'SP...' } })
222
- * // rows: InferTableRow<typeof mySubgraph.schema.transfers>[]
223
- * ```
224
- */
225
- typed<T extends {
226
- name: string;
227
- schema: Record<string, unknown>;
228
- }>(def: T): InferSubgraphClient<T>;
229
- /**
230
- * `columns` is the table's declared column set from `defineSubgraph()`.
231
- * Filters and orderBy always accept the canonical system names
232
- * `_id` / `_blockHeight` / `_txId` / `_createdAt`; the unprefixed
233
- * shorthands (`id`, `blockHeight`, ...) mean the system column only when
234
- * the table declares no column of that name.
235
- */
236
- private createTableClient;
237
- }
238
- import { InferSubgraphClient as InferSubgraphClient2 } from "@secondlayer/subgraphs";
239
1
  import { InstanceDiagnosis as InstanceDiagnosis2 } from "@secondlayer/shared/archive/instance-diagnosis";
240
2
  import { SubgraphSummary as SubgraphSummary2 } from "@secondlayer/shared/schemas";
241
3
  import { InstanceDiagnosis, PublicStatus } from "@secondlayer/shared/archive/instance-diagnosis";
@@ -387,6 +149,120 @@ type ArchiveClient = {
387
149
  type SecondLayerArchive = ArchiveClient & {
388
150
  verify(input: ArchiveVerifyInput): Promise<ArchiveVerifyResult>;
389
151
  };
152
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
153
+ interface SecondLayerOptions {
154
+ /** Base URL of the instance API (trailing slashes are stripped). */
155
+ baseUrl: string;
156
+ /** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */
157
+ apiKey?: string;
158
+ /** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by
159
+ * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */
160
+ accountKey?: string;
161
+ /** Fetch implementation. Tests and edge runtimes can provide their own. */
162
+ fetchImpl?: FetchLike;
163
+ /** Public base URL for Streams bulk parquet dumps (the cold backfill plane).
164
+ * Required for `streams.dumps.*`; without it the dumps client falls back to
165
+ * its built-in default. */
166
+ dumpsBaseUrl?: string;
167
+ /** Public base URL for the signed canonical archive tree. Defaults to
168
+ * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */
169
+ archiveBaseUrl?: string;
170
+ /** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,
171
+ * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */
172
+ archiveOpsUrl?: string;
173
+ /** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */
174
+ origin?: "cli" | "mcp" | "session";
175
+ /** Check the ed25519 signature on every Streams read. Omit for lenient
176
+ * (verify when signed, pass through unsigned self-host responses), `true`
177
+ * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */
178
+ verify?: boolean | {
179
+ publicKey: string;
180
+ };
181
+ /** Check the dumps manifest signature before trusting any file hash
182
+ * (default on). Reaches `sl.streams.dumps`. */
183
+ verifyDumpsManifest?: boolean;
184
+ /** How long one request may take, headers and body, before it fails with a
185
+ * retryable `ApiError` (default 30 000 ms). A hung socket then trips the
186
+ * retry policy instead of stalling a walk or consume loop forever. `0`
187
+ * disables the timeout. */
188
+ requestTimeoutMs?: number;
189
+ /** Where GET responses carrying an `ETag` are kept, so a repeat read sends
190
+ * `If-None-Match` and a finalized page comes back as a free `304`.
191
+ * Defaults to an in-memory store of the last 64 pages. Pass your own to
192
+ * keep it across processes (a file, a KV), or `false` to turn it off. */
193
+ etagCache?: EtagCache | false;
194
+ }
195
+ /** One cached GET response: its validator and the body it validated. */
196
+ type EtagEntry = {
197
+ etag: string;
198
+ body: string;
199
+ };
200
+ /** Storage for `etagCache`. Keys are full request URLs. Either method may be
201
+ * async, so a disk or KV store works as well as a Map. */
202
+ interface EtagCache {
203
+ get(key: string): EtagEntry | undefined | Promise<EtagEntry | undefined>;
204
+ set(key: string, entry: EtagEntry): void | Promise<void>;
205
+ }
206
+ /** Bounded in-memory `EtagCache`. Evicts the least recently used page, so a
207
+ * long walk can't hold more than `limit` page bodies. */
208
+ declare class MemoryEtagCache implements EtagCache {
209
+ private readonly limit;
210
+ private entries;
211
+ constructor(limit?: number);
212
+ get(key: string): EtagEntry | undefined;
213
+ set(key: string, entry: EtagEntry): void;
214
+ }
215
+ /** Default per-request budget. Long enough for a 1000-row filtered page on a
216
+ * cold cache, short enough that a half-open connection surfaces as a retry. */
217
+ declare const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
218
+ /** Per-call options every `request*` method accepts. */
219
+ type RequestOptions = {
220
+ /** Cancels the in-flight request (and its body read). The rejection is the
221
+ * signal's reason, an `AbortError` by default, never an `ApiError`. */
222
+ signal?: AbortSignal;
223
+ };
224
+ /** Product default: the local one-box API. Override with `baseUrl` or
225
+ * `SECONDLAYER_API_URL`. */
226
+ declare const LOCAL_API_URL = "http://127.0.0.1:3800";
227
+ /** Instance credential. `secondlayer init` writes this. */
228
+ declare const INSTANCE_TOKEN_ENV = "INSTANCE_TOKEN";
229
+ /** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */
230
+ declare const ACCOUNT_KEY_ENV = "SECONDLAYER_API_KEY";
231
+ declare function resolveBaseUrl(explicit?: string): string;
232
+ /** Resolve the instance credential. Precedence: explicit `apiKey` (including
233
+ * `""` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key
234
+ * env vars. Guarded for browsers and edge runtimes. */
235
+ declare function resolveApiKey(apiKey?: string): string | undefined;
236
+ /** Resolve the hosted account key for archive quote/fetch/credits.
237
+ * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY` → `SL_API_KEY` /
238
+ * `SL_ARCHIVE_API_KEY` (one-release warn-fallbacks). Does not read
239
+ * `INSTANCE_TOKEN`. */
240
+ declare function resolveAccountKey(accountKey?: string): string | undefined;
241
+ declare abstract class BaseClient {
242
+ protected baseUrl: string;
243
+ protected apiKey?: string;
244
+ protected origin: "cli" | "mcp" | "session";
245
+ protected fetchImpl: FetchLike;
246
+ protected requestTimeoutMs: number;
247
+ protected etagCache: EtagCache | null;
248
+ constructor(options?: Partial<SecondLayerOptions>);
249
+ static authHeaders(apiKey?: string): Record<string, string>;
250
+ protected request<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
251
+ /** Like `request`, but maps a 404 to `null` instead of throwing — the one
252
+ * place that owns the "absent resource" rule for `get*` accessors. */
253
+ protected requestOrNull<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T | null>;
254
+ protected requestText(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<string>;
255
+ /** Run one request under the caller's signal plus the per-request timeout.
256
+ * One combined signal covers the fetch and the body read, so a socket that
257
+ * stalls mid-body times out the same way one that never answers does. A
258
+ * timeout rejects with a retryable `ApiError`; a caller abort rejects with
259
+ * the signal's reason so loops can tell "stop" from "try again". */
260
+ private withRequestBudget;
261
+ /** Issue the HTTP request and map non-2xx statuses onto the error family.
262
+ * `signal` is the combined caller-plus-timeout signal from `request*`;
263
+ * subclasses that stream a body call this directly and read it themselves. */
264
+ protected fetchResponse(method: string, path: string, body?: unknown, signal?: AbortSignal, extraHeaders?: Record<string, string>): Promise<Response>;
265
+ }
390
266
  /**
391
267
  * Typed client for the contract-discovery API (`GET /v1/contracts`).
392
268
  *
@@ -2617,6 +2493,154 @@ declare class Index extends BaseClient {
2617
2493
  private walkPoxCycles;
2618
2494
  private getPoxCycle;
2619
2495
  }
2496
+ import { ReindexResponse, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGapsResponse, SubgraphQueryParams, SubgraphSummary } from "@secondlayer/shared/schemas";
2497
+ import { DeploySubgraphRequest, DeploySubgraphResponse } from "@secondlayer/shared/schemas/subgraphs";
2498
+ import { SubgraphAgentSchema, SubgraphSpecOptions } from "@secondlayer/shared/subgraphs/spec";
2499
+ import { InferSubgraphClient } from "@secondlayer/subgraphs";
2500
+ interface SubgraphSource {
2501
+ name: string;
2502
+ version: string;
2503
+ sourceCode: string | null;
2504
+ readOnly: boolean;
2505
+ reason?: string;
2506
+ updatedAt: string;
2507
+ }
2508
+ /** Status of a tracked reindex/backfill operation (poll until terminal). */
2509
+ interface SubgraphOperationStatus {
2510
+ id: string;
2511
+ subgraphName: string;
2512
+ kind: "reindex" | "backfill";
2513
+ status: "queued" | "running" | "completed" | "failed" | "cancelled";
2514
+ fromBlock: number | null;
2515
+ toBlock: number | null;
2516
+ processedBlocks: number | null;
2517
+ /** 0–1 fraction; null when no denominator is known yet. 1 when completed. */
2518
+ progress: number | null;
2519
+ error: string | null;
2520
+ startedAt: string | null;
2521
+ finishedAt: string | null;
2522
+ createdAt: string;
2523
+ updatedAt: string;
2524
+ }
2525
+ /** /v1 cursor envelope for subgraph table reads. */
2526
+ interface SubgraphRowsEnvelope<T = unknown> {
2527
+ rows: T[];
2528
+ next_cursor: string | null;
2529
+ tip: {
2530
+ block_height: number;
2531
+ subgraph_height: number;
2532
+ blocks_behind: number;
2533
+ };
2534
+ }
2535
+ interface BundleSubgraphResponse {
2536
+ ok: true;
2537
+ name: string;
2538
+ description: string | null;
2539
+ sources: Record<string, Record<string, unknown>>;
2540
+ schema: Record<string, unknown>;
2541
+ handlerCode: string;
2542
+ sourceCode: string;
2543
+ bundleSize: number;
2544
+ }
2545
+ declare class Subgraphs extends BaseClient {
2546
+ list(): Promise<{
2547
+ data: SubgraphSummary[];
2548
+ }>;
2549
+ /**
2550
+ * The subgraph's current state — health, sync position, tables. The verify
2551
+ * step after a deploy, reindex, or backfill: poll it until `sync` catches
2552
+ * the tip.
2553
+ */
2554
+ status(name: string): Promise<SubgraphDetail>;
2555
+ openapi(name: string, options?: SubgraphSpecOptions): Promise<Record<string, unknown>>;
2556
+ schema(name: string, options?: SubgraphSpecOptions): Promise<SubgraphAgentSchema>;
2557
+ markdown(name: string, options?: SubgraphSpecOptions): Promise<string>;
2558
+ /**
2559
+ * Reindex always drops and rebuilds the whole subgraph, so it takes no
2560
+ * block range; the API rejects one with `REINDEX_RANGE_NOT_SUPPORTED`.
2561
+ * Use {@link backfill} to process a specific range. While a reindex or
2562
+ * backfill is already running the API answers 409 with code
2563
+ * `OPERATION_IN_PROGRESS`; poll {@link operations} until it finishes.
2564
+ */
2565
+ reindex(name: string): Promise<ReindexResponse>;
2566
+ stop(name: string): Promise<{
2567
+ message: string;
2568
+ operationId?: string;
2569
+ status?: string;
2570
+ }>;
2571
+ /** Process one block range. 409 `OPERATION_IN_PROGRESS` while another
2572
+ * reindex or backfill runs on this subgraph. */
2573
+ backfill(name: string, options: {
2574
+ fromBlock: number;
2575
+ toBlock: number;
2576
+ }): Promise<ReindexResponse>;
2577
+ gaps(name: string, opts?: {
2578
+ limit?: number;
2579
+ offset?: number;
2580
+ resolved?: boolean;
2581
+ }): Promise<SubgraphGapsResponse>;
2582
+ delete(name: string, options?: {
2583
+ force?: boolean;
2584
+ }): Promise<{
2585
+ message: string;
2586
+ }>;
2587
+ /**
2588
+ * Open /v1 read: cursor-paginated rows. Anon works on an open instance;
2589
+ * pass an apiKey on the client where reads are closed. Resume with the
2590
+ * returned `next_cursor`.
2591
+ */
2592
+ rows<T = unknown>(name: string, table: string, params?: Omit<SubgraphQueryParams, "offset" | "sort"> & {
2593
+ cursor?: string;
2594
+ }): Promise<SubgraphRowsEnvelope<T>>;
2595
+ /** Recent reindex/backfill operations for a subgraph, newest first. */
2596
+ operations(name: string): Promise<{
2597
+ operations: SubgraphOperationStatus[];
2598
+ }>;
2599
+ /** Status of a single operation (poll the `operationId` returned by
2600
+ * reindex/backfill/stop until `status` is terminal). */
2601
+ getOperation(name: string, operationId: string): Promise<SubgraphOperationStatus>;
2602
+ /** Create or update a subgraph. A deploy that needs a rebuild queues one;
2603
+ * if a reindex or backfill is already running the API answers 409 with
2604
+ * code `OPERATION_IN_PROGRESS` (an `ApiError`, not a dedicated class). */
2605
+ deploy(data: DeploySubgraphRequest): Promise<DeploySubgraphResponse>;
2606
+ getSource(name: string): Promise<SubgraphSource>;
2607
+ /**
2608
+ * Bundle a TypeScript subgraph source on the server. Used by the web chat
2609
+ * authoring loop so Vercel's serverless runtime doesn't have to run esbuild.
2610
+ */
2611
+ bundle(data: {
2612
+ code: string;
2613
+ }): Promise<BundleSubgraphResponse>;
2614
+ queryTable(name: string, table: string, params?: SubgraphQueryParams): Promise<unknown[]>;
2615
+ queryTableCount(name: string, table: string, params?: SubgraphQueryParams): Promise<{
2616
+ count: number;
2617
+ }>;
2618
+ queryTableAggregate(name: string, table: string, params?: SubgraphAggregateParams): Promise<SubgraphAggregateResponse>;
2619
+ /**
2620
+ * Returns a typed client for a subgraph defined with `defineSubgraph()`.
2621
+ * Row types are inferred from the subgraph's schema literal types.
2622
+ *
2623
+ * @example
2624
+ * ```ts
2625
+ * import mySubgraph from './subgraphs/my-token-subgraph'
2626
+ * const client = sl.subgraphs.typed(mySubgraph)
2627
+ * const rows = await client.transfers.findMany({ where: { sender: 'SP...' } })
2628
+ * // rows: InferTableRow<typeof mySubgraph.schema.transfers>[]
2629
+ * ```
2630
+ */
2631
+ typed<T extends {
2632
+ name: string;
2633
+ schema: Record<string, unknown>;
2634
+ }>(def: T): InferSubgraphClient<T>;
2635
+ /**
2636
+ * `columns` is the table's declared column set from `defineSubgraph()`.
2637
+ * Filters and orderBy always accept the canonical system names
2638
+ * `_id` / `_blockHeight` / `_txId` / `_createdAt`; the unprefixed
2639
+ * shorthands (`id`, `blockHeight`, ...) mean the system column only when
2640
+ * the table declares no column of that name.
2641
+ */
2642
+ private createTableClient;
2643
+ }
2620
2644
  import { CreateWebhookRequest, CreateWebhookResponse, DeadRow, DeliveryRow, ReplayResult, RotateSecretResponse, UpdateWebhookRequest, WebhookDetail, WebhookSummary, WebhookTestResult } from "@secondlayer/shared/schemas/webhooks";
2621
2645
  import { ChainTrigger, ChainTriggerType, CreateWebhookRequest as CreateWebhookRequest2, CreateWebhookResponse as CreateWebhookResponse2, DeadRow as DeadRow2, DeliveryRow as DeliveryRow2, ReplayResult as ReplayResult2, RotateSecretResponse as RotateSecretResponse2, WebhookDetail as WebhookDetail2, WebhookFormat, WebhookKind, WebhookRuntime, WebhookStatus, WebhookSummary as WebhookSummary2, WebhookTestResult as WebhookTestResult2, UpdateWebhookRequest as UpdateWebhookRequest2 } from "@secondlayer/shared/schemas/webhooks";
2622
2646
  import { trigger } from "@secondlayer/shared/schemas/webhooks";
@@ -2740,81 +2764,68 @@ declare class SecondLayer extends BaseClient {
2740
2764
  */
2741
2765
  context(): Promise<ContextSnapshot>;
2742
2766
  }
2767
+ import { InstanceDiagnosis as InstanceDiagnosis3, InstanceIssue, InstanceState, PublicStatus as PublicStatus2 } from "@secondlayer/shared/archive/instance-diagnosis";
2768
+ import { InferSubgraphClient as InferSubgraphClient2 } from "@secondlayer/subgraphs";
2743
2769
  /**
2744
2770
  * Returns a typed client for a subgraph defined with `defineSubgraph()`.
2745
2771
  *
2746
- * Accepts a plain options object, a `SecondLayer` instance, or a `Subgraphs` instance.
2747
- *
2748
- * @example
2749
- * ```ts
2750
- * import mySubgraph from './subgraphs/my-subgraph'
2751
- * import { getSubgraph } from '@secondlayer/sdk'
2752
- *
2753
- * const client = getSubgraph(mySubgraph, { apiKey: 'sl_...' })
2754
- * const rows = await client.transfers.findMany({ where: { sender: 'SP...' } })
2755
- * ```
2756
- */
2757
- declare function getSubgraph<T extends {
2758
- name: string;
2759
- schema: Record<string, unknown>;
2760
- }>(def: T, options?: Partial<SecondLayerOptions> | SecondLayer | Subgraphs): InferSubgraphClient2<T>;
2761
- type CreateStreamsClientOptions = {
2762
- apiKey?: string;
2763
- baseUrl?: string;
2764
- /** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */
2765
- origin?: "cli" | "mcp" | "session";
2766
- fetchImpl?: FetchLike2;
2767
- /**
2768
- * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required
2769
- * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.
2770
- */
2771
- dumpsBaseUrl?: string;
2772
- /**
2773
- * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE
2774
- * signature. Three states:
2775
- * - **default (omitted)** — *lenient*: verify when the server signs (the
2776
- * hosted API signs every response), and pass through when no signature is
2777
- * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).
2778
- * So verification is on by default against the hosted API without breaking
2779
- * unsigned self-host deployments. An *invalid* signature always throws.
2780
- * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing
2781
- * OR invalid signature throws `StreamsSignatureError`. Use this when you
2782
- * require a portable, non-repudiable attestation and won't accept unsigned
2783
- * data (it also closes the lenient mode's strip-the-header downgrade).
2784
- * - **`false`** — off.
2785
- *
2786
- * The key is fetched once from `/public/streams/signing-key` (cached; a
2787
- * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.
2788
- */
2789
- verify?: boolean | {
2790
- publicKey: string;
2791
- };
2792
- /**
2793
- * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`
2794
- * before trusting any file sha256 (default ON). Uses the same key source as
2795
- * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass
2796
- * `false` to opt out. A missing or invalid signature throws
2797
- * `StreamsSignatureError`.
2798
- */
2799
- verifyDumpsManifest?: boolean;
2800
- };
2801
- declare function createStreamsClient(options: CreateStreamsClientOptions): StreamsClient;
2802
- /**
2803
- * Decode a raw Streams event into the SAME flat, `event_type`-discriminated
2804
- * row shape Index serves — so Streams consumption reads identically to Index
2805
- * consumption, with one call instead of eleven guard+decode pairs.
2806
- *
2772
+ * Accepts a plain options object, a `SecondLayer` instance, or a `Subgraphs` instance.
2773
+ *
2774
+ * @example
2807
2775
  * ```ts
2808
- * for (const event of envelope.events) {
2809
- * const row = decode(event);
2810
- * if (row.event_type === "ft_transfer") row.amount; // string, narrowed
2811
- * }
2776
+ * import mySubgraph from './subgraphs/my-subgraph'
2777
+ * import { getSubgraph } from '@secondlayer/sdk'
2778
+ *
2779
+ * const client = getSubgraph(mySubgraph, { apiKey: 'sl_...' })
2780
+ * const rows = await client.transfers.findMany({ where: { sender: 'SP...' } })
2812
2781
  * ```
2782
+ */
2783
+ declare function getSubgraph<T extends {
2784
+ name: string;
2785
+ schema: Record<string, unknown>;
2786
+ }>(def: T, options?: Partial<SecondLayerOptions> | SecondLayer | Subgraphs): InferSubgraphClient2<T>;
2787
+ import { SubgraphAgentSchema as SubgraphAgentSchema3, SubgraphSpecFormat as SubgraphSpecFormat2, SubgraphSpecOptions as SubgraphSpecOptions3 } from "@secondlayer/shared/subgraphs/spec";
2788
+ /**
2789
+ * The two pieces every "deploy a consumer" guide leaves out, packaged:
2790
+ * a liveness endpoint and a graceful-shutdown signal. Both are
2791
+ * runtime-agnostic — the SDK never binds a port or assumes Bun/Node.
2792
+ */
2793
+ interface ConsumerHealth {
2794
+ /** Feed this to the consume loop's `onProgress` — it stamps arrival time
2795
+ * and keeps the latest progress ctx for the health body. */
2796
+ record: (ctx: ConsumerBatchContext) => void;
2797
+ /** Fetch-style handler for `GET /health`. Mount it on whatever serves
2798
+ * HTTP in your runtime:
2799
+ * `Bun.serve({ port, fetch: health.handler })` ·
2800
+ * `http.createServer(...)` via an adapter · a Workers route. */
2801
+ handler: (req: Request) => Response;
2802
+ }
2803
+ /**
2804
+ * Liveness for a consume loop. The gate is "did a page land recently", NOT
2805
+ * "are we near the tip": during a genesis backfill the loop is millions of
2806
+ * blocks behind and perfectly healthy, so lag can't be the signal. A wedged
2807
+ * loop stops reporting pages and flips to 503 — that's what platforms
2808
+ * should restart on. The body carries position for dashboards:
2809
+ * `blocks_behind` is the actual backlog (`tip - scanned_height`, ~0 for a
2810
+ * caught-up tail even on a quiet contract), while `last_delivered_height`
2811
+ * is the last DELIVERED row — its distance from the tip is event age, not
2812
+ * lag.
2813
+ */
2814
+ declare function consumerHealth(options?: {
2815
+ staleAfterMs?: number;
2816
+ }): ConsumerHealth;
2817
+ /**
2818
+ * An `AbortSignal` wired to SIGTERM/SIGINT (redeploys arrive as SIGTERM).
2819
+ * Pass it as the consume loop's `signal`: aborting is checked at the top of
2820
+ * the loop, never mid-batch, so the in-flight transaction — rows AND
2821
+ * checkpoint — always commits before the process exits. Nothing is
2822
+ * half-written; the next run resumes from exactly that cursor.
2813
2823
  *
2814
- * Prefer `decoded: true` on `streams.events.consume` — then decoding never
2815
- * appears in your code at all.
2824
+ * No-op (never fires) on runtimes without `process` signal handling.
2816
2825
  */
2817
- declare function decode(event: StreamsEvent): IndexEvent;
2826
+ declare function shutdownSignal(options?: {
2827
+ signals?: readonly ("SIGTERM" | "SIGINT")[];
2828
+ }): AbortSignal;
2818
2829
  /** Options accepted by every error in the family. */
2819
2830
  interface SecondLayerErrorOptions {
2820
2831
  cause?: Error;
@@ -2929,97 +2940,6 @@ declare class ArchiveGateNotConfiguredError extends SecondLayerError {
2929
2940
  }
2930
2941
  /** Parse a `Retry-After` header: delta-seconds or an HTTP-date. */
2931
2942
  declare function parseRetryAfter(value?: string | null): number | undefined;
2932
- /** Thrown on a 5xx from the Streams API, and on a failed signing-key fetch.
2933
- * `retryable`: the page retry policy tries again. */
2934
- declare class StreamsServerError extends ApiError {
2935
- constructor(message: string, status: number, body?: unknown, code?: string);
2936
- }
2937
- /** Thrown when response signature verification is enabled and fails. */
2938
- declare class StreamsSignatureError extends SecondLayerError {
2939
- constructor(message?: string);
2940
- }
2941
- import { decodeFtTransfer, isFtTransfer, decodeNftTransfer, isNftTransfer, decodeStxBurn, decodeStxLock, decodeStxMint, decodeStxTransfer, isStxBurn, isStxLock, isStxMint, isStxTransfer, decodeFtBurn, decodeFtMint, decodeNftBurn, decodeNftMint, isFtBurn, isFtMint, isNftBurn, isNftMint, decodePrint, isPrint } from "@secondlayer/shared/streams-rows";
2942
- import { DecodedEventColumns, DecodedEventRow, DecodedFtBurn, DecodedFtBurnPayload, DecodedFtMint, DecodedFtMintPayload, DecodedFtTransfer, DecodedFtTransferPayload, DecodedNftBurn, DecodedNftBurnPayload, DecodedNftMint, DecodedNftMintPayload, DecodedNftTransfer, DecodedNftTransferPayload, DecodedPrint, DecodedPrintPayload, DecodedPrintValue, DecodedStxBurn, DecodedStxBurnPayload, DecodedStxLock, DecodedStxLockPayload, DecodedStxMint, DecodedStxMintPayload, DecodedStxTransfer, DecodedStxTransferPayload, FtTransferEvent, FtTransferPayload as FtTransferPayload2, NftTransferEvent, NftTransferPayload as NftTransferPayload2 } from "@secondlayer/shared/streams-rows";
2943
- /**
2944
- * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string
2945
- * that marks a position in the event stream; treat the format as an
2946
- * implementation detail and go through these helpers instead of string-building
2947
- * it at call sites. Encode/decode and the rewind sentinel come from the
2948
- * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling
2949
- * the server would 400, or rewind to a different foot than Index/Streams.
2950
- */
2951
- declare const Cursor: {
2952
- /**
2953
- * Cursor at the foot of `height` — a position that sorts strictly below the
2954
- * first event of block `height` (`height:0`) and strictly above every event
2955
- * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so
2956
- * resuming from it re-reads the entire canonical run starting at `height:0`
2957
- * inclusive. This is the position to rewind to after a reorg whose fork point
2958
- * is `height`: the new canonical block at `height` carries a fresh first
2959
- * event at `(height, 0)` that the consumer MUST re-read.
2960
- *
2961
- * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural
2962
- * `${height}:0` — that earlier form was an off-by-one: being exclusive, it
2963
- * skipped `(height, 0)`, silently dropping the fork block's first row on
2964
- * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column
2965
- * type), larger than any real index, so nothing at `height - 1` survives the
2966
- * keyset and the next returned row is exactly `(height, 0)`.
2967
- *
2968
- * `atHeight(0)` is `null`: the pre-genesis position both consume loops
2969
- * accept as "read everything from the first event". There is no string
2970
- * cursor below `0:0`, and `0:0` itself is exclusive, so returning it here
2971
- * skipped the genesis event.
2972
- */
2973
- atHeight(height: number): string | null;
2974
- /** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */
2975
- parse(cursor: string): {
2976
- blockHeight: number;
2977
- eventIndex: number;
2978
- };
2979
- };
2980
- import { InstanceDiagnosis as InstanceDiagnosis3, InstanceIssue, InstanceState, PublicStatus as PublicStatus2 } from "@secondlayer/shared/archive/instance-diagnosis";
2981
- import { SubgraphAgentSchema as SubgraphAgentSchema3, SubgraphSpecFormat as SubgraphSpecFormat2, SubgraphSpecOptions as SubgraphSpecOptions3 } from "@secondlayer/shared/subgraphs/spec";
2982
- /**
2983
- * The two pieces every "deploy a consumer" guide leaves out, packaged:
2984
- * a liveness endpoint and a graceful-shutdown signal. Both are
2985
- * runtime-agnostic — the SDK never binds a port or assumes Bun/Node.
2986
- */
2987
- interface ConsumerHealth {
2988
- /** Feed this to the consume loop's `onProgress` — it stamps arrival time
2989
- * and keeps the latest progress ctx for the health body. */
2990
- record: (ctx: ConsumerBatchContext) => void;
2991
- /** Fetch-style handler for `GET /health`. Mount it on whatever serves
2992
- * HTTP in your runtime:
2993
- * `Bun.serve({ port, fetch: health.handler })` ·
2994
- * `http.createServer(...)` via an adapter · a Workers route. */
2995
- handler: (req: Request) => Response;
2996
- }
2997
- /**
2998
- * Liveness for a consume loop. The gate is "did a page land recently", NOT
2999
- * "are we near the tip": during a genesis backfill the loop is millions of
3000
- * blocks behind and perfectly healthy, so lag can't be the signal. A wedged
3001
- * loop stops reporting pages and flips to 503 — that's what platforms
3002
- * should restart on. The body carries position for dashboards:
3003
- * `blocks_behind` is the actual backlog (`tip - scanned_height`, ~0 for a
3004
- * caught-up tail even on a quiet contract), while `last_delivered_height`
3005
- * is the last DELIVERED row — its distance from the tip is event age, not
3006
- * lag.
3007
- */
3008
- declare function consumerHealth(options?: {
3009
- staleAfterMs?: number;
3010
- }): ConsumerHealth;
3011
- /**
3012
- * An `AbortSignal` wired to SIGTERM/SIGINT (redeploys arrive as SIGTERM).
3013
- * Pass it as the consume loop's `signal`: aborting is checked at the top of
3014
- * the loop, never mid-batch, so the in-flight transaction — rows AND
3015
- * checkpoint — always commits before the process exits. Nothing is
3016
- * half-written; the next run resumes from exactly that cursor.
3017
- *
3018
- * No-op (never fires) on runtimes without `process` signal handling.
3019
- */
3020
- declare function shutdownSignal(options?: {
3021
- signals?: readonly ("SIGTERM" | "SIGINT")[];
3022
- }): AbortSignal;
3023
2943
  type CreateArchiveClientOptions = {
3024
2944
  /** @deprecated Prefer `accountKey`. Kept one release as an alias. */
3025
2945
  apiKey?: string;
@@ -3188,5 +3108,110 @@ declare function verifySecondlayerSignature(rawBody: string, headers: WebhookHea
3188
3108
  */
3189
3109
  declare function decodeChainWebhook(rawBody: string): ChainWebhookDelivery;
3190
3110
  import { RewardSet as RewardSet2 } from "@secondlayer/shared/node/consensus";
3111
+ type CreateStreamsClientOptions = {
3112
+ apiKey?: string;
3113
+ baseUrl?: string;
3114
+ /** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */
3115
+ origin?: "cli" | "mcp" | "session";
3116
+ fetchImpl?: FetchLike2;
3117
+ /**
3118
+ * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required
3119
+ * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.
3120
+ */
3121
+ dumpsBaseUrl?: string;
3122
+ /**
3123
+ * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE
3124
+ * signature. Three states:
3125
+ * - **default (omitted)** — *lenient*: verify when the server signs (the
3126
+ * hosted API signs every response), and pass through when no signature is
3127
+ * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).
3128
+ * So verification is on by default against the hosted API without breaking
3129
+ * unsigned self-host deployments. An *invalid* signature always throws.
3130
+ * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing
3131
+ * OR invalid signature throws `StreamsSignatureError`. Use this when you
3132
+ * require a portable, non-repudiable attestation and won't accept unsigned
3133
+ * data (it also closes the lenient mode's strip-the-header downgrade).
3134
+ * - **`false`** — off.
3135
+ *
3136
+ * The key is fetched once from `/public/streams/signing-key` (cached; a
3137
+ * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.
3138
+ */
3139
+ verify?: boolean | {
3140
+ publicKey: string;
3141
+ };
3142
+ /**
3143
+ * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`
3144
+ * before trusting any file sha256 (default ON). Uses the same key source as
3145
+ * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass
3146
+ * `false` to opt out. A missing or invalid signature throws
3147
+ * `StreamsSignatureError`.
3148
+ */
3149
+ verifyDumpsManifest?: boolean;
3150
+ };
3151
+ declare function createStreamsClient(options: CreateStreamsClientOptions): StreamsClient;
3152
+ /**
3153
+ * Decode a raw Streams event into the SAME flat, `event_type`-discriminated
3154
+ * row shape Index serves — so Streams consumption reads identically to Index
3155
+ * consumption, with one call instead of eleven guard+decode pairs.
3156
+ *
3157
+ * ```ts
3158
+ * for (const event of envelope.events) {
3159
+ * const row = decode(event);
3160
+ * if (row.event_type === "ft_transfer") row.amount; // string, narrowed
3161
+ * }
3162
+ * ```
3163
+ *
3164
+ * Prefer `decoded: true` on `streams.events.consume` — then decoding never
3165
+ * appears in your code at all.
3166
+ */
3167
+ declare function decode(event: StreamsEvent): IndexEvent;
3168
+ /** Thrown on a 5xx from the Streams API, and on a failed signing-key fetch.
3169
+ * `retryable`: the page retry policy tries again. */
3170
+ declare class StreamsServerError extends ApiError {
3171
+ constructor(message: string, status: number, body?: unknown, code?: string);
3172
+ }
3173
+ /** Thrown when response signature verification is enabled and fails. */
3174
+ declare class StreamsSignatureError extends SecondLayerError {
3175
+ constructor(message?: string);
3176
+ }
3177
+ import { decodeFtTransfer, isFtTransfer, decodeNftTransfer, isNftTransfer, decodeStxBurn, decodeStxLock, decodeStxMint, decodeStxTransfer, isStxBurn, isStxLock, isStxMint, isStxTransfer, decodeFtBurn, decodeFtMint, decodeNftBurn, decodeNftMint, isFtBurn, isFtMint, isNftBurn, isNftMint, decodePrint, isPrint } from "@secondlayer/shared/streams-rows";
3178
+ import { DecodedEventColumns, DecodedEventRow, DecodedFtBurn, DecodedFtBurnPayload, DecodedFtMint, DecodedFtMintPayload, DecodedFtTransfer, DecodedFtTransferPayload, DecodedNftBurn, DecodedNftBurnPayload, DecodedNftMint, DecodedNftMintPayload, DecodedNftTransfer, DecodedNftTransferPayload, DecodedPrint, DecodedPrintPayload, DecodedPrintValue, DecodedStxBurn, DecodedStxBurnPayload, DecodedStxLock, DecodedStxLockPayload, DecodedStxMint, DecodedStxMintPayload, DecodedStxTransfer, DecodedStxTransferPayload, FtTransferEvent, FtTransferPayload as FtTransferPayload2, NftTransferEvent, NftTransferPayload as NftTransferPayload2 } from "@secondlayer/shared/streams-rows";
3179
+ /**
3180
+ * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string
3181
+ * that marks a position in the event stream; treat the format as an
3182
+ * implementation detail and go through these helpers instead of string-building
3183
+ * it at call sites. Encode/decode and the rewind sentinel come from the
3184
+ * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling
3185
+ * the server would 400, or rewind to a different foot than Index/Streams.
3186
+ */
3187
+ declare const Cursor: {
3188
+ /**
3189
+ * Cursor at the foot of `height` — a position that sorts strictly below the
3190
+ * first event of block `height` (`height:0`) and strictly above every event
3191
+ * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so
3192
+ * resuming from it re-reads the entire canonical run starting at `height:0`
3193
+ * inclusive. This is the position to rewind to after a reorg whose fork point
3194
+ * is `height`: the new canonical block at `height` carries a fresh first
3195
+ * event at `(height, 0)` that the consumer MUST re-read.
3196
+ *
3197
+ * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural
3198
+ * `${height}:0` — that earlier form was an off-by-one: being exclusive, it
3199
+ * skipped `(height, 0)`, silently dropping the fork block's first row on
3200
+ * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column
3201
+ * type), larger than any real index, so nothing at `height - 1` survives the
3202
+ * keyset and the next returned row is exactly `(height, 0)`.
3203
+ *
3204
+ * `atHeight(0)` is `null`: the pre-genesis position both consume loops
3205
+ * accept as "read everything from the first event". There is no string
3206
+ * cursor below `0:0`, and `0:0` itself is exclusive, so returning it here
3207
+ * skipped the genesis event.
3208
+ */
3209
+ atHeight(height: number): string | null;
3210
+ /** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */
3211
+ parse(cursor: string): {
3212
+ blockHeight: number;
3213
+ eventIndex: number;
3214
+ };
3215
+ };
3191
3216
  import { decodeClarityValue, toJsonSafe } from "@secondlayer/shared/streams-rows";
3192
- export { verifyWebhookSignature, verifyTransactionProof, verify as verifyStandardWebhooksHeaders, verifySecondlayerSignature, trigger, toJsonSafe, shutdownSignal, resolveBaseUrl, resolveApiKey, resolveAccountKey, parseRetryAfter, isStxTransfer, isStxMint, isStxLock, isStxBurn, isPrint, isNftTransfer, isNftMint, isNftBurn, isFtTransfer, isFtMint, isFtBurn, getSubgraph, fetchRewardSet, decodeStxTransfer, decodeStxMint, decodeStxLock, decodeStxBurn, decodePrint, decodeNftTransfer, decodeNftMint, decodeNftBurn, decodeFtTransfer, decodeFtMint, decodeFtBurn, decodeClarityValue, decodeChainWebhook, decode, createStreamsClient, createArchiveClient, contextField, consumerHealth, consumeIndexFeed, WithSinkTx, Webhooks, WebhookTestResult2 as WebhookTestResult, WebhookSummary2 as WebhookSummary, WebhookStatus, WebhookRuntime, WebhookKind, WebhookHeaderInput, WebhookFormat, WebhookDetail2 as WebhookDetail, WalkOptions, VmStreamsEvent, ValidationError, UpdateWebhookRequest2 as UpdateWebhookRequest, TransactionsWalkParams, TransactionsListParams, TransactionsEnvelope, TransactionProofVerifyResult, TransactionProof, TransactionEnvelope, Subgraphs, SubgraphSpecOptions3 as SubgraphSpecOptions, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphOperationStatus, SubgraphAgentSchema3 as SubgraphAgentSchema, StreamsWireEvent2 as StreamsWireEvent, StreamsTip, StreamsSubscription, StreamsSignatureError, StreamsServerError, StreamsReorgsListParams, StreamsReorgsListEnvelope, StreamsReorgContext, StreamsReorg, StreamsEventsSubscribeParams, StreamsEventsStreamParams, StreamsEventsListParams, StreamsEventsListEnvelope, StreamsEventsEnvelope, StreamsEventsConsumeResult, StreamsEventsConsumeParams, StreamsEventType, StreamsEventPayload, StreamsEvent, StreamsDumpsManifest, StreamsDumps, StreamsDumpFile, StreamsConsumeParams, StreamsClient, StreamsCanonicalBlock, StreamsBatchContext, StreamsBatch, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StackingWalkParams, StackingListParams, StackingEnvelope, SinkTx, SecondLayerOptions, SecondLayerErrorOptions, SecondLayerError, SecondLayerArchive, SecondLayer, SbtcWithdrawalsWalkParams, SbtcWithdrawalsListParams, SbtcWithdrawalsEnvelope, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalStatus, SbtcWithdrawalEvent, SbtcWithdrawalEnvelope, SbtcSummaryEnvelope, SbtcResource, SbtcEventsWalkParams, SbtcEventsListParams, SbtcEventsEnvelope, SbtcEventsConsumeParams, SbtcEventTopic2 as SbtcEventTopic, SbtcDepositsWalkParams, SbtcDepositsListParams, SbtcDepositsEnvelope, SbtcDepositsConsumeParams, SbtcDepositEvent, SbtcDepositEnvelope, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, RequestOptions, ReplayResult2 as ReplayResult, RateLimitError, PublicStatus2 as PublicStatus, PrintSchemaResponse, PoxResource, PoxCyclesWalkParams, PoxCyclesListParams, PoxCyclesEnvelope, PoxCycleEnvelope, Pox5Resource, Pox5EventsWalkParams, Pox5EventsListParams, Pox5EventsEnvelope, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload2 as NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, LoadedArchive, LOCAL_API_URL, InsufficientArchiveCreditsError, InstanceStatus, InstanceState, InstanceIssue, InstanceDiagnosis3 as InstanceDiagnosis, InstanceClient, IndexVarSet, IndexTransaction, IndexTip, IndexStxTransfer, IndexStxMint, IndexStxLock, IndexStxBurn, IndexStackingAction, IndexSbtcWithdrawalPhase, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawal, IndexSbtcSummary, IndexSbtcEvent, IndexSbtcDepositDetail, IndexSbtcDeposit, IndexReorg, IndexPrint, IndexPoxFunctionCount, IndexPoxCycle, IndexPox5EventTopic, IndexPox5Event, IndexPostCondition, IndexNftTransfer, IndexNftMint, IndexNftBurn, IndexNestedContractCall, IndexMempoolTransaction, IndexMapSet, IndexMapInsert, IndexMapDelete, IndexFtTransfer, IndexFtMint, IndexFtBurn, IndexFeedItem, IndexFeedFetcher, IndexFeedEnvelope, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEventOf, IndexEventFields, IndexEvent, IndexDiscovery, IndexContractCall, IndexConsumeOptions, IndexCanonicalBlock, IndexBlock, IndexAlwaysFields, Index, INSTANCE_TOKEN_ENV, INDEX_MAX_PAGE_SIZE, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload2 as FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, EventsConsumeParams, DeliveryRow2 as DeliveryRow, DecodedStxTransferPayload, DecodedStxTransfer, DecodedStxMintPayload, DecodedStxMint, DecodedStxLockPayload, DecodedStxLock, DecodedStxBurnPayload, DecodedStxBurn, DecodedPrintValue, DecodedPrintPayload, DecodedPrint, DecodedNftTransferPayload, DecodedNftTransfer, DecodedNftMintPayload, DecodedNftMint, DecodedNftBurnPayload, DecodedNftBurn, DecodedFtTransferPayload, DecodedFtTransfer, DecodedFtMintPayload, DecodedFtMint, DecodedFtBurnPayload, DecodedFtBurn, DecodedEventRow, DecodedEventColumns, DeadRow2 as DeadRow, DEFAULT_REQUEST_TIMEOUT_MS, Cursor, CreateWebhookResponse2 as CreateWebhookResponse, CreateWebhookRequest2 as CreateWebhookRequest, CreateArchiveClientOptions, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContractCallsConsumeParams, ContextSnapshot, ContextFieldError, ContextField, ContextAccount, ConsumerSink, ConsumerHealth, ConsumerBatchContext, ChainWebhookEnvelope, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainTxLevelEvent, ChainTriggerType, ChainTrigger, ChainTestDelivery, ChainStxTransferData, ChainStxMintData, ChainStxLockData, ChainStxBurnData, ChainReorgRollbackEnvelope, ChainReorgRollbackDelivery, ChainReorgOrphanedEntry, ChainPrintEventData, ChainNftTransferData, ChainNftMintData, ChainNftBurnData, ChainFtTransferData, ChainFtMintData, ChainFtBurnData, ChainEventEnvelope, ChainApplyEnvelopeOf, ChainApplyEnvelope, ChainApplyDeliveryOf, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ArchiveVerifyResult, ArchiveVerifyRangeStatus, ArchiveVerifyInput, ArchiveStatus, ArchiveSignatureError, ArchiveQuote, ArchivePartition, ArchiveManifest, ArchiveLoadOptions, ArchiveGateNotConfiguredError, ArchiveFlow, ArchiveFetchResult, ArchiveFetchItem, ArchiveDataset, ArchiveCreditsBalance, ArchiveClient, ArchiveAuthError, ApiError, ActiveSubgraphOperation, ACCOUNT_KEY_ENV };
3217
+ export { ACCOUNT_KEY_ENV, ActiveSubgraphOperation, ApiError, ArchiveAuthError, ArchiveClient, ArchiveCreditsBalance, ArchiveDataset, ArchiveFetchItem, ArchiveFetchResult, ArchiveFlow, ArchiveGateNotConfiguredError, ArchiveLoadOptions, ArchiveManifest, ArchivePartition, ArchiveQuote, ArchiveSignatureError, ArchiveStatus, ArchiveVerifyInput, ArchiveVerifyRangeStatus, ArchiveVerifyResult, AuthError, BlockEnvelope, BlocksEnvelope, BlocksListParams, BlocksWalkParams, CanonicalEnvelope, CanonicalListParams, CanonicalWalkParams, ChainApplyDeliveryOf, ChainApplyEnvelope, ChainApplyEnvelopeOf, ChainEventEnvelope, ChainFtBurnData, ChainFtMintData, ChainFtTransferData, ChainNftBurnData, ChainNftMintData, ChainNftTransferData, ChainPrintEventData, ChainReorgOrphanedEntry, ChainReorgRollbackDelivery, ChainReorgRollbackEnvelope, ChainStxBurnData, ChainStxLockData, ChainStxMintData, ChainStxTransferData, ChainTestDelivery, ChainTrigger, ChainTriggerType, ChainTxLevelEvent, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainWebhookEnvelope, ConsumerBatchContext, ConsumerHealth, ConsumerSink, ContextAccount, ContextField, ContextFieldError, ContextSnapshot, ContractCallsConsumeParams, ContractCallsEnvelope, ContractCallsListParams, ContractCallsWalkParams, ContractConformance, ContractSummary, Contracts, ContractsEnvelope, ContractsListParams, CreateArchiveClientOptions, CreateWebhookRequest2 as CreateWebhookRequest, CreateWebhookResponse2 as CreateWebhookResponse, Cursor, DEFAULT_REQUEST_TIMEOUT_MS, DeadRow2 as DeadRow, DecodedEventColumns, DecodedEventRow, DecodedFtBurn, DecodedFtBurnPayload, DecodedFtMint, DecodedFtMintPayload, DecodedFtTransfer, DecodedFtTransferPayload, DecodedNftBurn, DecodedNftBurnPayload, DecodedNftMint, DecodedNftMintPayload, DecodedNftTransfer, DecodedNftTransferPayload, DecodedPrint, DecodedPrintPayload, DecodedPrintValue, DecodedStxBurn, DecodedStxBurnPayload, DecodedStxLock, DecodedStxLockPayload, DecodedStxMint, DecodedStxMintPayload, DecodedStxTransfer, DecodedStxTransferPayload, DeliveryRow2 as DeliveryRow, EtagCache, EtagEntry, EventsConsumeParams, EventsEnvelope, EventsListParams, EventsWalkParams, FetchLike2 as FetchLike, FtTransfer, FtTransferEvent, FtTransferPayload2 as FtTransferPayload, FtTransfersEnvelope, FtTransfersListParams, FtTransfersResource, FtTransfersWalkParams, INDEX_MAX_PAGE_SIZE, INSTANCE_TOKEN_ENV, Index, IndexAlwaysFields, IndexBlock, IndexCanonicalBlock, IndexConsumeOptions, IndexContractCall, IndexDiscovery, IndexEvent, IndexEventFields, IndexEventOf, IndexEventType, IndexEventTypeFilters, IndexEventsResource, IndexFeedEnvelope, IndexFeedFetcher, IndexFeedItem, IndexFtBurn, IndexFtMint, IndexFtTransfer, IndexMapDelete, IndexMapInsert, IndexMapSet, IndexMempoolTransaction, IndexNestedContractCall, IndexNftBurn, IndexNftMint, IndexNftTransfer, IndexPostCondition, IndexPox5Event, IndexPox5EventTopic, IndexPoxCycle, IndexPoxFunctionCount, IndexPrint, IndexReorg, IndexSbtcDeposit, IndexSbtcDepositDetail, IndexSbtcEvent, IndexSbtcSummary, IndexSbtcWithdrawal, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawalPhase, IndexStackingAction, IndexStxBurn, IndexStxLock, IndexStxMint, IndexStxTransfer, IndexTip, IndexTransaction, IndexVarSet, InstanceClient, InstanceDiagnosis3 as InstanceDiagnosis, InstanceIssue, InstanceState, InstanceStatus, InsufficientArchiveCreditsError, LOCAL_API_URL, LoadedArchive, MemoryEtagCache, MempoolEnvelope, MempoolListParams, MempoolTransactionEnvelope, MempoolWalkParams, NftTransfer, NftTransferEvent, NftTransferPayload2 as NftTransferPayload, NftTransfersEnvelope, NftTransfersListParams, NftTransfersResource, NftTransfersWalkParams, Pox5EventsEnvelope, Pox5EventsListParams, Pox5EventsWalkParams, Pox5Resource, PoxCycleEnvelope, PoxCyclesEnvelope, PoxCyclesListParams, PoxCyclesWalkParams, PoxResource, PrintSchemaResponse, PublicStatus2 as PublicStatus, RateLimitError, ReplayResult2 as ReplayResult, RequestOptions, RewardSet2 as RewardSet, RotateSecretResponse2 as RotateSecretResponse, SbtcDepositEnvelope, SbtcDepositEvent, SbtcDepositsConsumeParams, SbtcDepositsEnvelope, SbtcDepositsListParams, SbtcDepositsWalkParams, SbtcEventTopic2 as SbtcEventTopic, SbtcEventsConsumeParams, SbtcEventsEnvelope, SbtcEventsListParams, SbtcEventsWalkParams, SbtcResource, SbtcSummaryEnvelope, SbtcWithdrawalEnvelope, SbtcWithdrawalEvent, SbtcWithdrawalStatus, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalsEnvelope, SbtcWithdrawalsListParams, SbtcWithdrawalsWalkParams, SecondLayer, SecondLayerArchive, SecondLayerError, SecondLayerErrorOptions, SecondLayerOptions, SinkTx, StackingEnvelope, StackingListParams, StackingWalkParams, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StreamsBatch, StreamsBatchContext, StreamsCanonicalBlock, StreamsClient, StreamsConsumeParams, StreamsDumpFile, StreamsDumps, StreamsDumpsManifest, StreamsEvent, StreamsEventPayload, StreamsEventType, StreamsEventsConsumeParams, StreamsEventsConsumeResult, StreamsEventsEnvelope, StreamsEventsListEnvelope, StreamsEventsListParams, StreamsEventsStreamParams, StreamsEventsSubscribeParams, StreamsReorg, StreamsReorgContext, StreamsReorgsListEnvelope, StreamsReorgsListParams, StreamsServerError, StreamsSignatureError, StreamsSubscription, StreamsTip, StreamsWireEvent2 as StreamsWireEvent, SubgraphAgentSchema3 as SubgraphAgentSchema, SubgraphOperationStatus, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphSpecOptions3 as SubgraphSpecOptions, Subgraphs, TransactionEnvelope, TransactionProof, TransactionProofVerifyResult, TransactionsEnvelope, TransactionsListParams, TransactionsWalkParams, UpdateWebhookRequest2 as UpdateWebhookRequest, ValidationError, VmStreamsEvent, WalkOptions, WebhookDetail2 as WebhookDetail, WebhookFormat, WebhookHeaderInput, WebhookKind, WebhookRuntime, WebhookStatus, WebhookSummary2 as WebhookSummary, WebhookTestResult2 as WebhookTestResult, Webhooks, WithSinkTx, consumeIndexFeed, consumerHealth, contextField, createArchiveClient, createStreamsClient, decode, decodeChainWebhook, decodeClarityValue, decodeFtBurn, decodeFtMint, decodeFtTransfer, decodeNftBurn, decodeNftMint, decodeNftTransfer, decodePrint, decodeStxBurn, decodeStxLock, decodeStxMint, decodeStxTransfer, fetchRewardSet, getSubgraph, isFtBurn, isFtMint, isFtTransfer, isNftBurn, isNftMint, isNftTransfer, isPrint, isStxBurn, isStxLock, isStxMint, isStxTransfer, parseRetryAfter, resolveAccountKey, resolveApiKey, resolveBaseUrl, shutdownSignal, toJsonSafe, trigger, verifySecondlayerSignature, verify as verifyStandardWebhooksHeaders, verifyTransactionProof, verifyWebhookSignature };