@secondlayer/sdk 3.3.2 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -276,6 +276,370 @@ class Subgraphs extends BaseClient {
276
276
  };
277
277
  }
278
278
  }
279
+ // src/index-api/client.ts
280
+ function appendSearchParam(params, name, value) {
281
+ if (value === undefined || value === null)
282
+ return;
283
+ params.set(name, String(value));
284
+ }
285
+ function firstWalkFromHeight(params) {
286
+ if (params.fromHeight !== undefined)
287
+ return params.fromHeight;
288
+ if (params.cursor || params.fromCursor)
289
+ return;
290
+ return 0;
291
+ }
292
+
293
+ class Index extends BaseClient {
294
+ constructor(options = {}) {
295
+ super(options);
296
+ }
297
+ ftTransfers = {
298
+ list: (params = {}) => this.listFtTransfers(params),
299
+ walk: (params = {}) => this.walkFtTransfers(params)
300
+ };
301
+ nftTransfers = {
302
+ list: (params = {}) => this.listNftTransfers(params),
303
+ walk: (params = {}) => this.walkNftTransfers(params)
304
+ };
305
+ async listFtTransfers(params = {}) {
306
+ const searchParams = new URLSearchParams;
307
+ appendSearchParam(searchParams, "cursor", params.cursor);
308
+ appendSearchParam(searchParams, "from_cursor", params.fromCursor);
309
+ appendSearchParam(searchParams, "limit", params.limit);
310
+ appendSearchParam(searchParams, "contract_id", params.contractId);
311
+ appendSearchParam(searchParams, "sender", params.sender);
312
+ appendSearchParam(searchParams, "recipient", params.recipient);
313
+ appendSearchParam(searchParams, "from_height", params.fromHeight);
314
+ appendSearchParam(searchParams, "to_height", params.toHeight);
315
+ const query = searchParams.toString();
316
+ return this.request("GET", `/v1/index/ft-transfers${query ? `?${query}` : ""}`);
317
+ }
318
+ async listNftTransfers(params = {}) {
319
+ const searchParams = new URLSearchParams;
320
+ appendSearchParam(searchParams, "cursor", params.cursor);
321
+ appendSearchParam(searchParams, "from_cursor", params.fromCursor);
322
+ appendSearchParam(searchParams, "limit", params.limit);
323
+ appendSearchParam(searchParams, "contract_id", params.contractId);
324
+ appendSearchParam(searchParams, "asset_identifier", params.assetIdentifier);
325
+ appendSearchParam(searchParams, "sender", params.sender);
326
+ appendSearchParam(searchParams, "recipient", params.recipient);
327
+ appendSearchParam(searchParams, "from_height", params.fromHeight);
328
+ appendSearchParam(searchParams, "to_height", params.toHeight);
329
+ const query = searchParams.toString();
330
+ return this.request("GET", `/v1/index/nft-transfers${query ? `?${query}` : ""}`);
331
+ }
332
+ async* walkFtTransfers(params = {}) {
333
+ const batchSize = params.batchSize ?? 200;
334
+ let cursor = params.cursor ?? params.fromCursor ?? null;
335
+ let firstPage = true;
336
+ while (!params.signal?.aborted) {
337
+ const envelope = await this.listFtTransfers({
338
+ ...params,
339
+ limit: batchSize,
340
+ cursor: firstPage ? params.cursor : cursor,
341
+ fromCursor: firstPage ? params.fromCursor : undefined,
342
+ fromHeight: firstPage ? firstWalkFromHeight(params) : undefined
343
+ });
344
+ for (const event of envelope.events) {
345
+ if (params.signal?.aborted)
346
+ return;
347
+ yield event;
348
+ }
349
+ const nextCursor = envelope.next_cursor;
350
+ if (!nextCursor || nextCursor === cursor || envelope.events.length < batchSize) {
351
+ return;
352
+ }
353
+ cursor = nextCursor;
354
+ firstPage = false;
355
+ }
356
+ }
357
+ async* walkNftTransfers(params = {}) {
358
+ const batchSize = params.batchSize ?? 200;
359
+ let cursor = params.cursor ?? params.fromCursor ?? null;
360
+ let firstPage = true;
361
+ while (!params.signal?.aborted) {
362
+ const envelope = await this.listNftTransfers({
363
+ ...params,
364
+ limit: batchSize,
365
+ cursor: firstPage ? params.cursor : cursor,
366
+ fromCursor: firstPage ? params.fromCursor : undefined,
367
+ fromHeight: firstPage ? firstWalkFromHeight(params) : undefined
368
+ });
369
+ for (const event of envelope.events) {
370
+ if (params.signal?.aborted)
371
+ return;
372
+ yield event;
373
+ }
374
+ const nextCursor = envelope.next_cursor;
375
+ if (!nextCursor || nextCursor === cursor || envelope.events.length < batchSize) {
376
+ return;
377
+ }
378
+ cursor = nextCursor;
379
+ firstPage = false;
380
+ }
381
+ }
382
+ }
383
+
384
+ // src/streams/consumer.ts
385
+ async function defaultSleep(ms, signal) {
386
+ if (signal?.aborted)
387
+ return;
388
+ await new Promise((resolve) => {
389
+ const timeout = setTimeout(resolve, ms);
390
+ if (!signal)
391
+ return;
392
+ signal.addEventListener("abort", () => {
393
+ clearTimeout(timeout);
394
+ resolve();
395
+ }, { once: true });
396
+ });
397
+ }
398
+ async function consumeStreamsEvents(opts) {
399
+ const sleep = opts.sleep ?? defaultSleep;
400
+ const mode = opts.mode ?? "tail";
401
+ const emptyBackoffMs = opts.emptyBackoffMs ?? 500;
402
+ const maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;
403
+ const maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;
404
+ let cursor = opts.fromCursor ?? null;
405
+ let pages = 0;
406
+ let emptyPolls = 0;
407
+ while (pages < maxPages && emptyPolls < maxEmptyPolls && !opts.signal?.aborted) {
408
+ const envelope = await opts.fetchEvents({
409
+ cursor,
410
+ limit: opts.batchSize,
411
+ types: opts.types
412
+ });
413
+ pages++;
414
+ const returnedCursor = await opts.onBatch(envelope.events, envelope);
415
+ const nextCursor = returnedCursor ?? envelope.next_cursor;
416
+ if (nextCursor && nextCursor !== cursor) {
417
+ cursor = nextCursor;
418
+ emptyPolls = 0;
419
+ continue;
420
+ }
421
+ if (envelope.events.length === 0) {
422
+ emptyPolls++;
423
+ if (mode === "bounded") {
424
+ return { cursor, pages, emptyPolls };
425
+ }
426
+ await sleep(emptyBackoffMs, opts.signal);
427
+ continue;
428
+ }
429
+ return { cursor, pages, emptyPolls };
430
+ }
431
+ return { cursor, pages, emptyPolls };
432
+ }
433
+ async function* streamStreamsEvents(opts) {
434
+ const sleep = opts.sleep ?? defaultSleep;
435
+ const emptyBackoffMs = opts.emptyBackoffMs ?? 500;
436
+ const maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;
437
+ const maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;
438
+ let cursor = opts.fromCursor ?? null;
439
+ let pages = 0;
440
+ let emptyPolls = 0;
441
+ while (pages < maxPages && emptyPolls < maxEmptyPolls && !opts.signal?.aborted) {
442
+ const envelope = await opts.fetchEvents({
443
+ cursor,
444
+ limit: opts.batchSize,
445
+ types: opts.types
446
+ });
447
+ pages++;
448
+ for (const event of envelope.events) {
449
+ if (opts.signal?.aborted)
450
+ return;
451
+ yield event;
452
+ }
453
+ const nextCursor = envelope.next_cursor;
454
+ if (nextCursor && nextCursor !== cursor) {
455
+ cursor = nextCursor;
456
+ emptyPolls = 0;
457
+ continue;
458
+ }
459
+ if (envelope.events.length === 0) {
460
+ emptyPolls++;
461
+ if (emptyPolls >= maxEmptyPolls || pages >= maxPages)
462
+ return;
463
+ await sleep(emptyBackoffMs, opts.signal);
464
+ continue;
465
+ }
466
+ return;
467
+ }
468
+ }
469
+
470
+ // src/streams/errors.ts
471
+ class AuthError extends Error {
472
+ status = 401;
473
+ constructor(message = "API key invalid or expired.") {
474
+ super(message);
475
+ this.name = "AuthError";
476
+ }
477
+ }
478
+
479
+ class RateLimitError extends Error {
480
+ retryAfter;
481
+ status = 429;
482
+ constructor(message = "Rate limited. Try again later.", retryAfter) {
483
+ super(message);
484
+ this.retryAfter = retryAfter;
485
+ this.name = "RateLimitError";
486
+ }
487
+ }
488
+
489
+ class ValidationError extends Error {
490
+ status;
491
+ body;
492
+ constructor(message, status, body) {
493
+ super(message);
494
+ this.status = status;
495
+ this.body = body;
496
+ this.name = "ValidationError";
497
+ }
498
+ }
499
+
500
+ class StreamsServerError extends Error {
501
+ status;
502
+ body;
503
+ constructor(message, status, body) {
504
+ super(message);
505
+ this.status = status;
506
+ this.body = body;
507
+ this.name = "StreamsServerError";
508
+ }
509
+ }
510
+
511
+ // src/streams/client.ts
512
+ var DEFAULT_STREAMS_BASE_URL = "https://api.secondlayer.tools";
513
+ function normalizeBaseUrl(baseUrl) {
514
+ return baseUrl.replace(/\/+$/, "");
515
+ }
516
+ function appendSearchParam2(params, name, value) {
517
+ if (value === undefined || value === null)
518
+ return;
519
+ params.set(name, String(value));
520
+ }
521
+ async function responseBody(response) {
522
+ const text = await response.text();
523
+ if (text.length === 0)
524
+ return;
525
+ try {
526
+ return JSON.parse(text);
527
+ } catch {
528
+ return text;
529
+ }
530
+ }
531
+ function errorMessage(body, fallback) {
532
+ if (body && typeof body === "object") {
533
+ const record = body;
534
+ const message = record.error ?? record.message;
535
+ if (typeof message === "string" && message.length > 0)
536
+ return message;
537
+ }
538
+ if (typeof body === "string" && body.length > 0)
539
+ return body;
540
+ return fallback;
541
+ }
542
+ async function mapStreamsError(response) {
543
+ const body = await responseBody(response);
544
+ if (response.status === 401) {
545
+ throw new AuthError(errorMessage(body, "API key invalid or expired."));
546
+ }
547
+ if (response.status === 429) {
548
+ const retryAfter = response.headers.get("Retry-After") ?? undefined;
549
+ throw new RateLimitError(errorMessage(body, "Rate limited. Try again later."), retryAfter);
550
+ }
551
+ if (response.status >= 500) {
552
+ throw new StreamsServerError(errorMessage(body, `Streams server returned ${response.status}.`), response.status, body);
553
+ }
554
+ throw new ValidationError(errorMessage(body, `Streams request returned ${response.status}.`), response.status, body);
555
+ }
556
+ function createStreamsClient(options) {
557
+ const baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_STREAMS_BASE_URL);
558
+ const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
559
+ async function request(path) {
560
+ const response = await fetchImpl(`${baseUrl}${path}`, {
561
+ headers: { Authorization: `Bearer ${options.apiKey}` }
562
+ });
563
+ if (!response.ok)
564
+ await mapStreamsError(response);
565
+ return await response.json();
566
+ }
567
+ const fetchEvents = async ({
568
+ cursor,
569
+ limit,
570
+ types
571
+ }) => {
572
+ return listEvents({ cursor, limit, types });
573
+ };
574
+ async function listEvents(params = {}) {
575
+ const searchParams = new URLSearchParams;
576
+ appendSearchParam2(searchParams, "cursor", params.cursor);
577
+ appendSearchParam2(searchParams, "from_height", params.fromHeight);
578
+ appendSearchParam2(searchParams, "to_height", params.toHeight);
579
+ appendSearchParam2(searchParams, "limit", params.limit);
580
+ appendSearchParam2(searchParams, "contract_id", params.contractId);
581
+ if (params.types?.length) {
582
+ searchParams.set("types", params.types.join(","));
583
+ }
584
+ const query = searchParams.toString();
585
+ return request(`/v1/streams/events${query ? `?${query}` : ""}`);
586
+ }
587
+ return {
588
+ events: {
589
+ list: listEvents,
590
+ byTxId(txId) {
591
+ return request(`/v1/streams/events/${encodeURIComponent(txId)}`);
592
+ },
593
+ consume(params) {
594
+ return consumeStreamsEvents({
595
+ fromCursor: params.fromCursor,
596
+ mode: params.mode,
597
+ types: params.types,
598
+ batchSize: params.batchSize ?? 100,
599
+ fetchEvents,
600
+ onBatch: params.onBatch,
601
+ emptyBackoffMs: params.emptyBackoffMs,
602
+ maxPages: params.maxPages,
603
+ maxEmptyPolls: params.maxEmptyPolls,
604
+ signal: params.signal
605
+ });
606
+ },
607
+ stream(params = {}) {
608
+ return streamStreamsEvents({
609
+ fromCursor: params.fromCursor,
610
+ types: params.types,
611
+ batchSize: params.batchSize ?? 100,
612
+ emptyBackoffMs: params.emptyBackoffMs,
613
+ maxPages: params.maxPages,
614
+ maxEmptyPolls: params.maxEmptyPolls,
615
+ signal: params.signal,
616
+ fetchEvents
617
+ });
618
+ }
619
+ },
620
+ blocks: {
621
+ events(heightOrHash) {
622
+ return request(`/v1/streams/blocks/${encodeURIComponent(String(heightOrHash))}/events`);
623
+ }
624
+ },
625
+ reorgs: {
626
+ list(params) {
627
+ const searchParams = new URLSearchParams;
628
+ appendSearchParam2(searchParams, "since", params.since);
629
+ appendSearchParam2(searchParams, "limit", params.limit);
630
+ const query = searchParams.toString();
631
+ return request(`/v1/streams/reorgs${query ? `?${query}` : ""}`);
632
+ }
633
+ },
634
+ canonical(height) {
635
+ return request(`/v1/streams/canonical/${height}`);
636
+ },
637
+ tip() {
638
+ return request("/v1/streams/tip");
639
+ }
640
+ };
641
+ }
642
+
279
643
  // src/subscriptions/client.ts
