@secondlayer/shared 12.1.2 → 13.1.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/src/db/index.d.ts +1 -8
- package/dist/src/db/index.js +1 -5
- package/dist/src/db/index.js.map +3 -3
- package/dist/src/db/queries/chain-reorgs.js +1 -4
- package/dist/src/db/queries/chain-reorgs.js.map +3 -3
- package/dist/src/db/queries/instance.d.ts +12 -1
- package/dist/src/db/queries/instance.js +16 -1
- package/dist/src/db/queries/instance.js.map +3 -3
- package/dist/src/index-http.d.ts +71 -1
- package/dist/src/index-http.js +35 -1
- package/dist/src/index-http.js.map +3 -3
- package/dist/src/index.d.ts +3 -8
- package/dist/src/index.js +8 -6
- package/dist/src/index.js.map +4 -4
- package/dist/src/queue/listener.js +1 -4
- package/dist/src/queue/listener.js.map +3 -3
- package/dist/src/runtime/index.d.ts +2 -53
- package/dist/src/runtime/index.js +4 -73
- package/dist/src/runtime/index.js.map +4 -5
- package/dist/src/schemas/index.d.ts +2 -0
- package/dist/src/schemas/index.js +8 -2
- package/dist/src/schemas/index.js.map +3 -3
- package/dist/src/schemas/webhooks.d.ts +4 -1
- package/dist/src/schemas/webhooks.js +9 -2
- package/dist/src/schemas/webhooks.js.map +3 -3
- package/package.json +2 -2
|
@@ -62,15 +62,30 @@ function toInstance(row) {
|
|
|
62
62
|
created_at: row.created_at
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
|
+
async function hasNoLocalChain(db, opts = {}) {
|
|
66
|
+
const env = opts.env ?? process.env;
|
|
67
|
+
if (!env.SUBGRAPH_INDEX_API_URL)
|
|
68
|
+
return false;
|
|
69
|
+
const network = env.NETWORK ?? "mainnet";
|
|
70
|
+
const hasRow = opts.hasProgressRow ?? ((n) => hasLocalProgressRow(db, n));
|
|
71
|
+
return !await hasRow(network);
|
|
72
|
+
}
|
|
73
|
+
async function hasLocalProgressRow(db, network) {
|
|
74
|
+
const row = await db.selectFrom("index_progress").select("network").where("network", "=", network).executeTakeFirst().catch(() => {
|
|
75
|
+
return;
|
|
76
|
+
});
|
|
77
|
+
return row !== undefined;
|
|
78
|
+
}
|
|
65
79
|
export {
|
|
66
80
|
INSTANCE_NETWORKS,
|
|
67
81
|
InstanceNetworkMismatchError,
|
|
68
82
|
InvalidInstanceNetworkError,
|
|
69
83
|
ensureInstance,
|
|
70
84
|
getInstance,
|
|
85
|
+
hasNoLocalChain,
|
|
71
86
|
instanceNetworkFromEnv,
|
|
72
87
|
parseInstanceNetwork
|
|
73
88
|
};
|
|
74
89
|
|
|
75
|
-
//# debugId=
|
|
90
|
+
//# debugId=CD5DDEF4E82D8D8764756E2164756E21
|
|
76
91
|
//# sourceMappingURL=instance.js.map
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/db/queries/instance.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { Kysely } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? \"mainnet\");\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n"
|
|
5
|
+
"import type { Kysely } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? \"mainnet\");\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n\n/**\n * A stack with no local chain: it reads chain data from a hosted Index/Streams\n * API (`SUBGRAPH_INDEX_API_URL` set) and its own `index_progress` has no row\n * for this network (a hosted tenant). Derived, not configured: a self-hoster\n * running a local indexer has the row and keeps reading its own tables, even\n * with its processors pointed at its own api over HTTP.\n */\nexport async function hasNoLocalChain(\n\tdb: Kysely<Database>,\n\topts: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\thasProgressRow?: (network: string) => Promise<boolean>;\n\t} = {},\n): Promise<boolean> {\n\tconst env = opts.env ?? process.env;\n\tif (!env.SUBGRAPH_INDEX_API_URL) return false;\n\tconst network = env.NETWORK ?? \"mainnet\";\n\tconst hasRow =\n\t\topts.hasProgressRow ?? ((n: string) => hasLocalProgressRow(db, n));\n\treturn !(await hasRow(network));\n}\n\nasync function hasLocalProgressRow(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(\"network\")\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst()\n\t\t.catch(() => undefined);\n\treturn row !== undefined;\n}\n"
|
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UAAU,IAAI,WAAW;AAAA,EAC/B,MAAM,SACL,KAAK,mBAAmB,CAAC,MAAc,oBAAoB,IAAI,CAAC;AAAA,EACjE,OAAO,CAAE,MAAM,OAAO,OAAO;AAAA;AAG9B,eAAe,mBAAmB,CACjC,IACA,SACmB;AAAA,EACnB,MAAM,MAAM,MAAM,GAChB,WAAW,gBAAgB,EAC3B,OAAO,SAAS,EAChB,MAAM,WAAW,KAAK,OAAO,EAC7B,iBAAiB,EACjB,MAAM,MAAG;AAAA,IAAG;AAAA,GAAS;AAAA,EACvB,OAAO,QAAQ;AAAA;",
|
|
8
|
+
"debugId": "CD5DDEF4E82D8D8764756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/dist/src/index-http.d.ts
CHANGED
|
@@ -202,6 +202,62 @@ type IndexStateWriteRow = {
|
|
|
202
202
|
tx_contract_id?: string | null
|
|
203
203
|
tx_function_name?: string | null
|
|
204
204
|
};
|
|
205
|
+
/** A `/v1/index/sbtc/events` row: one decoded sBTC protocol event. Numeric
|
|
206
|
+
* columns are JSON numbers here (the API normalizes them). */
|
|
207
|
+
type IndexSbtcEventRow = {
|
|
208
|
+
cursor: string
|
|
209
|
+
block_height: number
|
|
210
|
+
block_time?: string | null
|
|
211
|
+
tx_id: string
|
|
212
|
+
tx_index: number
|
|
213
|
+
event_index: number
|
|
214
|
+
topic: string
|
|
215
|
+
request_id: number | null
|
|
216
|
+
amount: string | null
|
|
217
|
+
sender: string | null
|
|
218
|
+
recipient_btc_version: number | null
|
|
219
|
+
recipient_btc_hashbytes: string | null
|
|
220
|
+
bitcoin_txid: string | null
|
|
221
|
+
output_index: number | null
|
|
222
|
+
sweep_txid: string | null
|
|
223
|
+
burn_hash: string | null
|
|
224
|
+
burn_height: number | null
|
|
225
|
+
signer_bitmap: string | null
|
|
226
|
+
max_fee: string | null
|
|
227
|
+
fee: string | null
|
|
228
|
+
governance_contract_type: number | null
|
|
229
|
+
governance_new_contract: string | null
|
|
230
|
+
signer_aggregate_pubkey: string | null
|
|
231
|
+
signer_threshold: number | null
|
|
232
|
+
signer_address: string | null
|
|
233
|
+
signer_keys_count: number | null
|
|
234
|
+
};
|
|
235
|
+
/** A `/v1/contracts?trait=` row (ABI omitted). */
|
|
236
|
+
type IndexContractRow = {
|
|
237
|
+
contract_id: string
|
|
238
|
+
deployer: string
|
|
239
|
+
block_height: number
|
|
240
|
+
declared_traits: string[] | null
|
|
241
|
+
inferred_standards: string[] | null
|
|
242
|
+
abi_status: string
|
|
243
|
+
};
|
|
244
|
+
/** A `/v1/index/sbtc/withdrawals` row: one peg-out rolled up per request. */
|
|
245
|
+
type IndexSbtcWithdrawalRow = {
|
|
246
|
+
cursor: string
|
|
247
|
+
request_id: number
|
|
248
|
+
status: "REQUESTED" | "ACCEPTED" | "REJECTED"
|
|
249
|
+
amount: string | null
|
|
250
|
+
sender: string | null
|
|
251
|
+
recipient_btc_version: number | null
|
|
252
|
+
recipient_btc_hashbytes: string | null
|
|
253
|
+
sweep_txid: string | null
|
|
254
|
+
settlement_confirmed: boolean | null
|
|
255
|
+
btc_confirmations: number | null
|
|
256
|
+
btc_block_height: number | null
|
|
257
|
+
confirmed_at: string | null
|
|
258
|
+
requested_at?: string | null
|
|
259
|
+
resolved_at?: string | null
|
|
260
|
+
};
|
|
205
261
|
type StreamsReorgRow = {
|
|
206
262
|
id: string
|
|
207
263
|
detected_at: string
|
|
@@ -285,6 +341,20 @@ declare class IndexHttpClient {
|
|
|
285
341
|
/** Lowest height the Index serves `state_writes` for, or null when it has
|
|
286
342
|
* none (its node does not deliver them). One row. */
|
|
287
343
|
firstStateWriteHeight(): Promise<number | null>;
|
|
344
|
+
/**
|
|
345
|
+
* Canonical sBTC protocol events over [fromHeight, toHeight] for `topics`,
|
|
346
|
+
* ordered by (block_height, event_index). One drained walk per topic (the
|
|
347
|
+
* endpoint filters on a single topic); `requestId` narrows each walk.
|
|
348
|
+
*/
|
|
349
|
+
fetchSbtcEvents(fromHeight: number, toHeight: number, topics: readonly string[], opts?: {
|
|
350
|
+
requestId?: number
|
|
351
|
+
}): Promise<IndexSbtcEventRow[]>;
|
|
352
|
+
/** Every canonical contract conforming to `trait` (declared or inferred),
|
|
353
|
+
* draining `/v1/contracts`'s `next_cursor`. */
|
|
354
|
+
listContractsByTrait(trait: string): Promise<IndexContractRow[]>;
|
|
355
|
+
/** Withdrawals whose BTC sweep crossed the confirmation threshold strictly
|
|
356
|
+
* after `confirmedAfter`, across all history. */
|
|
357
|
+
fetchSettledWithdrawals(confirmedAfter: Date): Promise<IndexSbtcWithdrawalRow[]>;
|
|
288
358
|
walkTransactions(fromHeight: number, toHeight: number): Promise<IndexTransactionRow[]>;
|
|
289
359
|
/** Canonical tip height from the Streams clock. */
|
|
290
360
|
getStreamsTip(): Promise<number>;
|
|
@@ -369,4 +439,4 @@ declare class IndexHttpClient {
|
|
|
369
439
|
}
|
|
370
440
|
/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */
|
|
371
441
|
declare function createInternalIndexHttpClient(): IndexHttpClient;
|
|
372
|
-
export { BillingPausedCode, BillingPausedError, IndexBlockRow, IndexEventRow, IndexHttpClient, IndexHttpOptions, IndexHttpStatusError, IndexStateWriteRow, IndexTipEnvelope, IndexTransactionRow, MAX_INDEX_WAIT_SECONDS, StreamsReorgRow, createInternalIndexHttpClient };
|
|
442
|
+
export { BillingPausedCode, BillingPausedError, IndexBlockRow, IndexContractRow, IndexEventRow, IndexHttpClient, IndexHttpOptions, IndexHttpStatusError, IndexSbtcEventRow, IndexSbtcWithdrawalRow, IndexStateWriteRow, IndexTipEnvelope, IndexTransactionRow, MAX_INDEX_WAIT_SECONDS, StreamsReorgRow, createInternalIndexHttpClient };
|
package/dist/src/index-http.js
CHANGED
|
@@ -78,6 +78,8 @@ function billingPausedFrom(status, body, message) {
|
|
|
78
78
|
} catch {}
|
|
79
79
|
return null;
|
|
80
80
|
}
|
|
81
|
+
var CONTRACTS_PAGE_LIMIT = 500;
|
|
82
|
+
var THROUGH_TIP = Number.MAX_SAFE_INTEGER;
|
|
81
83
|
|
|
82
84
|
class IndexHttpClient {
|
|
83
85
|
indexBaseUrl;
|
|
@@ -189,6 +191,38 @@ class IndexHttpClient {
|
|
|
189
191
|
const { items } = await this.getPage("/v1/index/state-writes", "state_writes", new URLSearchParams({ from_height: "0", limit: "1" }));
|
|
190
192
|
return items[0]?.block_height ?? null;
|
|
191
193
|
}
|
|
194
|
+
async fetchSbtcEvents(fromHeight, toHeight, topics, opts) {
|
|
195
|
+
const out = [];
|
|
196
|
+
for (const topic of topics) {
|
|
197
|
+
out.push(...await this.walk("/v1/index/sbtc/events", "events", fromHeight, toHeight, {
|
|
198
|
+
topic,
|
|
199
|
+
...opts?.requestId !== undefined ? { request_id: String(opts.requestId) } : {}
|
|
200
|
+
}));
|
|
201
|
+
}
|
|
202
|
+
return out.sort((a, b) => a.block_height - b.block_height || a.event_index - b.event_index);
|
|
203
|
+
}
|
|
204
|
+
async listContractsByTrait(trait) {
|
|
205
|
+
const out = [];
|
|
206
|
+
let cursor = null;
|
|
207
|
+
do {
|
|
208
|
+
const params = new URLSearchParams({
|
|
209
|
+
trait,
|
|
210
|
+
limit: String(CONTRACTS_PAGE_LIMIT)
|
|
211
|
+
});
|
|
212
|
+
if (cursor)
|
|
213
|
+
params.set("cursor", cursor);
|
|
214
|
+
const { items, next_cursor } = await this.getPage("/v1/contracts", "contracts", params);
|
|
215
|
+
out.push(...items);
|
|
216
|
+
cursor = next_cursor;
|
|
217
|
+
} while (cursor);
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
fetchSettledWithdrawals(confirmedAfter) {
|
|
221
|
+
return this.walk("/v1/index/sbtc/withdrawals", "withdrawals", 0, THROUGH_TIP, {
|
|
222
|
+
settlement_confirmed: "true",
|
|
223
|
+
confirmed_after: confirmedAfter.toISOString()
|
|
224
|
+
});
|
|
225
|
+
}
|
|
192
226
|
walkTransactions(fromHeight, toHeight) {
|
|
193
227
|
return this.walk("/v1/index/transactions", "transactions", fromHeight, toHeight);
|
|
194
228
|
}
|
|
@@ -283,5 +317,5 @@ export {
|
|
|
283
317
|
createInternalIndexHttpClient
|
|
284
318
|
};
|
|
285
319
|
|
|
286
|
-
//# debugId=
|
|
320
|
+
//# debugId=E54A5375EB1771BD64756E2164756E21
|
|
287
321
|
//# sourceMappingURL=index-http.js.map
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../src/index-internal-auth.ts", "../src/index-http.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"// Internal service credentials for first-party consumers of /v1/index and\n// /v1/streams over HTTP (decoder, subgraph processor PublicApiBlockSource).\n// Seeded as internal tenants with NO account_id, so these reads are\n// unmetered (metering gates on account_id). Lives in shared so the API (seed)\n// and the consumers import it without a cycle.\n//\n// Resolution: STREAMS_INTERNAL_API_KEY / INDEX_INTERNAL_API_KEY, then\n// INSTANCE_TOKEN (OSS). No committed fallback. Empty-string env values fall\n// through (`trim()`, then empty): compose interpolates\n// `${STREAMS_INTERNAL_API_KEY:-}` which is \"\" when unset.\n//\n// Archive keys must not use the `sk-sl_` prefix; generate with `sl-int_`.\n// OSS compose should omit the internal env and send INSTANCE_TOKEN.\nexport const INDEX_INTERNAL_TENANT_ID = \"tenant_index_internal\";\nexport const INTERNAL_STREAMS_TENANT_ID = \"tenant_streams_decode_internal\";\n\nconst DEFAULT_INTERNAL_INDEX_BASE_URL = \"http://api:3800\";\n\nconst MISSING_INTERNAL_STREAMS_API_KEY =\n\t\"Set STREAMS_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Empty env no longer falls back to a committed secret.\";\n\nconst MISSING_INTERNAL_INDEX_API_KEY =\n\t\"Set INDEX_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Without one, Index reads carry no credential and platform mode 401s every one of them.\";\n\nexport function defaultInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.INDEX_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\nexport function defaultInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.STREAMS_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\n/**\n * Platform-mode Index consumer: refuse to run with neither credential.\n *\n * Platform mode requires a credential on every Index read (a keyless read\n * 401s, `api/src/index/auth.ts`) — a first-party consumer with no internal\n * key would fail every request at call time. Fail here at startup instead.\n *\n * Self-hosted (oss/dedicated) instances are not gated, so they must NOT call\n * this — `defaultInternalIndexApiKey()` returning undefined is correct there.\n */\nexport function requireInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalIndexApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_INDEX_API_KEY);\n\treturn key;\n}\n\n/** Decoder startup: refuse to run with neither credential. */\nexport function requireInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalStreamsApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_STREAMS_API_KEY);\n\treturn key;\n}\n\n/** Shared env contract for decoder + subgraph HTTP dogfood. */\nexport function defaultInternalIndexBaseUrl(): string {\n\treturn (\n\t\tprocess.env.SUBGRAPH_INDEX_API_URL ||\n\t\tprocess.env.STREAMS_API_URL ||\n\t\tDEFAULT_INTERNAL_INDEX_BASE_URL\n\t);\n}\n",
|
|
6
|
-
"import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\n/** The two refusals a metered read can get once an account is past its free\n * allowance (`checkRowsAllowance`). Both are deliberate billing states, not\n * outages: retrying them in a storm only burns the request budget. */\nexport type BillingPausedCode = \"spend_cap_reached\" | \"insufficient_credits\";\n\nconst BILLING_PAUSED_CODES: ReadonlySet<string> = new Set<BillingPausedCode>([\n\t\"spend_cap_reached\",\n\t\"insufficient_credits\",\n]);\n\n/** A read refused with `402` and `{ error: \"spend_cap_reached\" |\n * \"insufficient_credits\" }`. Raised only on an exact body match, so an\n * unmetered (self-host) server never produces it. */\nexport class BillingPausedError extends IndexHttpStatusError {\n\tconstructor(\n\t\treadonly code: BillingPausedCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(402, message);\n\t\tthis.name = \"BillingPausedError\";\n\t}\n}\n\n/** `BillingPausedError` when `status`/`body` is exactly a billing refusal. */\nfunction billingPausedFrom(\n\tstatus: number,\n\tbody: string,\n\tmessage: string,\n): BillingPausedError | null {\n\tif (status !== 402) return null;\n\ttry {\n\t\tconst code = (JSON.parse(body) as { error?: unknown } | null)?.error;\n\t\tif (typeof code === \"string\" && BILLING_PAUSED_CODES.has(code)) {\n\t\t\treturn new BillingPausedError(code as BillingPausedCode, message);\n\t\t}\n\t} catch {\n\t\t// Not JSON: not a billing refusal.\n\t}\n\treturn null;\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\n/** A `/v1/index/state-writes` row read with `tx_context=true`. */\nexport type IndexStateWriteRow = {\n\tblock_height: number;\n\tordinal: number;\n\t/** Null for block-level writes. */\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\ttx_id?: string | null;\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst body = await res.text();\n\t\t\t\tconst message = `GET ${url} → ${res.status} ${body}`;\n\t\t\t\tthrow (\n\t\t\t\t\tbillingPausedFrom(res.status, body, message) ??\n\t\t\t\t\tnew IndexHttpStatusError(res.status, message)\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t\t/** Scope the walk to one contract (what a filter pins), so the Index\n\t\t * returns, and meters, only that contract's rows. */\n\t\tcontractId?: string,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Every node storage write over the range, each with its writing tx\n\t * (`tx_context=true`); scoped to one contract's keys when given. */\n\twalkStateWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<IndexStateWriteRow[]> {\n\t\treturn this.walk<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\ttx_context: \"true\",\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Lowest height the Index serves `state_writes` for, or null when it has\n\t * none (its node does not deliver them). One row. */\n\tasync firstStateWriteHeight(): Promise<number | null> {\n\t\tconst { items } = await this.getPage<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tnew URLSearchParams({ from_height: \"0\", limit: \"1\" }),\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
|
|
6
|
+
"import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\n/** The two refusals a metered read can get once an account is past its free\n * allowance (`checkRowsAllowance`). Both are deliberate billing states, not\n * outages: retrying them in a storm only burns the request budget. */\nexport type BillingPausedCode = \"spend_cap_reached\" | \"insufficient_credits\";\n\nconst BILLING_PAUSED_CODES: ReadonlySet<string> = new Set<BillingPausedCode>([\n\t\"spend_cap_reached\",\n\t\"insufficient_credits\",\n]);\n\n/** A read refused with `402` and `{ error: \"spend_cap_reached\" |\n * \"insufficient_credits\" }`. Raised only on an exact body match, so an\n * unmetered (self-host) server never produces it. */\nexport class BillingPausedError extends IndexHttpStatusError {\n\tconstructor(\n\t\treadonly code: BillingPausedCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(402, message);\n\t\tthis.name = \"BillingPausedError\";\n\t}\n}\n\n/** `BillingPausedError` when `status`/`body` is exactly a billing refusal. */\nfunction billingPausedFrom(\n\tstatus: number,\n\tbody: string,\n\tmessage: string,\n): BillingPausedError | null {\n\tif (status !== 402) return null;\n\ttry {\n\t\tconst code = (JSON.parse(body) as { error?: unknown } | null)?.error;\n\t\tif (typeof code === \"string\" && BILLING_PAUSED_CODES.has(code)) {\n\t\t\treturn new BillingPausedError(code as BillingPausedCode, message);\n\t\t}\n\t} catch {\n\t\t// Not JSON: not a billing refusal.\n\t}\n\treturn null;\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\n/** A `/v1/index/state-writes` row read with `tx_context=true`. */\nexport type IndexStateWriteRow = {\n\tblock_height: number;\n\tordinal: number;\n\t/** Null for block-level writes. */\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\ttx_id?: string | null;\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\n/** A `/v1/index/sbtc/events` row: one decoded sBTC protocol event. Numeric\n * columns are JSON numbers here (the API normalizes them). */\nexport type IndexSbtcEventRow = {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: string;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tbitcoin_txid: string | null;\n\toutput_index: number | null;\n\tsweep_txid: string | null;\n\tburn_hash: string | null;\n\tburn_height: number | null;\n\tsigner_bitmap: string | null;\n\tmax_fee: string | null;\n\tfee: string | null;\n\tgovernance_contract_type: number | null;\n\tgovernance_new_contract: string | null;\n\tsigner_aggregate_pubkey: string | null;\n\tsigner_threshold: number | null;\n\tsigner_address: string | null;\n\tsigner_keys_count: number | null;\n};\n\n/** A `/v1/contracts?trait=` row (ABI omitted). */\nexport type IndexContractRow = {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tdeclared_traits: string[] | null;\n\tinferred_standards: string[] | null;\n\tabi_status: string;\n};\n\n/** A `/v1/index/sbtc/withdrawals` row: one peg-out rolled up per request. */\nexport type IndexSbtcWithdrawalRow = {\n\tcursor: string;\n\trequest_id: number;\n\tstatus: \"REQUESTED\" | \"ACCEPTED\" | \"REJECTED\";\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tsweep_txid: string | null;\n\tsettlement_confirmed: boolean | null;\n\tbtc_confirmations: number | null;\n\tbtc_block_height: number | null;\n\tconfirmed_at: string | null;\n\trequested_at?: string | null;\n\tresolved_at?: string | null;\n};\n\n/** Page size for `/v1/contracts`, its server-side maximum. */\nconst CONTRACTS_PAGE_LIMIT = 500;\n\n/** `to_height` meaning \"through the tip\": the server clamps it to its tip. */\nconst THROUGH_TIP = Number.MAX_SAFE_INTEGER;\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst body = await res.text();\n\t\t\t\tconst message = `GET ${url} → ${res.status} ${body}`;\n\t\t\t\tthrow (\n\t\t\t\t\tbillingPausedFrom(res.status, body, message) ??\n\t\t\t\t\tnew IndexHttpStatusError(res.status, message)\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t\t/** Scope the walk to one contract (what a filter pins), so the Index\n\t\t * returns, and meters, only that contract's rows. */\n\t\tcontractId?: string,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Every node storage write over the range, each with its writing tx\n\t * (`tx_context=true`); scoped to one contract's keys when given. */\n\twalkStateWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<IndexStateWriteRow[]> {\n\t\treturn this.walk<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\ttx_context: \"true\",\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Lowest height the Index serves `state_writes` for, or null when it has\n\t * none (its node does not deliver them). One row. */\n\tasync firstStateWriteHeight(): Promise<number | null> {\n\t\tconst { items } = await this.getPage<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tnew URLSearchParams({ from_height: \"0\", limit: \"1\" }),\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\t/**\n\t * Canonical sBTC protocol events over [fromHeight, toHeight] for `topics`,\n\t * ordered by (block_height, event_index). One drained walk per topic (the\n\t * endpoint filters on a single topic); `requestId` narrows each walk.\n\t */\n\tasync fetchSbtcEvents(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\ttopics: readonly string[],\n\t\topts?: { requestId?: number },\n\t): Promise<IndexSbtcEventRow[]> {\n\t\tconst out: IndexSbtcEventRow[] = [];\n\t\tfor (const topic of topics) {\n\t\t\tout.push(\n\t\t\t\t...(await this.walk<\"events\", IndexSbtcEventRow>(\n\t\t\t\t\t\"/v1/index/sbtc/events\",\n\t\t\t\t\t\"events\",\n\t\t\t\t\tfromHeight,\n\t\t\t\t\ttoHeight,\n\t\t\t\t\t{\n\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t...(opts?.requestId !== undefined\n\t\t\t\t\t\t\t? { request_id: String(opts.requestId) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t)),\n\t\t\t);\n\t\t}\n\t\treturn out.sort(\n\t\t\t(a, b) =>\n\t\t\t\ta.block_height - b.block_height || a.event_index - b.event_index,\n\t\t);\n\t}\n\n\t/** Every canonical contract conforming to `trait` (declared or inferred),\n\t * draining `/v1/contracts`'s `next_cursor`. */\n\tasync listContractsByTrait(trait: string): Promise<IndexContractRow[]> {\n\t\tconst out: IndexContractRow[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\ttrait,\n\t\t\t\tlimit: String(CONTRACTS_PAGE_LIMIT),\n\t\t\t});\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\t\"contracts\",\n\t\t\t\tIndexContractRow\n\t\t\t>(\"/v1/contracts\", \"contracts\", params);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/** Withdrawals whose BTC sweep crossed the confirmation threshold strictly\n\t * after `confirmedAfter`, across all history. */\n\tfetchSettledWithdrawals(\n\t\tconfirmedAfter: Date,\n\t): Promise<IndexSbtcWithdrawalRow[]> {\n\t\treturn this.walk<\"withdrawals\", IndexSbtcWithdrawalRow>(\n\t\t\t\"/v1/index/sbtc/withdrawals\",\n\t\t\t\"withdrawals\",\n\t\t\t0,\n\t\t\tTHROUGH_TIP,\n\t\t\t{\n\t\t\t\tsettlement_confirmed: \"true\",\n\t\t\t\tconfirmed_after: confirmedAfter.toISOString(),\n\t\t\t},\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";AAaO,IAAM,2BAA2B;AACjC,IAAM,6BAA6B;AAE1C,IAAM,kCAAkC;AAExC,IAAM,mCACL;AAED,IAAM,iCACL;AAEM,SAAS,0BAA0B,CACzC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,IACxC,eAAe,6BAA6B;AAAA,EAC7C,CAAC;AAAA;",
|
|
9
|
+
"debugId": "E54A5375EB1771BD64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -2537,13 +2537,6 @@ declare function getDb(connectionString?: string): Kysely<Database>;
|
|
|
2537
2537
|
* Defaults to the target role (tenant schemas live in the target DB).
|
|
2538
2538
|
*/
|
|
2539
2539
|
declare function getRawClient(role?: "source" | "target"): ReturnType<typeof postgres>;
|
|
2540
|
-
/**
|
|
2541
|
-
* Raw postgres.js client for an arbitrary connection string (cached by URL).
|
|
2542
|
-
* Used by the CLI setup-wizard and similar one-off tooling. Distinct from
|
|
2543
|
-
* {@link getRawClient}, which only knows the source/target roles resolved
|
|
2544
|
-
* from env.
|
|
2545
|
-
*/
|
|
2546
|
-
declare function getRawClientFor(url: string): ReturnType<typeof postgres>;
|
|
2547
2540
|
/** Close all DB connection pools. Call in CLI commands to allow process exit. */
|
|
2548
2541
|
declare function closeDb(): Promise<void>;
|
|
2549
2542
|
/**
|
|
@@ -2795,6 +2788,8 @@ type ChainTrigger = {
|
|
|
2795
2788
|
type: "print_event"
|
|
2796
2789
|
contractId?: string
|
|
2797
2790
|
topic?: string
|
|
2791
|
+
/** Equality on top-level keys of the decoded print tuple; array = any-of, keys AND. */
|
|
2792
|
+
where?: Record<string, string | readonly string[]>
|
|
2798
2793
|
} & TraitScoped) | ({
|
|
2799
2794
|
type: "nested_contract_call"
|
|
2800
2795
|
contractId?: string
|
|
@@ -3425,4 +3420,4 @@ declare function publicKeyPemFromPrivate(privateKeyPem: string): string;
|
|
|
3425
3420
|
declare function ed25519KeyId(publicKeyPem: string): string;
|
|
3426
3421
|
declare function signEd25519(payload: string, privateKey: KeyObject): string;
|
|
3427
3422
|
declare function verifyEd25519(payload: string, signatureBase64: string, publicKey: KeyObject): boolean;
|
|
3428
|
-
export { Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeysTable, ArchiveFetch, ArchiveFetchesTable, AuthenticationError, AuthorizationError, BILLING_PAUSED_PREFIX, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, CHAIN_TRIGGER_FIELDS, CHAIN_TRIGGER_TYPES, CODE_TO_STATUS, ChainApplyDeliveryOf, ChainApplyEnvelope, ChainApplyEnvelopeOf, ChainEventEnvelope, ChainFtBurnData, ChainFtMintData, ChainFtTransferData, ChainNftBurnData, ChainNftMintData, ChainNftTransferData, ChainPrintEventData, ChainReadCacheTable, ChainReorgOrphanedEntry, ChainReorgRollbackDelivery, ChainReorgRollbackEnvelope, ChainReorgsTable, ChainStxBurnData, ChainStxLockData, ChainStxMintData, ChainStxTransferData, ChainTestDelivery, ChainTxLevelEvent, ChainWebhookDelivery, ChainWebhookEnvelope, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, CreateWebhookRequest, CreateWebhookRequestSchema, CreateWebhookResponse, DB_TO_STREAMS_EVENT_TYPE, DECODED_EVENT_TYPES2 as DECODED_EVENT_TYPES, DEFAULT_BTC_CONFIRMATIONS, Database, DatabaseError, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, ForbiddenError, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, RUNE_EVENT_TYPES, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, RuneApplyDeliveryOf, RuneApplyEnvelope, RuneEventType, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, StreamsCursor, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphSummary, SubgraphSyncInfo, SubgraphVerification, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSubgraph, UpdateSubgraphOperation, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UpdateWebhookRequest, UpdateWebhookRequestSchema, UsageLedgerRow, UsageLedgerTable, VM_EVENT_TYPES, VM_NODE_TO_STORED_TYPE2 as VM_NODE_TO_STORED_TYPE, VM_STORED_TO_NODE_TYPE, ValidationError, VersionConflictError, VmEvent, VmEventType, VmEventsArchiveTable, VmEventsTable, VmNodeEventType, WEBHOOK_FORMATS, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDetail, WebhookFormat, WebhookFormatSchema, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, billingPausedCode, blockEndCursor, closeDb, closeDbOrTimeout, committedHeight, compareStreamsCursor, exports_hmac as crypto, decodeStreamsCursor, describeDbUrl, exports_ed25519 as ed25519, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient,
|
|
3423
|
+
export { Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeysTable, ArchiveFetch, ArchiveFetchesTable, AuthenticationError, AuthorizationError, BILLING_PAUSED_PREFIX, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, CHAIN_TRIGGER_FIELDS, CHAIN_TRIGGER_TYPES, CODE_TO_STATUS, ChainApplyDeliveryOf, ChainApplyEnvelope, ChainApplyEnvelopeOf, ChainEventEnvelope, ChainFtBurnData, ChainFtMintData, ChainFtTransferData, ChainNftBurnData, ChainNftMintData, ChainNftTransferData, ChainPrintEventData, ChainReadCacheTable, ChainReorgOrphanedEntry, ChainReorgRollbackDelivery, ChainReorgRollbackEnvelope, ChainReorgsTable, ChainStxBurnData, ChainStxLockData, ChainStxMintData, ChainStxTransferData, ChainTestDelivery, ChainTxLevelEvent, ChainWebhookDelivery, ChainWebhookEnvelope, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, CreateWebhookRequest, CreateWebhookRequestSchema, CreateWebhookResponse, DB_TO_STREAMS_EVENT_TYPE, DECODED_EVENT_TYPES2 as DECODED_EVENT_TYPES, DEFAULT_BTC_CONFIRMATIONS, Database, DatabaseError, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, ForbiddenError, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, RUNE_EVENT_TYPES, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, RuneApplyDeliveryOf, RuneApplyEnvelope, RuneEventType, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, StreamsCursor, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphSummary, SubgraphSyncInfo, SubgraphVerification, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSubgraph, UpdateSubgraphOperation, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UpdateWebhookRequest, UpdateWebhookRequestSchema, UsageLedgerRow, UsageLedgerTable, VM_EVENT_TYPES, VM_NODE_TO_STORED_TYPE2 as VM_NODE_TO_STORED_TYPE, VM_STORED_TO_NODE_TYPE, ValidationError, VersionConflictError, VmEvent, VmEventType, VmEventsArchiveTable, VmEventsTable, VmNodeEventType, WEBHOOK_FORMATS, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDetail, WebhookFormat, WebhookFormatSchema, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, billingPausedCode, blockEndCursor, closeDb, closeDbOrTimeout, committedHeight, compareStreamsCursor, exports_hmac as crypto, decodeStreamsCursor, describeDbUrl, exports_ed25519 as ed25519, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient, getSourceDb, getTargetDb, isBnsDecoderEnabled, isEmptyRangeCursor, isPox4DecoderEnabled, isPox5DecoderEnabled, isSbtcDecoderEnabled, jsonb, logger, onChainPlane, onControlPlane, parseJsonb, resolveSourceUrl, resolveTargetUrl, setMigrationRole, sql };
|
package/dist/src/index.js
CHANGED
|
@@ -1034,9 +1034,6 @@ function getRawClient(role = "target") {
|
|
|
1034
1034
|
const url = role === "source" ? resolveSourceUrl() : resolveTargetUrl();
|
|
1035
1035
|
return getOrCreatePool(url).rawClient;
|
|
1036
1036
|
}
|
|
1037
|
-
function getRawClientFor(url) {
|
|
1038
|
-
return getOrCreatePool(url).rawClient;
|
|
1039
|
-
}
|
|
1040
1037
|
async function closeDb() {
|
|
1041
1038
|
for (const entry of pools.values()) {
|
|
1042
1039
|
await entry.db.destroy();
|
|
@@ -1349,6 +1346,11 @@ var triggerAmount = z3.union([
|
|
|
1349
1346
|
]);
|
|
1350
1347
|
var triggerPattern = z3.string().trim().min(1);
|
|
1351
1348
|
var trait = z3.string().trim().min(1);
|
|
1349
|
+
var printWhereValue = z3.string().min(1).max(256);
|
|
1350
|
+
var PrintWhereSchema = z3.record(z3.string().trim().min(1).max(64), z3.union([printWhereValue, z3.array(printWhereValue).min(1).max(20)])).refine((o) => {
|
|
1351
|
+
const n = Object.keys(o).length;
|
|
1352
|
+
return n >= 1 && n <= 10;
|
|
1353
|
+
}, "where takes 1 to 10 keys");
|
|
1352
1354
|
var ChainTriggerSchema = z3.discriminatedUnion("type", [
|
|
1353
1355
|
z3.object({
|
|
1354
1356
|
type: z3.literal("stx_transfer"),
|
|
@@ -1429,7 +1431,8 @@ var ChainTriggerSchema = z3.discriminatedUnion("type", [
|
|
|
1429
1431
|
type: z3.literal("print_event"),
|
|
1430
1432
|
contractId: triggerPattern.optional(),
|
|
1431
1433
|
topic: triggerPattern.optional(),
|
|
1432
|
-
trait: trait.optional()
|
|
1434
|
+
trait: trait.optional(),
|
|
1435
|
+
where: PrintWhereSchema.optional()
|
|
1433
1436
|
}).strict(),
|
|
1434
1437
|
z3.object({
|
|
1435
1438
|
type: z3.literal("nested_contract_call"),
|
|
@@ -2154,7 +2157,6 @@ export {
|
|
|
2154
2157
|
getErrorMessage,
|
|
2155
2158
|
getMigrationRole,
|
|
2156
2159
|
getRawClient,
|
|
2157
|
-
getRawClientFor,
|
|
2158
2160
|
getSourceDb,
|
|
2159
2161
|
getTargetDb,
|
|
2160
2162
|
isBnsDecoderEnabled,
|
|
@@ -2173,5 +2175,5 @@ export {
|
|
|
2173
2175
|
sql2 as sql
|
|
2174
2176
|
};
|
|
2175
2177
|
|
|
2176
|
-
//# debugId=
|
|
2178
|
+
//# debugId=ED936767BF724EC464756E2164756E21
|
|
2177
2179
|
//# sourceMappingURL=index.js.map
|