@secondlayer/sdk 6.20.0 → 6.21.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
@@ -273,155 +273,6 @@ declare class Contracts extends BaseClient {
273
273
  includeAbi?: boolean
274
274
  }): Promise<ContractSummary | null>;
275
275
  }
276
- /**
277
- * Typed client for the Foundation Datasets REST API (`/v1/datasets/*`).
278
- *
279
- * Most datasets are cursor-paginated event lists with a uniform `list`/`walk`
280
- * surface; a few (bns names/namespaces/resolve, network-health) are
281
- * offset/single-object/summary and get bespoke methods. Query params are typed
282
- * per dataset; rows are `DatasetRow` (JSON) in v1 — per-dataset row interfaces
283
- * are a fast-follow.
284
- */
285
- /** A dataset row — flat JSON object. Per-dataset interfaces are a follow-up. */
286
- type DatasetRow = Record<string, unknown>;
287
- /** Filters shared by every cursor-paginated dataset. */
288
- interface CursorListParams {
289
- cursor?: string;
290
- limit?: number;
291
- fromBlock?: number;
292
- toBlock?: number;
293
- }
294
- interface CursorEnvelope {
295
- rows: DatasetRow[];
296
- next_cursor: string | null;
297
- tip?: {
298
- block_height: number
299
- };
300
- }
301
- type RangeFilters = CursorListParams;
302
- type StxTransfersParams = RangeFilters & {
303
- sender?: string
304
- recipient?: string
305
- };
306
- type SbtcEventsParams = RangeFilters & {
307
- topic?: string
308
- address?: string
309
- };
310
- type SbtcTokenEventsParams = RangeFilters & {
311
- eventType?: string
312
- sender?: string
313
- recipient?: string
314
- };
315
- type Pox4CallsParams = RangeFilters & {
316
- functionName?: string
317
- stacker?: string
318
- delegateTo?: string
319
- signerKey?: string
320
- rewardCycle?: number
321
- /** Any-role: matches caller OR stacker OR delegate_to. */
322
- address?: string
323
- };
324
- type BurnchainRewardsParams = RangeFilters & {
325
- /** Filter to one Bitcoin reward address. */
326
- recipient?: string
327
- };
328
- type BurnchainRewardSlotsParams = RangeFilters & {
329
- /** Filter to one reward-set Bitcoin address. */
330
- holder?: string
331
- };
332
- type BnsEventsParams = RangeFilters & {
333
- topic?: string
334
- namespace?: string
335
- name?: string
336
- owner?: string
337
- };
338
- type BnsNamespaceEventsParams = RangeFilters & {
339
- status?: string
340
- namespace?: string
341
- };
342
- type BnsMarketplaceEventsParams = RangeFilters & {
343
- action?: string
344
- bnsId?: string
345
- };
346
- type CursorDataset<P> = {
347
- list: (params?: P) => Promise<CursorEnvelope>
348
- walk: (params?: P & {
349
- batchSize?: number
350
- signal?: AbortSignal
351
- }) => AsyncIterable<DatasetRow>
352
- };
353
- /** Cursor-paginated dataset slugs → REST path + envelope row key. */
354
- declare const CURSOR_SLUGS: Record<string, {
355
- path: string
356
- rowKey: string
357
- }>;
358
- declare class Datasets extends BaseClient {
359
- private catalogPromise?;
360
- constructor(options?: Partial<SecondLayerOptions>);
361
- /** Dataset catalog + freshness (the discovery endpoint). */
362
- listDatasets(): Promise<unknown>;
363
- /**
364
- * Generic read by slug for ANY catalog dataset — cursor or bespoke. Resolves
365
- * the slug against the live `/v1/datasets` catalog (so datasets added
366
- * server-side work with no SDK change), issues the GET, and normalizes the
367
- * response into a uniform `{ rows, next_cursor, tip }` envelope. Single-object
368
- * datasets (bns/resolve, network-health/summary) come back as 0-or-1 rows.
369
- * Accepts both family (`sbtc-events`) and path (`sbtc/events`) slug forms.
370
- * Prefer this over {@link query} unless you specifically need cursor-only
371
- * semantics.
372
- */
373
- get(slug: string, params?: Record<string, unknown>): Promise<CursorEnvelope>;
374
- /**
375
- * Generic cursor query by slug — used by the CLI. Params are passed through as
376
- * REST query keys (snake_case), so callers can use the documented filter names
377
- * directly. Throws for non-cursor (bespoke) datasets — use {@link get} for
378
- * those (and for slugs added to the catalog after this SDK was built).
379
- */
380
- query(slug: string, params?: Record<string, unknown>): Promise<CursorEnvelope>;
381
- readonly stxTransfers: CursorDataset<StxTransfersParams>;
382
- readonly sbtcEvents: CursorDataset<SbtcEventsParams>;
383
- readonly sbtcTokenEvents: CursorDataset<SbtcTokenEventsParams>;
384
- readonly pox4Calls: CursorDataset<Pox4CallsParams>;
385
- readonly burnchainRewards: CursorDataset<BurnchainRewardsParams>;
386
- readonly burnchainRewardSlots: CursorDataset<BurnchainRewardSlotsParams>;
387
- readonly bnsEvents: CursorDataset<BnsEventsParams>;
388
- readonly bnsNamespaceEvents: CursorDataset<BnsNamespaceEventsParams>;
389
- readonly bnsMarketplaceEvents: CursorDataset<BnsMarketplaceEventsParams>;
390
- /** BNS names — offset-paginated. */
391
- bnsNames(params?: {
392
- namespace?: string
393
- owner?: string
394
- limit?: number
395
- offset?: number
396
- }): Promise<{
397
- names: DatasetRow[]
398
- }>;
399
- /** All BNS namespaces (no pagination). */
400
- bnsNamespaces(): Promise<{
401
- namespaces: DatasetRow[]
402
- }>;
403
- /** Resolve a fully-qualified BNS name → single record. */
404
- bnsResolve(fqn: string): Promise<{
405
- name: DatasetRow | null
406
- }>;
407
- /** Network health summary. */
408
- networkHealth(): Promise<{
409
- summary: DatasetRow
410
- }>;
411
- private requestPath;
412
- /** Resolve a slug → relative path + row key. Known cursor slugs take a
413
- * network-free fast path; anything else is matched against the live catalog
414
- * by family name or path tail. */
415
- private resolveDataset;
416
- /** Fetch + cache the catalog families. Caches the in-flight promise so
417
- * concurrent first-calls share one request; no TTL — agent sessions are
418
- * short-lived, and a new client picks up newly added datasets. */
419
- private loadCatalog;
420
- /** Map camelCase filter fields to snake_case query keys (dropping pagination
421
- * controls) and build the canonical query suffix. */
422
- private paramsToQuery;
423
- private cursorDataset;
424
- }
425
276
  import { RewardSet } from "@secondlayer/shared/node/consensus";
