@secondlayer/sdk 6.33.0 → 6.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -17,6 +17,14 @@ interface SecondLayerOptions {
17
17
  /** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */
18
18
  origin?: "cli" | "mcp" | "session";
19
19
  }
20
+ /** Resolve the credential a client should use. An explicit `apiKey` option
21
+ * always wins — including an explicit `""`, which is how you opt a client
22
+ * back into keyless reads on a machine that has a key exported. Otherwise
23
+ * fall back to `SL_API_KEY`, the single credential var shared with the CLI
24
+ * and MCP server, so `new Index()` picks up an already-exported key instead
25
+ * of silently running keyless and 402-ing on the first deep-history read.
26
+ * Guarded for browsers and edge runtimes, where `process` is undefined. */
27
+ declare function resolveApiKey(apiKey?: string): string | undefined;
20
28
  declare abstract class BaseClient {
21
29
  protected baseUrl: string;
22
30
  protected apiKey?: string;
@@ -566,9 +574,34 @@ type StreamsEventsSubscribeParams = {
566
574
  * It is the position to advance to: `next_cursor` normally, or the last
567
575
  * finalized event when `finalizedOnly` is set.
568
576
  */
569
- type StreamsBatchContext = {
577
+ /**
578
+ * What the loop knows at the end of a page, handed to `onBatch`.
579
+ *
580
+ * `cursor` is the position to commit. The rest answers "how far along am I,
581
+ * and am I still moving" — the question every deployed consumer has to expose
582
+ * for a health check.
583
+ *
584
+ * Progress is reported here rather than left to callers because only the loop
585
+ * can get it right: `height` has to survive empty pages (normal at the tip)
586
+ * and has to roll back to `fork_point_height - 1` after a reorg rewind.
587
+ * Deriving it from `cursor` is wrong — `Cursor.atHeight` encodes the foot of a
588
+ * block as `${height - 1}:<sentinel>`, so a rewound cursor parses to a
589
+ * position that was never reached.
590
+ */
591
+ type ConsumerBatchContext = {
592
+ /** Checkpoint to commit alongside your rows. */
570
593
  cursor: string | null
571
- };
594
+ /** Highest canonical block the sweep has reached. `null` before the first
595
+ * row of a fresh consume. */
596
+ height: number | null
597
+ /** Chain tip as of this page's read. */
598
+ tipHeight: number
599
+ /** `tipHeight - height`, floored at 0. `null` until `height` is known. */
600
+ blocksBehind: number | null
601
+ };
602
+ /** @deprecated Use {@link ConsumerBatchContext} — the Index and Streams loops
603
+ * share one shape now. Kept as an alias so existing annotations compile. */
604
+ type StreamsBatchContext = ConsumerBatchContext;
572
605
  /**
573
606
  * The checkpoint for a reorg rollback. Persist `cursor` (the rewind position)
574
607
  * inside the same transaction as your rollback so the two commit atomically.
@@ -835,9 +868,7 @@ type IndexConsumeOptions<
835
868
  * never reorgs, so `onReorg` is skipped entirely. */
836
869
  finalizedOnly?: boolean
837
870
  batchSize?: number
838
- onBatch: (items: TItem[], envelope: TEnvelope, ctx: {
839
- cursor: string | null
840
- }) => void | string | null | undefined | Promise<void> | Promise<string | null | undefined>
871
+ onBatch: (items: TItem[], envelope: TEnvelope, ctx: ConsumerBatchContext) => void | string | null | undefined | Promise<void> | Promise<string | null | undefined>
841
872
  onReorg?: (reorg: IndexReorg, ctx: {
842
873
  cursor: string
843
874
  }) => Promise<void> | void
@@ -2838,4 +2869,4 @@ declare function toJsonSafe(value: unknown): unknown;
2838
2869
  /** Decode a hex-encoded Clarity value to JSON-safe JS (uints as strings,
2839
2870
  * buffers as `0x…` hex, tuples as objects). Returns the input hex on failure. */
2840
2871
  declare function decodeClarityValue(hex: string): unknown;
2841
- export { withX402, verifyWebhookSignature, verifyTransactionProof, verify as verifyStandardWebhooksHeaders, verifySecondlayerSignature, trigger, toJsonSafe, selectOffer, resolveAccountNonce, readX402Receipt, readX402Challenge, payAndRetry, isStxTransfer, isStxMint, isStxLock, isStxBurn, isPrint, isNftTransfer, isNftMint, isNftBurn, isFtTransfer, isFtMint, isFtBurn, getSubgraph, fetchRewardSet, decodeStxTransfer, decodeStxMint, decodeStxLock, decodeStxBurn, decodePrint, decodeNftTransfer, decodeNftMint, decodeNftBurn, decodeFtTransfer, decodeFtMint, decodeFtBurn, decodeClarityValue, decodeChainWebhook, createX402Client, createStreamsClient, consumeIndexFeed, buildSignedX402Payment, X402SpendGuardError, X402Result, X402Receipt, X402Fetch, X402ClientOptions, X402Client, X402Challenge, X402Accept, WithX402Options, WebhookHeaderInput, VersionConflictError, ValidationError, UpdateSubscriptionRequest2 as UpdateSubscriptionRequest, UpdateProjectParams, TransactionsWalkParams, TransactionsListParams, TransactionsEnvelope, TransactionProofVerifyResult, TransactionProof, TransactionEnvelope, Subscriptions, SubscriptionSummary2 as SubscriptionSummary, SubscriptionStatus, SubscriptionRuntime, SubscriptionKind, SubscriptionFormat, SubscriptionDetail2 as SubscriptionDetail, Subgraphs, SubgraphSpecOptions3 as SubgraphSpecOptions, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphOperationStatus, SubgraphAgentSchema3 as SubgraphAgentSchema, StreamsUsage, StreamsTip, StreamsSignatureError, StreamsServerError, StreamsReorgsListParams, StreamsReorgsListEnvelope, StreamsReorgContext, StreamsReorg, StreamsEventsSubscribeParams, StreamsEventsStreamParams, StreamsEventsListParams, StreamsEventsListEnvelope, StreamsEventsEnvelope, StreamsEventsConsumeResult, StreamsEventsConsumeParams, StreamsEventType, StreamsEventPayload, StreamsEvent, StreamsDumpsManifest, StreamsDumps, StreamsDumpFile, StreamsConsumeParams, StreamsClient, StreamsCanonicalBlock, StreamsBatchContext, StreamsBatch, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StackingWalkParams, StackingListParams, StackingEnvelope, SelectOfferOptions, SecondLayerOptions, SecondLayer, ScopedKeyProduct, SbtcWithdrawalsWalkParams, SbtcWithdrawalsListParams, SbtcWithdrawalsEnvelope, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalStatus, SbtcWithdrawalEvent, SbtcWithdrawalEnvelope, SbtcSummaryEnvelope, SbtcResource, SbtcEventsWalkParams, SbtcEventsListParams, SbtcEventsEnvelope, SbtcEventTopic, SbtcDepositsWalkParams, SbtcDepositsListParams, SbtcDepositsEnvelope, SbtcDepositEvent, SbtcDepositEnvelope, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, ReplayResult2 as ReplayResult, RateLimitError, Projects, ProjectTeamMember, ProjectTeam, ProjectInvitation, Project, PrintSchemaResponse, PoxResource, PoxCyclesWalkParams, PoxCyclesListParams, PoxCyclesEnvelope, PoxCycleEnvelope, Pox5Resource, Pox5EventsWalkParams, Pox5EventsListParams, Pox5EventsEnvelope, PayAndRetryOptions, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, IndexUsage, IndexTransaction, IndexTip, IndexStxTransfer, IndexStxMint, IndexStxLock, IndexStxBurn, IndexStackingAction, IndexSbtcWithdrawalPhase, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawal, IndexSbtcSummary, IndexSbtcEvent, IndexSbtcDepositDetail, IndexSbtcDeposit, IndexReorg, IndexPrint, IndexPoxFunctionCount, IndexPoxCycle, IndexPox5EventTopic, IndexPox5Event, IndexPostCondition, IndexNftTransfer, IndexNftMint, IndexNftBurn, IndexMempoolTransaction, IndexFtTransfer, IndexFtMint, IndexFtBurn, IndexFeedItem, IndexFeedFetcher, IndexFeedEnvelope, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEvent, IndexDiscovery, IndexContractCall, IndexConsumeOptions, IndexCanonicalBlock, IndexBlock, Index, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, EventsConsumeParams, DeliveryRow2 as DeliveryRow, DecodedStxTransferPayload, DecodedStxTransfer, DecodedStxMintPayload, DecodedStxMint, DecodedStxLockPayload, DecodedStxLock, DecodedStxBurnPayload, DecodedStxBurn, DecodedPrintValue, DecodedPrintPayload, DecodedPrint, DecodedNftTransferPayload, DecodedNftTransfer, DecodedNftMintPayload, DecodedNftMint, DecodedNftBurnPayload, DecodedNftBurn, DecodedFtTransferPayload, DecodedFtTransfer, DecodedFtMintPayload, DecodedFtMint, DecodedFtBurnPayload, DecodedFtBurn, DecodedEventRow, DecodedEventColumns, DeadRow2 as DeadRow, DEFAULT_PREFER_ASSETS, Cursor, CreateSubscriptionResponse2 as CreateSubscriptionResponse, CreateSubscriptionRequest2 as CreateSubscriptionRequest, CreateProjectParams, CreateApiKeyResponse, CreateApiKeyParams, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContractCallsConsumeParams, ContextSnapshot, ContextProject, ContextApiKey, ContextAccount, ChainWebhookEnvelope, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainTxLevelEvent, ChainTriggerType, ChainTrigger, ChainTestDelivery, ChainStxTransferData, ChainStxMintData, ChainStxLockData, ChainStxBurnData, ChainReorgRollbackEnvelope, ChainReorgRollbackDelivery, ChainReorgOrphanedEntry, ChainPrintEventData, ChainNftTransferData, ChainNftMintData, ChainNftBurnData, ChainFtTransferData, ChainFtMintData, ChainFtBurnData, ChainEventEnvelope, ChainApplyEnvelopeOf, ChainApplyEnvelope, ChainApplyDeliveryOf, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, ByoBreakingChangeError, ByoBreakingChangeDetails, BuildSignedX402PaymentOptions, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ApiKeys, ApiKeySummary, ApiError, ActiveSubgraphOperation };
2872
+ export { withX402, verifyWebhookSignature, verifyTransactionProof, verify as verifyStandardWebhooksHeaders, verifySecondlayerSignature, trigger, toJsonSafe, selectOffer, resolveApiKey, resolveAccountNonce, readX402Receipt, readX402Challenge, payAndRetry, isStxTransfer, isStxMint, isStxLock, isStxBurn, isPrint, isNftTransfer, isNftMint, isNftBurn, isFtTransfer, isFtMint, isFtBurn, getSubgraph, fetchRewardSet, decodeStxTransfer, decodeStxMint, decodeStxLock, decodeStxBurn, decodePrint, decodeNftTransfer, decodeNftMint, decodeNftBurn, decodeFtTransfer, decodeFtMint, decodeFtBurn, decodeClarityValue, decodeChainWebhook, createX402Client, createStreamsClient, consumeIndexFeed, buildSignedX402Payment, X402SpendGuardError, X402Result, X402Receipt, X402Fetch, X402ClientOptions, X402Client, X402Challenge, X402Accept, WithX402Options, WebhookHeaderInput, VersionConflictError, ValidationError, UpdateSubscriptionRequest2 as UpdateSubscriptionRequest, UpdateProjectParams, TransactionsWalkParams, TransactionsListParams, TransactionsEnvelope, TransactionProofVerifyResult, TransactionProof, TransactionEnvelope, Subscriptions, SubscriptionSummary2 as SubscriptionSummary, SubscriptionStatus, SubscriptionRuntime, SubscriptionKind, SubscriptionFormat, SubscriptionDetail2 as SubscriptionDetail, Subgraphs, SubgraphSpecOptions3 as SubgraphSpecOptions, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphOperationStatus, SubgraphAgentSchema3 as SubgraphAgentSchema, StreamsUsage, StreamsTip, StreamsSignatureError, StreamsServerError, StreamsReorgsListParams, StreamsReorgsListEnvelope, StreamsReorgContext, StreamsReorg, StreamsEventsSubscribeParams, StreamsEventsStreamParams, StreamsEventsListParams, StreamsEventsListEnvelope, StreamsEventsEnvelope, StreamsEventsConsumeResult, StreamsEventsConsumeParams, StreamsEventType, StreamsEventPayload, StreamsEvent, StreamsDumpsManifest, StreamsDumps, StreamsDumpFile, StreamsConsumeParams, StreamsClient, StreamsCanonicalBlock, StreamsBatchContext, StreamsBatch, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StackingWalkParams, StackingListParams, StackingEnvelope, SelectOfferOptions, SecondLayerOptions, SecondLayer, ScopedKeyProduct, SbtcWithdrawalsWalkParams, SbtcWithdrawalsListParams, SbtcWithdrawalsEnvelope, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalStatus, SbtcWithdrawalEvent, SbtcWithdrawalEnvelope, SbtcSummaryEnvelope, SbtcResource, SbtcEventsWalkParams, SbtcEventsListParams, SbtcEventsEnvelope, SbtcEventTopic, SbtcDepositsWalkParams, SbtcDepositsListParams, SbtcDepositsEnvelope, SbtcDepositEvent, SbtcDepositEnvelope, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, ReplayResult2 as ReplayResult, RateLimitError, Projects, ProjectTeamMember, ProjectTeam, ProjectInvitation, Project, PrintSchemaResponse, PoxResource, PoxCyclesWalkParams, PoxCyclesListParams, PoxCyclesEnvelope, PoxCycleEnvelope, Pox5Resource, Pox5EventsWalkParams, Pox5EventsListParams, Pox5EventsEnvelope, PayAndRetryOptions, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, IndexUsage, IndexTransaction, IndexTip, IndexStxTransfer, IndexStxMint, IndexStxLock, IndexStxBurn, IndexStackingAction, IndexSbtcWithdrawalPhase, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawal, IndexSbtcSummary, IndexSbtcEvent, IndexSbtcDepositDetail, IndexSbtcDeposit, IndexReorg, IndexPrint, IndexPoxFunctionCount, IndexPoxCycle, IndexPox5EventTopic, IndexPox5Event, IndexPostCondition, IndexNftTransfer, IndexNftMint, IndexNftBurn, IndexMempoolTransaction, IndexFtTransfer, IndexFtMint, IndexFtBurn, IndexFeedItem, IndexFeedFetcher, IndexFeedEnvelope, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEvent, IndexDiscovery, IndexContractCall, IndexConsumeOptions, IndexCanonicalBlock, IndexBlock, Index, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, EventsConsumeParams, DeliveryRow2 as DeliveryRow, DecodedStxTransferPayload, DecodedStxTransfer, DecodedStxMintPayload, DecodedStxMint, DecodedStxLockPayload, DecodedStxLock, DecodedStxBurnPayload, DecodedStxBurn, DecodedPrintValue, DecodedPrintPayload, DecodedPrint, DecodedNftTransferPayload, DecodedNftTransfer, DecodedNftMintPayload, DecodedNftMint, DecodedNftBurnPayload, DecodedNftBurn, DecodedFtTransferPayload, DecodedFtTransfer, DecodedFtMintPayload, DecodedFtMint, DecodedFtBurnPayload, DecodedFtBurn, DecodedEventRow, DecodedEventColumns, DeadRow2 as DeadRow, DEFAULT_PREFER_ASSETS, Cursor, CreateSubscriptionResponse2 as CreateSubscriptionResponse, CreateSubscriptionRequest2 as CreateSubscriptionRequest, CreateProjectParams, CreateApiKeyResponse, CreateApiKeyParams, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContractCallsConsumeParams, ContextSnapshot, ContextProject, ContextApiKey, ContextAccount, ConsumerBatchContext, ChainWebhookEnvelope, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainTxLevelEvent, ChainTriggerType, ChainTrigger, ChainTestDelivery, ChainStxTransferData, ChainStxMintData, ChainStxLockData, ChainStxBurnData, ChainReorgRollbackEnvelope, ChainReorgRollbackDelivery, ChainReorgOrphanedEntry, ChainPrintEventData, ChainNftTransferData, ChainNftMintData, ChainNftBurnData, ChainFtTransferData, ChainFtMintData, ChainFtBurnData, ChainEventEnvelope, ChainApplyEnvelopeOf, ChainApplyEnvelope, ChainApplyDeliveryOf, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, ByoBreakingChangeError, ByoBreakingChangeDetails, BuildSignedX402PaymentOptions, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ApiKeys, ApiKeySummary, ApiError, ActiveSubgraphOperation };
package/dist/index.js CHANGED
@@ -494,6 +494,14 @@ var Cursor = {
494
494
  function reorgKey(reorg) {
495
495
  return `${reorg.detected_at}|${reorg.fork_point_height}|${reorg.new_canonical_tip}`;
496
496
  }
497
+ function batchContext(cursor, height, tipHeight) {
498
+ return {
499
+ cursor,
500
+ height,
501
+ tipHeight,
502
+ blocksBehind: height === null ? null : Math.max(0, tipHeight - height)
503
+ };
504
+ }
497
505
  async function defaultSleep(ms, signal) {
498
506
  if (signal?.aborted)
499
507
  return;
@@ -518,6 +526,7 @@ async function consumeStreamsEvents(opts) {
518
526
  const handledReorgs = new Set;
519
527
  let pages = 0;
520
528
  let emptyPolls = 0;
529
+ let height = null;
521
530
  while (pages < maxPages && emptyPolls < maxEmptyPolls && !opts.signal?.aborted) {
522
531
  const envelope = await opts.fetchEvents({
523
532
  cursor,
@@ -540,15 +549,15 @@ async function consumeStreamsEvents(opts) {
540
549
  handledReorgs.add(reorgKey(reorg));
541
550
  }
542
551
  cursor = rewind;
552
+ height = forkPoint > 0 ? forkPoint - 1 : null;
543
553
  emptyPolls = 0;
544
554
  continue;
545
555
  }
546
556
  }
547
557
  const emitted = finalizedOnly ? envelope.events.filter((event) => event.finalized) : envelope.events;
548
558
  const checkpoint = finalizedOnly ? emitted.at(-1)?.cursor ?? cursor : envelope.next_cursor;
549
- const returnedCursor = await opts.onBatch(emitted, envelope, {
550
- cursor: checkpoint
551
- });
559
+ height = emitted.at(-1)?.block_height ?? height;
560
+ const returnedCursor = await opts.onBatch(emitted, envelope, batchContext(checkpoint, height, envelope.tip.block_height));
552
561
  const nextCursor = returnedCursor ?? checkpoint;
553
562
  if (nextCursor && nextCursor !== cursor) {
554
563
  cursor = nextCursor;
@@ -654,6 +663,7 @@ async function consumeIndexFeed(opts) {
654
663
  const handledReorgs = new Set;
655
664
  let pages = 0;
656
665
  let emptyPolls = 0;
666
+ let height = null;
657
667
  while (pages < maxPages && emptyPolls < maxEmptyPolls && !opts.signal?.aborted) {
658
668
  const envelope = await opts.fetchPage({
659
669
  cursor,
@@ -671,6 +681,7 @@ async function consumeIndexFeed(opts) {
671
681
  handledReorgs.add(reorg.id);
672
682
  }
673
683
  cursor = rewind;
684
+ height = forkPoint > 0 ? forkPoint - 1 : null;
674
685
  emptyPolls = 0;
675
686
  continue;
676
687
  }
@@ -678,9 +689,8 @@ async function consumeIndexFeed(opts) {
678
689
  const items = opts.itemsOf(envelope);
679
690
  const emitted = finalizedOnly ? items.filter((item) => item.block_height <= envelope.tip.finalized_height) : items;
680
691
  const checkpoint = finalizedOnly ? emitted.at(-1)?.cursor ?? cursor : envelope.next_cursor;
681
- const returnedCursor = await opts.onBatch(emitted, envelope, {
682
- cursor: checkpoint
683
- });
692
+ height = emitted.at(-1)?.block_height ?? height;
693
+ const returnedCursor = await opts.onBatch(emitted, envelope, batchContext(checkpoint, height, envelope.tip.block_height));
684
694
  const nextCursor = returnedCursor ?? checkpoint;
685
695
  if (nextCursor && nextCursor !== cursor) {
686
696
  cursor = nextCursor;
@@ -2403,6 +2413,7 @@ export {
2403
2413
  trigger,
2404
2414
  toJsonSafe,
2405
2415
  selectOffer,
2416
+ resolveApiKey,
2406
2417
  resolveAccountNonce,
2407
2418
  readX402Receipt,
2408
2419
  readX402Challenge,
@@ -2457,5 +2468,5 @@ export {
2457
2468
  ApiError
2458
2469
  };
2459
2470
 
2460
- //# debugId=B52298E5CC69F2EF64756E2164756E21
2471
+ //# debugId=B953F3BE6ADE95C364756E2164756E21
2461
2472
  //# sourceMappingURL=index.js.map