@secondlayer/shared 14.2.0 → 15.0.1

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.
@@ -1,196 +0,0 @@
1
- /** v2 /extended/v2/blocks/{height} response */
2
- interface HiroBlockResponse {
3
- canonical: boolean;
4
- height: number;
5
- hash: string;
6
- block_time: number;
7
- block_time_iso: string;
8
- index_block_hash: string;
9
- parent_block_hash: string;
10
- parent_index_block_hash: string;
11
- burn_block_hash: string;
12
- burn_block_height: number;
13
- burn_block_time: number;
14
- miner_txid: string;
15
- tx_count: number;
16
- }
17
- /** v2 /extended/v2/blocks/{height}/transactions response */
18
- interface HiroBlockTxsResponse {
19
- limit: number;
20
- offset: number;
21
- total: number;
22
- results: HiroTxResponse[];
23
- }
24
- interface HiroTxResponse {
25
- tx_id: string;
26
- tx_type: string;
27
- tx_status: string;
28
- sender_address: string;
29
- fee_rate: string;
30
- nonce: number;
31
- block_hash: string;
32
- block_height: number;
33
- burn_block_height: number;
34
- tx_index: number;
35
- event_count: number;
36
- token_transfer?: {
37
- recipient_address: string
38
- amount: string
39
- memo: string
40
- };
41
- contract_call?: {
42
- contract_id: string
43
- function_name: string
44
- function_args: unknown[]
45
- };
46
- smart_contract?: {
47
- contract_id: string
48
- source_code: string
49
- };
50
- }
51
- interface HiroEvent {
52
- event_index: number;
53
- event_type: string;
54
- tx_id: string;
55
- asset?: {
56
- asset_event_type: string
57
- sender?: string
58
- recipient?: string
59
- amount?: string
60
- memo?: string
61
- asset_id?: string
62
- value?: unknown
63
- };
64
- contract_log?: {
65
- contract_id: string
66
- topic: string
67
- value: unknown
68
- };
69
- }
70
- interface HiroEventsResponse {
71
- limit: number;
72
- offset: number;
73
- events: HiroEvent[];
74
- }
75
- /** Shape our indexer expects at POST /new_block */
76
- interface NewBlockPayload {
77
- block_hash: string;
78
- block_height: number;
79
- index_block_hash: string;
80
- parent_block_hash: string;
81
- parent_index_block_hash: string;
82
- burn_block_hash: string;
83
- burn_block_height: number;
84
- burn_block_timestamp: number;
85
- miner_txid: string;
86
- timestamp: number;
87
- transactions: TransactionPayload[];
88
- events: TransactionEventPayload[];
89
- }
90
- interface TransactionPayload {
91
- txid: string;
92
- raw_tx: string;
93
- status: string;
94
- tx_index: number;
95
- tx_type?: string;
96
- sender_address?: string;
97
- }
98
- interface TransactionEventPayload {
99
- txid: string;
100
- event_index: number;
101
- committed: boolean;
102
- type: string;
103
- stx_transfer_event?: {
104
- sender: string
105
- recipient: string
106
- amount: string
107
- memo?: string
108
- };
109
- stx_mint_event?: {
110
- recipient: string
111
- amount: string
112
- };
113
- stx_burn_event?: {
114
- sender: string
115
- amount: string
116
- };
117
- stx_lock_event?: {
118
- locked_amount: string
119
- unlock_height: string
120
- locked_address: string
121
- };
122
- ft_transfer_event?: {
123
- asset_identifier: string
124
- sender: string
125
- recipient: string
126
- amount: string
127
- };
128
- ft_mint_event?: {
129
- asset_identifier: string
130
- recipient: string
131
- amount: string
132
- };
133
- ft_burn_event?: {
134
- asset_identifier: string
135
- sender: string
136
- amount: string
137
- };
138
- nft_transfer_event?: {
139
- asset_identifier: string
140
- sender: string
141
- recipient: string
142
- value: unknown
143
- };
144
- nft_mint_event?: {
145
- asset_identifier: string
146
- recipient: string
147
- value: unknown
148
- };
149
- nft_burn_event?: {
150
- asset_identifier: string
151
- sender: string
152
- value: unknown
153
- };
154
- smart_contract_event?: {
155
- contract_identifier: string
156
- topic: string
157
- value: unknown
158
- };
159
- }
160
- interface GetBlockOptions {
161
- /** Fetch actual raw_tx hex for each transaction (instead of "0x00" placeholder) */
162
- includeRawTx?: boolean;
163
- /** Max concurrent raw_tx fetches per block (default: 10) */
164
- rawTxConcurrency?: number;
165
- }
166
- declare class HiroClient {
167
- private apiUrl;
168
- private fallbackUrl;
169
- private apiKey;
170
- private maxRetries;
171
- constructor(apiUrl?: string, maxRetries?: number);
172
- private get headers();
173
- /** Fetch with retry on 429/5xx using exponential backoff */
174
- private fetchWithRetry;
175
- /**
176
- * Fetch a complete block by height, including all transactions and events,
177
- * transformed into the NewBlockPayload format our indexer expects.
178
- *
179
- * Uses 3-step approach:
180
- * 1. GET /extended/v2/blocks/{height} — block metadata
181
- * 2. GET /extended/v2/blocks/{height}/transactions — all txs (paginated)
182
- * 3. GET /extended/v1/tx/events?tx_id={txId} — events per tx (only for txs with events)
183
- */
184
- getBlockForIndexer(height: number, options?: GetBlockOptions): Promise<NewBlockPayload | null>;
185
- /** v2 block metadata */
186
- private fetchBlock;
187
- /** v2 block transactions (paginated) */
188
- private fetchBlockTransactions;
189
- private fetchAllEvents;
190
- /** Fetch raw_tx hex for a single transaction */
191
- fetchRawTx(txId: string): Promise<string | null>;
192
- /** Fetch raw_tx for multiple transactions with bounded concurrency */
193
- fetchRawTxBatch(txIds: string[], concurrency?: number): Promise<Map<string, string>>;
194
- getApiUrl(): string;
195
- }
196
- export { GetBlockOptions, HiroBlockResponse, HiroBlockTxsResponse, HiroClient, HiroEvent, HiroEventsResponse, HiroTxResponse, NewBlockPayload };
@@ -1,495 +0,0 @@
1
- // src/env.ts
2
- import { z } from "zod";
3
- var networksSchema = z.string().transform((val) => {
4
- const networks = val.split(",").map((n) => n.trim()).filter(Boolean);
5
- const valid = ["mainnet", "testnet"];
6
- for (const n of networks) {
7
- if (!valid.includes(n)) {
8
- throw new Error(`Invalid network: ${n}. Must be one of: ${valid.join(", ")}`);
9
- }
10
- }
11
- return networks;
12
- });
13
- var envSchema = z.object({
14
- DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
15
- SOURCE_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
16
- TARGET_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
17
- NETWORK: z.enum(["mainnet", "testnet"]).optional(),
18
- NETWORKS: networksSchema.optional(),
19
- LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
20
- NODE_ENV: z.enum(["development", "production", "test"]).default("development")
21
- });
22
- var cachedEnv = null;
23
- function getEnv() {
24
- if (cachedEnv) {
25
- return cachedEnv;
26
- }
27
- const result = envSchema.safeParse(process.env);
28
- if (!result.success) {
29
- console.error("❌ Invalid environment configuration:");
30
- console.error(z.treeifyError(result.error));
31
- throw new Error("Invalid environment configuration");
32
- }
33
- let enabledNetworks;
34
- if (result.data.NETWORKS && result.data.NETWORKS.length > 0) {
35
- enabledNetworks = result.data.NETWORKS;
36
- } else if (result.data.NETWORK) {
37
- enabledNetworks = [result.data.NETWORK];
38
- } else {
39
- enabledNetworks = ["mainnet"];
40
- }
41
- cachedEnv = { ...result.data, enabledNetworks };
42
- return cachedEnv;
43
- }
44
- function isProductionEnv() {
45
- return process.env["NODE_ENV"] === "production";
46
- }
47
- function isPox4DecoderEnabled(env = process.env) {
48
- return env.POX4_DECODER_ENABLED !== "false";
49
- }
50
- function isPox5DecoderEnabled(env = process.env) {
51
- return env.POX5_DECODER_ENABLED !== "false";
52
- }
53
- function isSbtcDecoderEnabled(env = process.env) {
54
- return env.SBTC_DECODER_ENABLED !== "false";
55
- }
56
- function isBnsDecoderEnabled(env = process.env) {
57
- return env.BNS_DECODER_ENABLED === "true";
58
- }
59
- // src/logger.ts
60
- var LOG_LEVELS = {
61
- debug: 0,
62
- info: 1,
63
- warn: 2,
64
- error: 3
65
- };
66
-
67
- class Logger {
68
- _level;
69
- _isProduction;
70
- _initialized = false;
71
- init() {
72
- if (this._initialized)
73
- return;
74
- this._initialized = true;
75
- try {
76
- const env = getEnv();
77
- this._level = env.LOG_LEVEL;
78
- this._isProduction = env.NODE_ENV === "production";
79
- } catch {
80
- this._level = "info";
81
- this._isProduction = false;
82
- }
83
- }
84
- get level() {
85
- this.init();
86
- return this._level;
87
- }
88
- get isProduction() {
89
- this.init();
90
- return this._isProduction;
91
- }
92
- shouldLog(level) {
93
- return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
94
- }
95
- formatMessage(level, message, meta) {
96
- const timestamp = new Date().toISOString();
97
- if (this.isProduction) {
98
- return JSON.stringify({
99
- timestamp,
100
- level,
101
- message,
102
- ...meta
103
- });
104
- }
105
- const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
106
- return `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;
107
- }
108
- debug(message, meta) {
109
- if (this.shouldLog("debug")) {
110
- console.debug(this.formatMessage("debug", message, meta));
111
- }
112
- }
113
- info(message, meta) {
114
- if (this.shouldLog("info")) {
115
- console.info(this.formatMessage("info", message, meta));
116
- }
117
- }
118
- warn(message, meta) {
119
- if (this.shouldLog("warn")) {
120
- console.warn(this.formatMessage("warn", message, meta));
121
- }
122
- }
123
- error(message, meta) {
124
- if (this.shouldLog("error")) {
125
- console.error(this.formatMessage("error", message, meta));
126
- }
127
- }
128
- }
129
- var logger = new Logger;
130
-
131
- // src/node/hiro-client.ts
132
- var DEFAULT_HIRO_API_URL = "https://api.mainnet.hiro.so";
133
-
134
- class HiroClient {
135
- apiUrl;
136
- fallbackUrl;
137
- apiKey;
138
- maxRetries;
139
- constructor(apiUrl, maxRetries = 5) {
140
- this.apiUrl = apiUrl || process.env.HIRO_API_URL || DEFAULT_HIRO_API_URL;
141
- this.fallbackUrl = process.env.HIRO_FALLBACK_URL;
142
- this.apiKey = process.env.HIRO_API_KEY;
143
- this.maxRetries = maxRetries;
144
- }
145
- get headers() {
146
- return this.apiKey ? { "x-hiro-api-key": this.apiKey } : {};
147
- }
148
- async fetchWithRetry(url, timeoutMs = 120000) {
149
- for (let attempt = 0;attempt < this.maxRetries; attempt++) {
150
- const res = await fetch(url, {
151
- headers: this.headers,
152
- signal: AbortSignal.timeout(timeoutMs)
153
- });
154
- if (res.ok || res.status === 404)
155
- return res;
156
- if (res.status === 429 || res.status >= 500) {
157
- const delay = Math.min(1000 * 2 ** attempt, 1e4);
158
- logger.info("Rate limited, retrying", {
159
- url: url.split("/").slice(-2).join("/"),
160
- attempt,
161
- delay
162
- });
163
- await new Promise((r) => setTimeout(r, delay));
164
- continue;
165
- }
166
- return res;
167
- }
168
- return fetch(url, {
169
- headers: this.headers,
170
- signal: AbortSignal.timeout(timeoutMs)
171
- });
172
- }
173
- async getBlockForIndexer(height, options) {
174
- let block = await this.fetchBlock(height);
175
- const fallbackUrl = this.fallbackUrl;
176
- let usingFallback = false;
177
- if (!block && fallbackUrl) {
178
- block = await this.fetchBlock(height, fallbackUrl);
179
- if (block)
180
- usingFallback = true;
181
- }
182
- if (!block)
183
- return null;
184
- const baseUrl = usingFallback && fallbackUrl ? fallbackUrl : this.apiUrl;
185
- const hiroTxs = await this.fetchBlockTransactions(height, baseUrl);
186
- const txPayloads = [];
187
- const eventPayloads = [];
188
- for (const hiroTx of hiroTxs) {
189
- txPayloads.push({
190
- txid: hiroTx.tx_id,
191
- raw_tx: "0x00",
192
- status: mapTxStatus(hiroTx.tx_status),
193
- tx_index: hiroTx.tx_index ?? 0,
194
- tx_type: mapTxType(hiroTx.tx_type),
195
- sender_address: hiroTx.sender_address
196
- });
197
- if (hiroTx.event_count > 0) {
198
- if (hiroTx.event_count > 1000) {
199
- logger.info("Fetching large event set", {
200
- txId: hiroTx.tx_id,
201
- eventCount: hiroTx.event_count,
202
- height
203
- });
204
- }
205
- try {
206
- const events = await this.fetchAllEvents(hiroTx.tx_id, baseUrl);
207
- eventPayloads.push(...events);
208
- } catch (err) {
209
- logger.warn("Failed to fetch events for backfill", {
210
- txId: hiroTx.tx_id,
211
- error: String(err)
212
- });
213
- }
214
- }
215
- }
216
- if (options?.includeRawTx && txPayloads.length > 0) {
217
- const txIds = txPayloads.map((t) => t.txid);
218
- const rawTxMap = await this.fetchRawTxBatch(txIds, options.rawTxConcurrency);
219
- for (const txPayload of txPayloads) {
220
- const raw = rawTxMap.get(txPayload.txid);
221
- if (raw)
222
- txPayload.raw_tx = raw;
223
- }
224
- }
225
- return {
226
- block_hash: block.hash,
227
- block_height: block.height,
228
- index_block_hash: block.index_block_hash,
229
- parent_block_hash: block.parent_block_hash,
230
- parent_index_block_hash: block.parent_index_block_hash,
231
- burn_block_hash: block.burn_block_hash,
232
- burn_block_height: block.burn_block_height,
233
- burn_block_timestamp: block.burn_block_time,
234
- miner_txid: block.miner_txid,
235
- timestamp: block.block_time,
236
- transactions: txPayloads,
237
- events: eventPayloads
238
- };
239
- }
240
- async fetchBlock(height, baseUrl) {
241
- const url = baseUrl || this.apiUrl;
242
- const res = await this.fetchWithRetry(`${url}/extended/v2/blocks/${height}`);
243
- if (res.status === 404)
244
- return null;
245
- if (!res.ok)
246
- throw new Error(`Hiro API block/${height} returned ${res.status}`);
247
- return res.json();
248
- }
249
- async fetchBlockTransactions(height, baseUrl) {
250
- const url = baseUrl || this.apiUrl;
251
- const txs = [];
252
- let offset = 0;
253
- const limit = 50;
254
- while (true) {
255
- const res = await this.fetchWithRetry(`${url}/extended/v2/blocks/${height}/transactions?limit=${limit}&offset=${offset}`);
256
- if (!res.ok)
257
- throw new Error(`Hiro API block/${height}/transactions returned ${res.status}`);
258
- const data = await res.json();
259
- txs.push(...data.results);
260
- if (txs.length >= data.total || data.results.length < limit)
261
- break;
262
- offset += limit;
263
- }
264
- return txs;
265
- }
266
- async fetchAllEvents(txId, baseUrl, _maxEvents) {
267
- const url = baseUrl || this.apiUrl;
268
- const events = [];
269
- let offset = 0;
270
- const limit = 100;
271
- while (true) {
272
- const res = await this.fetchWithRetry(`${url}/extended/v1/tx/events?tx_id=${txId}&limit=${limit}&offset=${offset}`);
273
- if (!res.ok) {
274
- logger.warn("Failed to fetch events from Hiro", {
275
- txId,
276
- status: res.status
277
- });
278
- break;
279
- }
280
- const data = await res.json();
281
- for (const hEvent of data.events) {
282
- const converted = convertHiroEvent(hEvent);
283
- if (converted)
284
- events.push(converted);
285
- }
286
- if (data.events.length < limit)
287
- break;
288
- offset += limit;
289
- }
290
- return events;
291
- }
292
- async fetchRawTx(txId) {
293
- try {
294
- const res = await this.fetchWithRetry(`${this.apiUrl}/extended/v1/tx/${txId}/raw`, 1e4);
295
- if (!res.ok)
296
- return null;
297
- const data = await res.json();
298
- return data.raw_tx || null;
299
- } catch {
300
- return null;
301
- }
302
- }
303
- async fetchRawTxBatch(txIds, concurrency = 10) {
304
- const results = new Map;
305
- for (let i = 0;i < txIds.length; i += concurrency) {
306
- const chunk = txIds.slice(i, i + concurrency);
307
- const settled = await Promise.allSettled(chunk.map(async (txId) => {
308
- const raw = await this.fetchRawTx(txId);
309
- return { txId, raw };
310
- }));
311
- for (const result of settled) {
312
- if (result.status === "fulfilled" && result.value.raw) {
313
- results.set(result.value.txId, result.value.raw);
314
- }
315
- }
316
- }
317
- return results;
318
- }
319
- getApiUrl() {
320
- return this.apiUrl;
321
- }
322
- }
323
- function mapTxStatus(status) {
324
- switch (status) {
325
- case "success":
326
- return "success";
327
- case "abort_by_response":
328
- case "abort_by_post_condition":
329
- return status;
330
- default:
331
- return "success";
332
- }
333
- }
334
- function mapTxType(type) {
335
- switch (type) {
336
- case "token_transfer":
337
- return "token_transfer";
338
- case "contract_call":
339
- return "contract_call";
340
- case "smart_contract":
341
- return "smart_contract";
342
- case "coinbase":
343
- return "coinbase";
344
- case "tenure_change":
345
- return "tenure_change";
346
- case "poison_microblock":
347
- return "poison_microblock";
348
- default:
349
- return type;
350
- }
351
- }
352
- function convertHiroEvent(hEvent) {
353
- const base = {
354
- txid: hEvent.tx_id,
355
- event_index: hEvent.event_index,
356
- committed: true
357
- };
358
- if (hEvent.event_type === "stx_asset" && hEvent.asset) {
359
- const a = hEvent.asset;
360
- switch (a.asset_event_type) {
361
- case "transfer":
362
- return {
363
- ...base,
364
- type: "stx_transfer_event",
365
- stx_transfer_event: {
366
- sender: a.sender ?? "",
367
- recipient: a.recipient ?? "",
368
- amount: a.amount ?? "0",
369
- memo: a.memo
370
- }
371
- };
372
- case "mint":
373
- return {
374
- ...base,
375
- type: "stx_mint_event",
376
- stx_mint_event: {
377
- recipient: a.recipient ?? "",
378
- amount: a.amount ?? "0"
379
- }
380
- };
381
- case "burn":
382
- return {
383
- ...base,
384
- type: "stx_burn_event",
385
- stx_burn_event: { sender: a.sender ?? "", amount: a.amount ?? "0" }
386
- };
387
- case "lock":
388
- return {
389
- ...base,
390
- type: "stx_lock_event",
391
- stx_lock_event: {
392
- locked_amount: a.amount ?? "0",
393
- unlock_height: "0",
394
- locked_address: a.sender ?? ""
395
- }
396
- };
397
- }
398
- }
399
- if (hEvent.event_type === "fungible_token_asset" && hEvent.asset) {
400
- const a = hEvent.asset;
401
- const assetId = a.asset_id || "";
402
- switch (a.asset_event_type) {
403
- case "transfer":
404
- return {
405
- ...base,
406
- type: "ft_transfer_event",
407
- ft_transfer_event: {
408
- asset_identifier: assetId,
409
- sender: a.sender ?? "",
410
- recipient: a.recipient ?? "",
411
- amount: a.amount ?? "0"
412
- }
413
- };
414
- case "mint":
415
- return {
416
- ...base,
417
- type: "ft_mint_event",
418
- ft_mint_event: {
419
- asset_identifier: assetId,
420
- recipient: a.recipient ?? "",
421
- amount: a.amount ?? "0"
422
- }
423
- };
424
- case "burn":
425
- return {
426
- ...base,
427
- type: "ft_burn_event",
428
- ft_burn_event: {
429
- asset_identifier: assetId,
430
- sender: a.sender ?? "",
431
- amount: a.amount ?? "0"
432
- }
433
- };
434
- }
435
- }
436
- if (hEvent.event_type === "non_fungible_token_asset" && hEvent.asset) {
437
- const a = hEvent.asset;
438
- const assetId = a.asset_id || "";
439
- switch (a.asset_event_type) {
440
- case "transfer":
441
- return {
442
- ...base,
443
- type: "nft_transfer_event",
444
- nft_transfer_event: {
445
- asset_identifier: assetId,
446
- sender: a.sender ?? "",
447
- recipient: a.recipient ?? "",
448
- value: a.value
449
- }
450
- };
451
- case "mint":
452
- return {
453
- ...base,
454
- type: "nft_mint_event",
455
- nft_mint_event: {
456
- asset_identifier: assetId,
457
- recipient: a.recipient ?? "",
458
- value: a.value
459
- }
460
- };
461
- case "burn":
462
- return {
463
- ...base,
464
- type: "nft_burn_event",
465
- nft_burn_event: {
466
- asset_identifier: assetId,
467
- sender: a.sender ?? "",
468
- value: a.value
469
- }
470
- };
471
- }
472
- }
473
- if (hEvent.event_type === "smart_contract_log" && hEvent.contract_log) {
474
- return {
475
- ...base,
476
- type: "smart_contract_event",
477
- smart_contract_event: {
478
- contract_identifier: hEvent.contract_log.contract_id,
479
- topic: hEvent.contract_log.topic,
480
- value: hEvent.contract_log.value
481
- }
482
- };
483
- }
484
- logger.debug("Unknown Hiro event type, skipping", {
485
- eventType: hEvent.event_type,
486
- txId: hEvent.tx_id
487
- });
488
- return null;
489
- }
490
- export {
491
- HiroClient
492
- };
493
-
494
- //# debugId=F9C49EBA89BDC12B64756E2164756E21
495
- //# sourceMappingURL=hiro-client.js.map