426
277
  import { MerkleProofStep } from "@secondlayer/shared/node/nakamoto";
427
278
  /**
@@ -1697,7 +1548,6 @@ interface ContextSnapshot {
1697
1548
  declare class SecondLayer extends BaseClient {
1698
1549
  readonly streams: StreamsClient;
1699
1550
  readonly index: Index;
1700
- readonly datasets: Datasets;
1701
1551
  readonly contracts: Contracts;
1702
1552
  readonly subgraphs: Subgraphs;
1703
1553
  readonly subscriptions: Subscriptions;
@@ -1709,6 +1559,21 @@ declare class SecondLayer extends BaseClient {
1709
1559
  * from `secondlayer://context`, but available to any SDK/CLI consumer. Reads
1710
1560
  * run concurrently and degrade to `null` per field on failure.
1711
1561
  */
1562
+ /**
1563
+ * Up to 10 public reads in one round trip (`POST /v1/batch`). Each item
1564
+ * keeps its own auth/quota/x402 semantics; forwarded credentials (API key,
1565
+ * PAYMENT-BALANCE/SESSION) apply to every item.
1566
+ */
1567
+ batch(requests: Array<{
1568
+ path: string
1569
+ params?: Record<string, string | number | boolean>
1570
+ }>): Promise<{
1571
+ results: Array<{
1572
+ path: string | null
1573
+ status: number
1574
+ body: unknown
1575
+ }>
1576
+ }>;
1712
1577
  context(): Promise<ContextSnapshot>;