280
644
  class Subscriptions extends BaseClient {
281
645
  async list() {
@@ -318,10 +682,18 @@ class Subscriptions extends BaseClient {
318
682
 
319
683
  // src/client.ts
320
684
  class SecondLayer extends BaseClient {
685
+ streams;
686
+ index;
321
687
  subgraphs;
322
688
  subscriptions;
323
689
  constructor(options = {}) {
324
690
  super(options);
691
+ this.streams = createStreamsClient({
692
+ apiKey: options.apiKey ?? "",
693
+ baseUrl: options.baseUrl,
694
+ fetchImpl: options.fetchImpl
695
+ });
696
+ this.index = new Index(options);
325
697
  this.subgraphs = new Subgraphs(options);
326
698
  this.subscriptions = new Subscriptions(options);
327
699
  }
@@ -337,6 +709,132 @@ function getSubgraph(def, options = {}) {
337
709
  }
338
710
  return new Subgraphs(options).typed(def);
339
711
  }
712
+ // src/streams/ft-transfer.ts
713
+ function requireString(payload, field) {
714
+ const value = payload[field];
715
+ if (typeof value !== "string" || value.length === 0) {
716
+ throw new Error(`ft_transfer payload missing ${field}`);
717
+ }
718
+ return value;
719
+ }
720
+ function parseAssetIdentifier(assetIdentifier) {
721
+ const [contractId, tokenName] = assetIdentifier.split("::");
722
+ if (!contractId) {
723
+ throw new Error("ft_transfer payload has malformed asset_identifier");
724
+ }
725
+ return {
726
+ contract_id: contractId,
727
+ token_name: tokenName && tokenName.length > 0 ? tokenName : null
728
+ };
729
+ }
730
+ function isFtTransfer(event) {
731
+ return event.event_type === "ft_transfer";
732
+ }
733
+ function decodeFtTransfer(event) {
734
+ if (!isFtTransfer(event)) {
735
+ throw new Error(`Expected ft_transfer event, got ${event.event_type}`);
736
+ }
737
+ const payload = event.payload;
738
+ const assetIdentifier = requireString(payload, "asset_identifier");
739
+ const sender = requireString(payload, "sender");
740
+ const recipient = requireString(payload, "recipient");
741
+ const amount = requireString(payload, "amount");
742
+ if (!/^(0|[1-9]\d*)$/.test(amount)) {
743
+ throw new Error("ft_transfer payload has malformed amount");
744
+ }
745
+ const { contract_id, token_name } = parseAssetIdentifier(assetIdentifier);
746
+ return {
747
+ cursor: event.cursor,
748
+ block_height: event.block_height,
749
+ tx_id: event.tx_id,
750
+ tx_index: event.tx_index,
751
+ event_index: event.event_index,
752
+ event_type: event.event_type,
753
+ decoded_payload: {
754
+ asset_identifier: assetIdentifier,
755
+ contract_id: event.contract_id ?? contract_id,
756
+ token_name,
757
+ sender,
758
+ recipient,
759
+ amount
760
+ },
761
+ source_cursor: event.cursor
762
+ };
763
+ }
764
+ // src/streams/nft-transfer.ts
765
+ function requireString2(payload, field) {
766
+ const value = payload[field];
767
+ if (typeof value !== "string" || value.length === 0) {
768
+ throw new Error(`nft_transfer payload missing ${field}`);
769
+ }
770
+ return value;
771
+ }
772
+ function requireHexValue(payload) {
773
+ const value = payload.value;
774
+ const hex = typeof value === "string" ? value : value && typeof value === "object" && typeof value.hex === "string" ? value.hex : null;
775
+ if (!hex) {
776
+ throw new Error("nft_transfer payload missing value");
777
+ }
778
+ if (!/^0x[0-9a-fA-F]*$/.test(hex)) {
779
+ throw new Error("nft_transfer payload has malformed value");
780
+ }
781
+ return hex;
782
+ }
783
+ function parseAssetIdentifier2(assetIdentifier) {
784
+ const [contractId, tokenName] = assetIdentifier.split("::");
785
+ if (!contractId) {
786
+ throw new Error("nft_transfer payload has malformed asset_identifier");
787
+ }
788
+ return {
789
+ contract_id: contractId,
790
+ token_name: tokenName && tokenName.length > 0 ? tokenName : null
791
+ };
792
+ }
793
+ function isNftTransfer(event) {
794
+ return event.event_type === "nft_transfer";
795
+ }
796
+ function decodeNftTransfer(event) {
797
+ if (!isNftTransfer(event)) {
798
+ throw new Error(`Expected nft_transfer event, got ${event.event_type}`);
799
+ }
800
+ const payload = event.payload;
801
+ const assetIdentifier = requireString2(payload, "asset_identifier");
802
+ const sender = requireString2(payload, "sender");
803
+ const recipient = requireString2(payload, "recipient");
804
+ const value = requireHexValue(payload);
805
+ const { contract_id, token_name } = parseAssetIdentifier2(assetIdentifier);
806
+ return {
807
+ cursor: event.cursor,
808
+ block_height: event.block_height,
809
+ tx_id: event.tx_id,
810
+ tx_index: event.tx_index,
811
+ event_index: event.event_index,
812
+ event_type: event.event_type,
813
+ decoded_payload: {
814
+ asset_identifier: assetIdentifier,
815
+ contract_id: event.contract_id ?? contract_id,
816
+ token_name,
817
+ sender,
818
+ recipient,
819
+ value
820
+ },
821
+ source_cursor: event.cursor
822
+ };
823
+ }
824
+ // src/streams/types.ts
825
+ var STREAMS_EVENT_TYPES = [
826
+ "stx_transfer",
827
+ "stx_mint",
828
+ "stx_burn",
829
+ "stx_lock",
830
+ "ft_transfer",
831
+ "ft_mint",
832
+ "ft_burn",
833
+ "nft_transfer",
834
+ "nft_mint",
835
+ "nft_burn",
836
+ "print"
837
+ ];
340
838
  // src/webhooks.ts
341
839
  import { verifySignatureHeader } from "@secondlayer/shared/crypto/hmac";
342
840
  function verifyWebhookSignature(rawBody, signatureHeader, secret, toleranceSeconds = 300) {
@@ -344,13 +842,23 @@ function verifyWebhookSignature(rawBody, signatureHeader, secret, toleranceSecon
344
842
  }
345
843
  export {
346
844
  verifyWebhookSignature,
845
+ isNftTransfer,
846
+ isFtTransfer,
347
847
  getSubgraph,
848
+ decodeNftTransfer,
849
+ decodeFtTransfer,
850
+ createStreamsClient,
348
851
  VersionConflictError,
852
+ ValidationError,
349
853
  Subscriptions,
350
854
  Subgraphs,
855
+ StreamsServerError,
351
856
  SecondLayer,
857
+ RateLimitError,
858
+ Index,
859
+ AuthError,
352
860
  ApiError
353
861
  };
354
862
 
355
- //# debugId=75D2C909D4BDD37B64756E2164756E21
863
+ //# debugId=EEEF1F40FE614E8264756E2164756E21
356
864
  //# sourceMappingURL=index.js.map