@chainstream-io/sdk 0.1.21 → 0.1.23

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,4 +1,4 @@
1
- import { hZ as Resolution, a as Configuration, U as DexApi, Y as DexPoolApi, bi as TokenApi, bV as WalletApi, by as TradeApi, ax as RankingApi, bO as TransactionApi, z as DefiSolanaMoonshotApi, K as DefiSolanaPumpfunApi, aW as RedPacketApi, a6 as IpfsApi, w as BlockchainApi, bX as WatchlistApi, a9 as JobsApi, ar as KYTApi, a4 as EndpointApi } from './WatchlistApi-18jD3YH5.js';
1
+ import { hm as Resolution, a as Configuration, U as DexApi, Y as DexPoolApi, bf as TokenApi, bS as WalletApi, bv as TradeApi, au as RankingApi, bL as TransactionApi, z as DefiSolanaMoonshotApi, K as DefiSolanaPumpfunApi, aT as RedPacketApi, a6 as IpfsApi, w as BlockchainApi, bU as WatchlistApi, a9 as JobsApi, ao as KYTApi, a4 as EndpointApi } from './WatchlistApi-VmKx6Q1Q.js';
2
2
 
3
3
  declare enum TokenActivityType {
4
4
  Sell = "sell",
@@ -320,12 +320,42 @@ interface Unsubscrible {
320
320
  declare class StreamApi {
321
321
  private realtimeClient;
322
322
  private listenersMap;
323
+ private context;
324
+ private initPromise;
323
325
  constructor(context: DexRequestContext);
326
+ /**
327
+ * Initialize Centrifuge client with current token
328
+ * This is called lazily when connect() is called
329
+ */
330
+ private initClient;
331
+ /**
332
+ * Wait for initialization to complete
333
+ * If not initialized, auto-connect first
334
+ */
335
+ private ensureInitialized;
336
+ /**
337
+ * Get token value from string or TokenProvider
338
+ */
339
+ private getTokenValue;
324
340
  /**
325
341
  * Build WebSocket URL with token as query parameter
326
342
  */
327
343
  private buildWsUrl;
344
+ /**
345
+ * Connect to the WebSocket server.
346
+ * This is automatically called when you use subscribe methods if not already connected.
347
+ * You can also call this method manually for explicit control.
348
+ */
328
349
  connect(): void;
350
+ /**
351
+ * Disconnect from the WebSocket server.
352
+ * All subscriptions will be automatically removed.
353
+ */
354
+ disconnect(): void;
355
+ /**
356
+ * Check if the WebSocket is currently connected.
357
+ */
358
+ isConnected(): boolean;
329
359
  /**
330
360
  * Start batching commands for efficient bulk operations
331
361
  * All subscription commands after this call will be batched until stopBatching is called
@@ -470,8 +500,16 @@ interface DexAggregatorOptions {
470
500
  debug?: boolean;
471
501
  serverUrl?: string;
472
502
  streamUrl?: string;
503
+ /**
504
+ * Whether to automatically connect to WebSocket on initialization.
505
+ * Default: false
506
+ *
507
+ * If set to true, WebSocket will connect automatically.
508
+ * If false or not set, you need to manually call `client.stream.connect()` when needed.
509
+ */
510
+ autoConnectWebSocket?: boolean;
473
511
  }
474
- declare const LIB_VERSION = "0.1.20";
512
+ declare const LIB_VERSION = "0.1.23";
475
513
  declare class DexClient {
476
514
  readonly requestCtx: DexRequestContext;
477
515
  readonly _configuration: Configuration;
package/dist/index.cjs CHANGED
@@ -289,10 +289,24 @@ var StreamApi = class {
289
289
  constructor(context) {
290
290
  __publicField(this, "realtimeClient");
291
291
  __publicField(this, "listenersMap");
292
- const realtimeEndpoint = this.buildWsUrl(context.streamUrl, context.accessToken);
292
+ __publicField(this, "context");
293
+ __publicField(this, "initPromise", null);
294
+ this.context = context;
295
+ this.listenersMap = /* @__PURE__ */ new Map();
296
+ }
297
+ /**
298
+ * Initialize Centrifuge client with current token
299
+ * This is called lazily when connect() is called
300
+ */
301
+ async initClient() {
302
+ if (this.realtimeClient) {
303
+ return;
304
+ }
305
+ const token = await this.getTokenValue();
306
+ const realtimeEndpoint = this.buildWsUrl(this.context.streamUrl, token);
293
307
  this.realtimeClient = new import_centrifuge.Centrifuge(realtimeEndpoint, {
294
308
  getToken: async (_ctx) => {
295
- return typeof context.accessToken === "string" ? context.accessToken : await context.accessToken.getToken();
309
+ return this.getTokenValue();
296
310
  }
297
311
  });
298
312
  this.realtimeClient.on("connected", () => {
@@ -302,34 +316,73 @@ var StreamApi = class {
302
316
  }).on("error", (err) => {
303
317
  console.error("[streaming] error: ", err);
304
318
  });
305
- this.listenersMap = /* @__PURE__ */ new Map();
319
+ }
320
+ /**
321
+ * Wait for initialization to complete
322
+ * If not initialized, auto-connect first
323
+ */
324
+ async ensureInitialized() {
325
+ if (!this.initPromise) {
326
+ this.connect();
327
+ }
328
+ await this.initPromise;
329
+ }
330
+ /**
331
+ * Get token value from string or TokenProvider
332
+ */
333
+ async getTokenValue() {
334
+ return typeof this.context.accessToken === "string" ? this.context.accessToken : await this.context.accessToken.getToken();
306
335
  }
307
336
  /**
308
337
  * Build WebSocket URL with token as query parameter
309
338
  */
310
- buildWsUrl(endpoint, accessToken) {
339
+ buildWsUrl(endpoint, token) {
311
340
  const url = new URL(endpoint);
312
- if (typeof accessToken === "string") {
313
- url.searchParams.set("token", accessToken);
314
- }
341
+ url.searchParams.set("token", token);
315
342
  return url.toString();
316
343
  }
344
+ /**
345
+ * Connect to the WebSocket server.
346
+ * This is automatically called when you use subscribe methods if not already connected.
347
+ * You can also call this method manually for explicit control.
348
+ */
317
349
  connect() {
318
- this.realtimeClient.connect();
350
+ this.initPromise = this.initClient().then(() => {
351
+ this.realtimeClient.connect();
352
+ });
353
+ }
354
+ /**
355
+ * Disconnect from the WebSocket server.
356
+ * All subscriptions will be automatically removed.
357
+ */
358
+ disconnect() {
359
+ if (this.realtimeClient) {
360
+ this.realtimeClient.disconnect();
361
+ }
362
+ }
363
+ /**
364
+ * Check if the WebSocket is currently connected.
365
+ */
366
+ isConnected() {
367
+ return this.realtimeClient?.state === "connected";
319
368
  }
320
369
  /**
321
370
  * Start batching commands for efficient bulk operations
322
371
  * All subscription commands after this call will be batched until stopBatching is called
323
372
  */
324
373
  startBatching() {
325
- this.realtimeClient.startBatching();
374
+ if (this.realtimeClient) {
375
+ this.realtimeClient.startBatching();
376
+ }
326
377
  }
327
378
  /**
328
379
  * Stop batching and flush all collected commands to the server
329
380
  * This will send all batched subscription commands in a single network request
330
381
  */
331
382
  stopBatching() {
332
- this.realtimeClient.stopBatching();
383
+ if (this.realtimeClient) {
384
+ this.realtimeClient.stopBatching();
385
+ }
333
386
  }
334
387
  /**
335
388
  * Batch subscribe method that accepts a function containing subscription calls
@@ -359,26 +412,31 @@ var StreamApi = class {
359
412
  });
360
413
  }
361
414
  subscribe(channel, fn, filter, methodName) {
362
- let sub = this.realtimeClient.getSubscription(channel);
363
415
  let listeners = this.listenersMap.get(channel);
364
- if (!sub) {
416
+ if (!listeners) {
365
417
  listeners = /* @__PURE__ */ new Set();
366
418
  this.listenersMap.set(channel, listeners);
367
- console.log("[xrealtime] create new sub: ", channel);
368
- const processedFilter = filter && methodName ? replaceFilterFields(filter, methodName) : filter;
369
- sub = this.realtimeClient.newSubscription(channel, {
370
- delta: "fossil",
371
- ...processedFilter && { filter: processedFilter }
372
- });
373
- sub.on("subscribed", () => {
374
- console.log("[xrealtime] subscribed", channel);
375
- }).on("unsubscribed", () => {
376
- console.log("[xrealtime] unsubscribed", channel);
377
- }).on("publication", (ctx) => {
378
- listeners?.forEach((it) => it(ctx.data));
379
- }).subscribe();
380
- }
381
- listeners?.add(fn);
419
+ }
420
+ listeners.add(fn);
421
+ this.ensureInitialized().then(() => {
422
+ let sub = this.realtimeClient.getSubscription(channel);
423
+ if (!sub) {
424
+ console.log("[xrealtime] create new sub: ", channel);
425
+ const processedFilter = filter && methodName ? replaceFilterFields(filter, methodName) : filter;
426
+ sub = this.realtimeClient.newSubscription(channel, {
427
+ delta: "fossil",
428
+ ...processedFilter && { filter: processedFilter }
429
+ });
430
+ sub.on("subscribed", () => {
431
+ console.log("[xrealtime] subscribed", channel);
432
+ }).on("unsubscribed", () => {
433
+ console.log("[xrealtime] unsubscribed", channel);
434
+ }).on("publication", (ctx) => {
435
+ const currentListeners = this.listenersMap.get(channel);
436
+ currentListeners?.forEach((it) => it(ctx.data));
437
+ }).subscribe();
438
+ }
439
+ });
382
440
  return new StreamUnsubscrible(this, channel, fn);
383
441
  }
384
442
  unsubscribe(channel, fn) {
@@ -390,12 +448,14 @@ var StreamApi = class {
390
448
  console.log("unsubscribe, remain listeners: ", listeners.size);
391
449
  if (listeners.size === 0) {
392
450
  console.log("unsubscribe channel: ", channel);
393
- const sub = this.realtimeClient.getSubscription(channel);
394
- if (sub) {
395
- sub.unsubscribe();
396
- this.realtimeClient.removeSubscription(sub);
397
- }
398
451
  this.listenersMap.delete(channel);
452
+ this.ensureInitialized().then(() => {
453
+ const sub = this.realtimeClient.getSubscription(channel);
454
+ if (sub) {
455
+ sub.unsubscribe();
456
+ this.realtimeClient.removeSubscription(sub);
457
+ }
458
+ });
399
459
  }
400
460
  }
401
461
  formatScientificNotation(value) {
@@ -1864,7 +1924,9 @@ function AddressExposureFromJSONTyped(json, ignoreDiscriminator) {
1864
1924
  }
1865
1925
  return {
1866
1926
  "category": json["category"],
1867
- "value": json["value"]
1927
+ "value": json["value"],
1928
+ "exposureType": json["exposureType"],
1929
+ "direction": json["direction"]
1868
1930
  };
1869
1931
  }
1870
1932
 
@@ -2740,110 +2802,6 @@ function KYTRegisterWithdrawalRequestToJSONTyped(value, ignoreDiscriminator = fa
2740
2802
  };
2741
2803
  }
2742
2804
 
2743
- // src/openapi/models/KytAddressDTO.ts
2744
- function KytAddressDTOFromJSON(json) {
2745
- return KytAddressDTOFromJSONTyped(json, false);
2746
- }
2747
- function KytAddressDTOFromJSONTyped(json, ignoreDiscriminator) {
2748
- if (json == null) {
2749
- return json;
2750
- }
2751
- return {
2752
- "id": json["id"],
2753
- "orgId": json["orgId"],
2754
- "address": json["address"],
2755
- "createdAt": new Date(json["createdAt"]),
2756
- "updatedAt": new Date(json["updatedAt"])
2757
- };
2758
- }
2759
-
2760
- // src/openapi/models/KytAddressPage.ts
2761
- function KytAddressPageFromJSON(json) {
2762
- return KytAddressPageFromJSONTyped(json, false);
2763
- }
2764
- function KytAddressPageFromJSONTyped(json, ignoreDiscriminator) {
2765
- if (json == null) {
2766
- return json;
2767
- }
2768
- return {
2769
- "total": json["total"],
2770
- "page": json["page"],
2771
- "pageSize": json["pageSize"],
2772
- "totalPages": json["totalPages"],
2773
- "data": json["data"].map(KytAddressDTOFromJSON)
2774
- };
2775
- }
2776
-
2777
- // src/openapi/models/KytTransferDTO.ts
2778
- function KytTransferDTOFromJSON(json) {
2779
- return KytTransferDTOFromJSONTyped(json, false);
2780
- }
2781
- function KytTransferDTOFromJSONTyped(json, ignoreDiscriminator) {
2782
- if (json == null) {
2783
- return json;
2784
- }
2785
- return {
2786
- "id": json["id"],
2787
- "orgId": json["orgId"],
2788
- "txHash": json["txHash"],
2789
- "externalId": json["externalId"],
2790
- "createdAt": new Date(json["createdAt"]),
2791
- "updatedAt": new Date(json["updatedAt"])
2792
- };
2793
- }
2794
-
2795
- // src/openapi/models/KytTransferPage.ts
2796
- function KytTransferPageFromJSON(json) {
2797
- return KytTransferPageFromJSONTyped(json, false);
2798
- }
2799
- function KytTransferPageFromJSONTyped(json, ignoreDiscriminator) {
2800
- if (json == null) {
2801
- return json;
2802
- }
2803
- return {
2804
- "total": json["total"],
2805
- "page": json["page"],
2806
- "pageSize": json["pageSize"],
2807
- "totalPages": json["totalPages"],
2808
- "data": json["data"].map(KytTransferDTOFromJSON)
2809
- };
2810
- }
2811
-
2812
- // src/openapi/models/KytWithdrawalDTO.ts
2813
- function KytWithdrawalDTOFromJSON(json) {
2814
- return KytWithdrawalDTOFromJSONTyped(json, false);
2815
- }
2816
- function KytWithdrawalDTOFromJSONTyped(json, ignoreDiscriminator) {
2817
- if (json == null) {
2818
- return json;
2819
- }
2820
- return {
2821
- "id": json["id"],
2822
- "orgId": json["orgId"],
2823
- "address": json["address"],
2824
- "externalId": json["externalId"],
2825
- "createdAt": new Date(json["createdAt"]),
2826
- "updatedAt": new Date(json["updatedAt"])
2827
- };
2828
- }
2829
-
2830
- // src/openapi/models/KytWithdrawalPage.ts
2831
- function KytWithdrawalPageFromJSON(json) {
2832
- return KytWithdrawalPageFromJSONTyped(json, false);
2833
- }
2834
- function KytWithdrawalPageFromJSONTyped(json, ignoreDiscriminator) {
2835
- if (json == null) {
2836
- return json;
2837
- }
2838
- return {
2839
- "total": json["total"],
2840
- "page": json["page"],
2841
- "pageSize": json["pageSize"],
2842
- "totalPages": json["totalPages"],
2843
- "data": json["data"].map(KytWithdrawalDTOFromJSON)
2844
- };
2845
- }
2846
-
2847
2805
  // src/openapi/models/Link.ts
2848
2806
  function LinkToJSON(json) {
2849
2807
  return LinkToJSONTyped(json, false);
@@ -4562,7 +4520,7 @@ var EndpointApi = class extends BaseAPI {
4562
4520
  headerParameters["Authorization"] = `Bearer ${tokenString}`;
4563
4521
  }
4564
4522
  }
4565
- let urlPath = `/v1/webhook/endpoint/{id}`;
4523
+ let urlPath = `/v1/webhook/endpoint`;
4566
4524
  const response = await this.request({
4567
4525
  path: urlPath,
4568
4526
  method: "PATCH",
@@ -4741,117 +4699,6 @@ var KYTApi = class extends BaseAPI {
4741
4699
  const response = await this.getAddressRiskRaw(requestParameters, initOverrides);
4742
4700
  return await response.value();
4743
4701
  }
4744
- /**
4745
- * CONTROLLER.KYT.GET_KYT_ADDRESSES.DESCRIPTION
4746
- * CONTROLLER.KYT.GET_KYT_ADDRESSES.SUMMARY
4747
- */
4748
- async getKytAddressesRaw(requestParameters, initOverrides) {
4749
- const queryParameters = {};
4750
- if (requestParameters["page"] != null) {
4751
- queryParameters["page"] = requestParameters["page"];
4752
- }
4753
- if (requestParameters["pageSize"] != null) {
4754
- queryParameters["pageSize"] = requestParameters["pageSize"];
4755
- }
4756
- const headerParameters = {};
4757
- if (this.configuration && this.configuration.accessToken) {
4758
- const token = this.configuration.accessToken;
4759
- const tokenString = await token("bearer", []);
4760
- if (tokenString) {
4761
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
4762
- }
4763
- }
4764
- let urlPath = `/v1/kyt/addresses`;
4765
- const response = await this.request({
4766
- path: urlPath,
4767
- method: "GET",
4768
- headers: headerParameters,
4769
- query: queryParameters
4770
- }, initOverrides);
4771
- return new JSONApiResponse(response, (jsonValue) => KytAddressPageFromJSON(jsonValue));
4772
- }
4773
- /**
4774
- * CONTROLLER.KYT.GET_KYT_ADDRESSES.DESCRIPTION
4775
- * CONTROLLER.KYT.GET_KYT_ADDRESSES.SUMMARY
4776
- */
4777
- async getKytAddresses(requestParameters = {}, initOverrides) {
4778
- const response = await this.getKytAddressesRaw(requestParameters, initOverrides);
4779
- return await response.value();
4780
- }
4781
- /**
4782
- * CONTROLLER.KYT.GET_KYT_TRANSFERS.DESCRIPTION
4783
- * CONTROLLER.KYT.GET_KYT_TRANSFERS.SUMMARY
4784
- */
4785
- async getKytTransfersRaw(requestParameters, initOverrides) {
4786
- const queryParameters = {};
4787
- if (requestParameters["page"] != null) {
4788
- queryParameters["page"] = requestParameters["page"];
4789
- }
4790
- if (requestParameters["pageSize"] != null) {
4791
- queryParameters["pageSize"] = requestParameters["pageSize"];
4792
- }
4793
- const headerParameters = {};
4794
- if (this.configuration && this.configuration.accessToken) {
4795
- const token = this.configuration.accessToken;
4796
- const tokenString = await token("bearer", []);
4797
- if (tokenString) {
4798
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
4799
- }
4800
- }
4801
- let urlPath = `/v1/kyt/transfers`;
4802
- const response = await this.request({
4803
- path: urlPath,
4804
- method: "GET",
4805
- headers: headerParameters,
4806
- query: queryParameters
4807
- }, initOverrides);
4808
- return new JSONApiResponse(response, (jsonValue) => KytTransferPageFromJSON(jsonValue));
4809
- }
4810
- /**
4811
- * CONTROLLER.KYT.GET_KYT_TRANSFERS.DESCRIPTION
4812
- * CONTROLLER.KYT.GET_KYT_TRANSFERS.SUMMARY
4813
- */
4814
- async getKytTransfers(requestParameters = {}, initOverrides) {
4815
- const response = await this.getKytTransfersRaw(requestParameters, initOverrides);
4816
- return await response.value();
4817
- }
4818
- /**
4819
- * CONTROLLER.KYT.GET_KYT_WITHDRAWALS.DESCRIPTION
4820
- * CONTROLLER.KYT.GET_KYT_WITHDRAWALS.SUMMARY
4821
- */
4822
- async getKytWithdrawalsRaw(requestParameters, initOverrides) {
4823
- const queryParameters = {};
4824
- if (requestParameters["page"] != null) {
4825
- queryParameters["page"] = requestParameters["page"];
4826
- }
4827
- if (requestParameters["pageSize"] != null) {
4828
- queryParameters["pageSize"] = requestParameters["pageSize"];
4829
- }
4830
- const headerParameters = {};
4831
- if (this.configuration && this.configuration.accessToken) {
4832
- const token = this.configuration.accessToken;
4833
- const tokenString = await token("bearer", []);
4834
- if (tokenString) {
4835
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
4836
- }
4837
- }
4838
- let urlPath = `/v1/kyt/withdrawals`;
4839
- const response = await this.request({
4840
- path: urlPath,
4841
- method: "GET",
4842
- headers: headerParameters,
4843
- query: queryParameters
4844
- }, initOverrides);
4845
- return new JSONApiResponse(response, (jsonValue) => KytWithdrawalPageFromJSON(jsonValue));
4846
- }
4847
- /**
4848
- * CONTROLLER.KYT.GET_KYT_WITHDRAWALS.DESCRIPTION
4849
- * CONTROLLER.KYT.GET_KYT_WITHDRAWALS.SUMMARY
4850
- */
4851
- async getKytWithdrawals(requestParameters = {}, initOverrides) {
4852
- const response = await this.getKytWithdrawalsRaw(requestParameters, initOverrides);
4853
- return await response.value();
4854
- }
4855
4702
  /**
4856
4703
  * CONTROLLER.KYT.GET_TRANSFER_ALERTS.DESCRIPTION
4857
4704
  * CONTROLLER.KYT.GET_TRANSFER_ALERTS.SUMMARY
@@ -8172,7 +8019,7 @@ var WatchlistApi = class extends BaseAPI {
8172
8019
 
8173
8020
  // src/index.ts
8174
8021
  var import_event_source_polyfill = require("event-source-polyfill");
8175
- var LIB_VERSION = "0.1.20";
8022
+ var LIB_VERSION = "0.1.23";
8176
8023
  var UserAgentMiddleware = class {
8177
8024
  async pre(context) {
8178
8025
  if (!context.init.headers) {
@@ -8210,9 +8057,6 @@ var DexClient = class {
8210
8057
  __publicField(this, "endpoint");
8211
8058
  const baseUrl = options.serverUrl ?? "https://api-dex.chainstream.io";
8212
8059
  const streamUrl = options.streamUrl ?? "wss://realtime-dex.chainstream.io/connection/websocket";
8213
- const tokenProvider = typeof accessToken === "string" ? {
8214
- getToken: () => accessToken
8215
- } : accessToken;
8216
8060
  this.requestCtx = { baseUrl, streamUrl, accessToken };
8217
8061
  const config = new Configuration({
8218
8062
  basePath: baseUrl,
@@ -8242,7 +8086,9 @@ var DexClient = class {
8242
8086
  this.jobs = new JobsApi(config);
8243
8087
  this.kyt = new KYTApi(config);
8244
8088
  this.endpoint = new EndpointApi(config);
8245
- this.stream.connect();
8089
+ if (options.autoConnectWebSocket === true) {
8090
+ this.stream.connect();
8091
+ }
8246
8092
  }
8247
8093
  async waitForJob(jobId, timeout = 6e4) {
8248
8094
  const accessToken = typeof this.requestCtx.accessToken === "string" ? this.requestCtx.accessToken : await this.requestCtx.accessToken.getToken();