1713
1578
  }
1714
1579
  /**
@@ -2129,6 +1994,16 @@ declare function buildSignedX402Payment(opts: BuildSignedX402PaymentOptions): Pr
2129
1994
  }>;
2130
1995
  type WithX402Options = SelectOfferOptions & {
2131
1996
  account: LocalAccount
1997
+ /** Prepaid-credit token (PAYMENT-BALANCE) from a prior deposit — calls
1998
+ * debit the tab server-side instead of settling on-chain per call. */
1999
+ balanceToken?: string
2000
+ /** Autonomous treasury policy: when the tab's remaining balance (read from
2001
+ * X-BALANCE-REMAINING-USD) drops below `whenBelow`, deposit `usd` more in
2002
+ * the background (one on-chain payment) and adopt the fresh token. */
2003
+ topUp?: {
2004
+ usd: number
2005
+ whenBelow: number
2006
+ }
2132
2007
  /** Override the payer nonce; auto-resolved from `nodeUrl` when omitted. */
2133
2008
  accountNonce?: bigint | number | string
2134
2009
  /** Node for auto-nonce lookup. Defaults to {@link DEFAULT_NONCE_NODE_URL}. */
@@ -2367,4 +2242,4 @@ declare function toJsonSafe(value: unknown): unknown;
2367
2242
  /** Decode a hex-encoded Clarity value to JSON-safe JS (uints as strings,
2368
2243
  * buffers as `0x…` hex, tuples as objects). Returns the input hex on failure. */
2369
2244
  declare function decodeClarityValue(hex: string): unknown;
2370
- export { withX402, verifyWebhookSignature, verifyTransactionProof, 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, createX402Client, createStreamsClient, buildSignedX402Payment, X402SpendGuardError, X402Result, X402Receipt, X402Fetch, X402ClientOptions, X402Client, X402Challenge, X402Accept, WithX402Options, 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, StackingWalkParams, StackingListParams, StackingEnvelope, SelectOfferOptions, SecondLayerOptions, SecondLayer, ScopedKeyProduct, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, ReplayResult2 as ReplayResult, RateLimitError, Projects, ProjectTeamMember, ProjectTeam, ProjectInvitation, Project, Pox4CallsParams, PayAndRetryOptions, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, IndexUsage, IndexTransaction, IndexTip, IndexStackingAction, IndexReorg, IndexPostCondition, IndexMempoolTransaction, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEvent, IndexDiscovery, IndexContractCall, IndexCanonicalBlock, IndexBlock, Index, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, 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, Datasets, DatasetRow, DEFAULT_PREFER_ASSETS, CursorListParams, CursorEnvelope, Cursor, CreateSubscriptionResponse2 as CreateSubscriptionResponse, CreateSubscriptionRequest2 as CreateSubscriptionRequest, CreateProjectParams, CreateApiKeyResponse, CreateApiKeyParams, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContextSnapshot, ContextProject, ContextApiKey, ContextAccount, ChainTriggerType, ChainTrigger, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, CURSOR_SLUGS, ByoBreakingChangeError, ByoBreakingChangeDetails, BuildSignedX402PaymentOptions, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ApiKeys, ApiKeySummary, ApiError, ActiveSubgraphOperation };
2245
+ export { withX402, verifyWebhookSignature, verifyTransactionProof, 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, createX402Client, createStreamsClient, buildSignedX402Payment, X402SpendGuardError, X402Result, X402Receipt, X402Fetch, X402ClientOptions, X402Client, X402Challenge, X402Accept, WithX402Options, 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, StackingWalkParams, StackingListParams, StackingEnvelope, SelectOfferOptions, SecondLayerOptions, SecondLayer, ScopedKeyProduct, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, ReplayResult2 as ReplayResult, RateLimitError, Projects, ProjectTeamMember, ProjectTeam, ProjectInvitation, Project, PayAndRetryOptions, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, IndexUsage, IndexTransaction, IndexTip, IndexStackingAction, IndexReorg, IndexPostCondition, IndexMempoolTransaction, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEvent, IndexDiscovery, IndexContractCall, IndexCanonicalBlock, IndexBlock, Index, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, 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, ContextSnapshot, ContextProject, ContextApiKey, ContextAccount, ChainTriggerType, ChainTrigger, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, ByoBreakingChangeError, ByoBreakingChangeDetails, BuildSignedX402PaymentOptions, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ApiKeys, ApiKeySummary, ApiError, ActiveSubgraphOperation };
package/dist/index.js CHANGED
@@ -442,164 +442,6 @@ class Contracts extends BaseClient {
442
442
  }
443
443
  }
444
444
 
445
- // src/datasets/client.ts
446
- var PARAM_KEYS = {
447
- fromBlock: "from_block",
448
- toBlock: "to_block",
449
- functionName: "function_name",
450
- delegateTo: "delegate_to",
451
- signerKey: "signer_key",
452
- rewardCycle: "reward_cycle",
453
- eventType: "event_type",
454
- bnsId: "bns_id"
455
- };
456
- var CURSOR_SLUGS = {
457
- "stx-transfers": { path: "stx-transfers", rowKey: "events" },
458
- "sbtc-events": { path: "sbtc/events", rowKey: "events" },
459
- "sbtc-token-events": { path: "sbtc/token-events", rowKey: "events" },
460
- "pox-4-calls": { path: "pox-4/calls", rowKey: "calls" },
461
- "burnchain-rewards": { path: "burnchain/rewards", rowKey: "rewards" },
462
- "burnchain-reward-slots": {
463
- path: "burnchain/reward-slots",
464
- rowKey: "slots"
465
- },
466
- "bns-events": { path: "bns/events", rowKey: "events" },
467
- "bns-namespace-events": { path: "bns/namespace-events", rowKey: "events" },
468
- "bns-marketplace-events": {
469
- path: "bns/marketplace-events",
470
- rowKey: "events"
471
- }
472
- };
473
- function catalogPathTail(path) {
474
- return path.replace(/^\/?v1\/datasets\//, "").replace(/^\/+/, "");
475
- }
476
-
477
- class Datasets extends BaseClient {
478
- catalogPromise;
479
- constructor(options = {}) {
480
- super(options);
481
- }
482
- listDatasets() {
483
- return this.request("GET", "/v1/datasets");
484
- }
485
- async get(slug, params = {}) {
486
- const { path, rowKey } = await this.resolveDataset(slug);
487
- const env = await this.requestPath(path, this.paramsToQuery(params));
488
- const value = env[rowKey];
489
- const rows = Array.isArray(value) ? value : value == null ? [] : [value];
490
- return {
491
- rows,
492
- next_cursor: env.next_cursor ?? null,
493
- tip: env.tip
494
- };
495
- }
496
- async query(slug, params = {}) {
497
- const d = CURSOR_SLUGS[slug];
498
- if (!d) {
499
- throw new Error(`unknown cursor dataset "${slug}" (use one of: ${Object.keys(CURSOR_SLUGS).join(", ")})`);
500
- }
501
- const env = await this.requestPath(d.path, this.paramsToQuery(params));
502
- return {
503
- rows: env[d.rowKey] ?? [],
504
- next_cursor: env.next_cursor ?? null,
505
- tip: env.tip
506
- };
507
- }
508
- stxTransfers = this.cursorDataset("stx-transfers", "events");
509
- sbtcEvents = this.cursorDataset("sbtc/events", "events");
510
- sbtcTokenEvents = this.cursorDataset("sbtc/token-events", "events");
511
- pox4Calls = this.cursorDataset("pox-4/calls", "calls");
512
- burnchainRewards = this.cursorDataset("burnchain/rewards", "rewards");
513
- burnchainRewardSlots = this.cursorDataset("burnchain/reward-slots", "slots");
514
- bnsEvents = this.cursorDataset("bns/events", "events");
515
- bnsNamespaceEvents = this.cursorDataset("bns/namespace-events", "events");
516
- bnsMarketplaceEvents = this.cursorDataset("bns/marketplace-events", "events");
517
- bnsNames(params = {}) {
518
- return this.requestPath("bns/names", buildQuery({
519
- namespace: params.namespace,
520
- owner: params.owner,
521
- limit: params.limit,
522
- offset: params.offset
523
- }));
524
- }
525
- bnsNamespaces() {
526
- return this.requestPath("bns/namespaces", "");
527
- }
528
- bnsResolve(fqn) {
529
- return this.requestPath("bns/resolve", buildQuery({ fqn }));
530
- }
531
- networkHealth() {
532
- return this.requestPath("network-health/summary", "");
533
- }
534
- requestPath(path, query) {
535
- return this.request("GET", `/v1/datasets/${path}${query}`);
536
- }
537
- async resolveDataset(slug) {
538
- const cursor = CURSOR_SLUGS[slug];
539
- if (cursor)
540
- return { path: cursor.path, rowKey: cursor.rowKey };
541
- const families = await this.loadCatalog();
542
- const tail = catalogPathTail(slug);
543
- const match = families.find((f) => f.family === slug || catalogPathTail(f.path) === tail);
544
- if (!match) {
545
- throw new Error(`unknown dataset "${slug}" (available: ${families.map((f) => f.family).join(", ")})`);
546
- }
547
- return { path: catalogPathTail(match.path), rowKey: match.row_key };
548
- }
549
- loadCatalog() {
550
- this.catalogPromise ??= (async () => {
551
- const raw = await this.listDatasets();
552
- const families = raw.families;
553
- if (!Array.isArray(families)) {
554
- throw new Error("dataset catalog response missing families[]");
555
- }
556
- return families;
557
- })();
558
- return this.catalogPromise;
559
- }
560
- paramsToQuery(params) {
561
- const mapped = {};
562
- for (const [k, v] of Object.entries(params)) {
563
- if (v === undefined || v === null || k === "batchSize" || k === "signal")
564
- continue;
565
- mapped[PARAM_KEYS[k] ?? k] = v;
566
- }
567
- return buildQuery(mapped);
568
- }
569
- cursorDataset(path, rowKey) {
570
- const list = async (params = {}) => {
571
- const envelope = await this.requestPath(path, this.paramsToQuery(params));
572
- return {
573
- rows: envelope[rowKey] ?? [],
574
- next_cursor: envelope.next_cursor ?? null,
575
- tip: envelope.tip
576
- };
577
- };
578
- const walk = async function* (params = {}) {
579
- const batchSize = params.batchSize ?? 200;
580
- let cursor = params.cursor ?? null;
581
- let first = true;
582
- while (!params.signal?.aborted) {
583
- const env = await list({
584
- ...params,
585
- limit: batchSize,
586
- cursor: first ? params.cursor : cursor ?? undefined
587
- });
588
- for (const row of env.rows) {
589
- if (params.signal?.aborted)
590
- return;
591
- yield row;
592
- }
593
- if (!env.next_cursor || env.next_cursor === cursor || env.rows.length < batchSize)
594
- return;
595
- cursor = env.next_cursor;
596
- first = false;
597
- }
598
- }.bind(this);
599
- return { list, walk };
600
- }
601
- }
602
-
603
445
  // src/index-api/client.ts
604
446
  function firstWalkFromHeight(params) {
605
447
  if (params.fromHeight !== undefined)
@@ -1771,7 +1613,6 @@ class Subscriptions extends BaseClient {
1771
1613
  class SecondLayer extends BaseClient {
1772
1614
  streams;
1773
1615
  index;
1774
- datasets;
1775
1616
  contracts;
1776
1617
  subgraphs;
1777
1618
  subscriptions;
@@ -1786,13 +1627,15 @@ class SecondLayer extends BaseClient {
1786
1627
  dumpsBaseUrl: options.dumpsBaseUrl
1787
1628
  });
1788
1629
  this.index = new Index(options);
1789
- this.datasets = new Datasets(options);
1790
1630
  this.contracts = new Contracts(options);
1791
1631
  this.subgraphs = new Subgraphs(options);
1792
1632
  this.subscriptions = new Subscriptions(options);
1793
1633
  this.apiKeys = new ApiKeys(options);
1794
1634
  this.projects = new Projects(options);
1795
1635
  }
1636
+ async batch(requests) {
1637
+ return this.request("POST", "/v1/batch", { requests });
1638
+ }
1796
1639
  async context() {
1797
1640
  const safe = (p) => p.then((v) => v).catch(() => null);
1798
1641
  const [
@@ -2259,15 +2102,60 @@ async function buildSignedX402Payment(opts) {
2259
2102
  return { header, accept };
2260
2103
  }
2261
2104
  function withX402(baseFetch, opts) {
2262
- return async (input, init) => {
2105
+ const sessions = new Map;
2106
+ let balanceToken = opts.balanceToken ?? null;
2107
+ let toppingUp = false;
2108
+ const originOf = (input) => {
2109
+ try {
2110
+ return new URL(String(input)).origin;
2111
+ } catch {
2112
+ return "";
2113
+ }
2114
+ };
2115
+ const wrapped = async (input, init) => {
2116
+ const origin = originOf(input);
2263
2117
  const run = (extra, signal2) => baseFetch(input, {
2264
2118
  ...init,
2265
2119
  headers: { ...init?.headers, ...extra },
2266
2120
  ...signal2 ? { signal: signal2 } : {}
2267
2121
  });
2268
- const first = await run({});
2122
+ const maybeTopUp = (res) => {
2123
+ const policy = opts.topUp;
2124
+ if (!policy || toppingUp || !origin)
2125
+ return;
2126
+ const remaining = res.headers.get("X-BALANCE-REMAINING-USD");
2127
+ if (remaining === null || Number(remaining) >= policy.whenBelow)
2128
+ return;
2129
+ toppingUp = true;
2130
+ (async () => {
2131
+ try {
2132
+ const dep = await wrapped(`${origin}/v1/x402/deposit?usd=${policy.usd}`, { method: "POST" });
2133
+ if (dep.ok) {
2134
+ const body = await dep.json();
2135
+ if (body.balance_token)
2136
+ balanceToken = body.balance_token;
2137
+ }
2138
+ } catch {} finally {
2139
+ toppingUp = false;
2140
+ }
2141
+ })();
2142
+ };
2143
+ const remember = (res) => {
2144
+ const voucher = res.headers.get("PAYMENT-SESSION");
2145
+ if (voucher && origin)
2146
+ sessions.set(origin, voucher);
2147
+ maybeTopUp(res);
2148
+ return res;
2149
+ };
2150
+ const cached = origin ? sessions.get(origin) : undefined;
2151
+ const first = await run({
2152
+ ...cached ? { "PAYMENT-SESSION": cached } : {},
2153
+ ...balanceToken ? { "PAYMENT-BALANCE": balanceToken } : {}
2154
+ });
2269
2155
  if (first.status !== 402)
2270
- return first;
2156
+ return remember(first);
2157
+ if (cached && origin)
2158
+ sessions.delete(origin);
2271
2159
  const challenge = await readX402Challenge(first);
2272
2160
  if (!challenge)
2273
2161
  return first;
@@ -2282,8 +2170,9 @@ function withX402(baseFetch, opts) {
2282
2170
  });
2283
2171
  opts.onSettling?.({ asset: accept.asset, amount: accept.amount });
2284
2172
  const signal = opts.timeoutMs ? AbortSignal.timeout(opts.timeoutMs) : undefined;
2285
- return run({ "PAYMENT-SIGNATURE": header }, signal);
2173
+ return remember(await run({ "PAYMENT-SIGNATURE": header }, signal));
2286
2174
  };
2175
+ return wrapped;
2287
2176
  }
2288
2177
  function createX402Client(opts) {
2289
2178
  const f = withX402(opts.fetch ?? fetch, opts);
@@ -2496,16 +2385,14 @@ export {
2496
2385
  RateLimitError,
2497
2386
  Projects,
2498
2387
  Index,
2499
- Datasets,
2500
2388
  DEFAULT_PREFER_ASSETS,
2501
2389
  Cursor,
2502
2390
  Contracts,
2503
- CURSOR_SLUGS,
2504
2391
  ByoBreakingChangeError,
2505
2392
  AuthError,
2506
2393
  ApiKeys,
2507
2394
  ApiError
2508
2395
  };
2509
2396
 
2510
- //# debugId=EFE64A13154F57C864756E2164756E21
2397
+ //# debugId=EAC231197163FBBB64756E2164756E21
2511
2398
  //# sourceMappingURL=index.js.map