@nightlylabs/dex-sdk 0.3.35 → 0.3.37

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.cjs CHANGED
@@ -23578,6 +23578,7 @@ var EndpointsV1 = /* @__PURE__ */ ((EndpointsV12) => {
23578
23578
  EndpointsV12["GetIndexPrices"] = "/v1/get_index_prices";
23579
23579
  EndpointsV12["GetAccountValueRanking"] = "/v1/get_account_value_ranking";
23580
23580
  EndpointsV12["GetUserAccountValueRanking"] = "/v1/get_user_account_value_ranking";
23581
+ EndpointsV12["GetExchangeStatsHistory"] = "/v1/get_exchange_stats_history";
23581
23582
  return EndpointsV12;
23582
23583
  })(EndpointsV1 || {});
23583
23584
  var UserStatus = /* @__PURE__ */ ((UserStatus2) => {
@@ -23933,13 +23934,15 @@ var AccountSequenceNumber = class {
23933
23934
  // src/client.ts
23934
23935
  var getRandomId = () => (0, import_uuid.v7)();
23935
23936
  var Client = class _Client {
23936
- constructor(connection, enableWs, url, apiKey, chainId, params, networkMode = "testnet") {
23937
+ constructor(connection, enableWs, url, apiKey, chainId, params, networkMode = "testnet", wsDebug = false, timeout = 5e3) {
23937
23938
  this._apiKeySequenceNumber = 0;
23938
23939
  this._subscriptions = /* @__PURE__ */ new Map();
23939
23940
  this._gasUnitPrice = 100;
23940
23941
  this._expirationTimestampDelay = 20;
23941
23942
  // 20 seconds
23942
23943
  this.timeout = 5e3;
23944
+ // Same as below in init
23945
+ this.wsDebug = false;
23943
23946
  /////////////////////////////////// Sponsored transactions
23944
23947
  this.submitSponsoredTransaction = async (tx, signature) => {
23945
23948
  const payload = {
@@ -24389,13 +24392,25 @@ var Client = class _Client {
24389
24392
  this._maxGas = params?.maxGas || 2e4;
24390
24393
  this._gasUnitPrice = params?.gasUnitPrice || 100;
24391
24394
  this._expirationTimestampDelay = params?.expirationTimestampSecs || 20;
24395
+ this.wsDebug = wsDebug;
24396
+ this.timeout = timeout;
24392
24397
  if (enableWs) {
24393
24398
  this.connectWebSocket();
24394
24399
  }
24395
24400
  }
24396
- static async init(connection, enableWs = true, url, apiKey, chainId, params, networkMode = "testnet") {
24401
+ static async init(connection, enableWs = true, url, apiKey, chainId, params, networkMode = "testnet", wsDebug = false, timeout = 5e3) {
24397
24402
  const id = chainId || await connection.getChainId();
24398
- const client = new _Client(connection, enableWs, url, apiKey, id, params, networkMode);
24403
+ const client = new _Client(
24404
+ connection,
24405
+ enableWs,
24406
+ url,
24407
+ apiKey,
24408
+ id,
24409
+ params,
24410
+ networkMode,
24411
+ wsDebug,
24412
+ timeout
24413
+ );
24399
24414
  if (enableWs) {
24400
24415
  client.connectWebSocket();
24401
24416
  }
@@ -24429,11 +24444,21 @@ var Client = class _Client {
24429
24444
  * myApiKeyAccount // custom API key
24430
24445
  * )
24431
24446
  */
24432
- static async create(connection, networkMode = "testnet", enableWs = true, url, apiKey) {
24447
+ static async create(connection, networkMode = "testnet", enableWs = true, url, apiKey, wsDebug = false, timeout = 5e3) {
24433
24448
  const networkConfig = getNetworkConfig(networkMode);
24434
24449
  const apiUrl = url || networkConfig.apiUrl;
24435
24450
  const chainId = networkConfig.chainId;
24436
- return _Client.init(connection, enableWs, apiUrl, apiKey, chainId, void 0, networkMode);
24451
+ return _Client.init(
24452
+ connection,
24453
+ enableWs,
24454
+ apiUrl,
24455
+ apiKey,
24456
+ chainId,
24457
+ void 0,
24458
+ networkMode,
24459
+ wsDebug,
24460
+ timeout
24461
+ );
24437
24462
  }
24438
24463
  async setApiKey(apiKey) {
24439
24464
  this._apiKey = apiKey;
@@ -24459,21 +24484,60 @@ var Client = class _Client {
24459
24484
  this._expirationTimestampDelay = params.expirationTimestampSecs;
24460
24485
  }
24461
24486
  //////////////////////////////////////// Websocket functions
24487
+ _wsLog(...args) {
24488
+ if (this.wsDebug) console.log("[WS]", ...args);
24489
+ }
24490
+ setWsDebugActive(active) {
24491
+ this.wsDebug = active;
24492
+ }
24462
24493
  async connectWebSocket() {
24463
24494
  if (this._ws) {
24464
24495
  console.warn("WebSocket is already connected");
24465
24496
  return;
24466
24497
  }
24467
24498
  try {
24468
- this._ws = await _Client.initWebSocket(this._serverUrl, this.timeout);
24499
+ const wsUrl = `${this._serverUrl.replace("http", "ws").replace("https", "wss")}` + "/v1/ws" /* Ws */;
24500
+ this._wsLog("Connecting to", wsUrl);
24501
+ this._ws = new WebSocket(wsUrl);
24469
24502
  this._setupWebSocketHandlers();
24470
- return;
24503
+ await this._waitForOpen(this.timeout);
24504
+ this._wsLog("Connected");
24471
24505
  } catch (error) {
24506
+ this._wsLog("Connection failed:", error);
24507
+ this._ws = void 0;
24472
24508
  throw new Error(`Failed to connect WebSocket: ${error}`);
24473
24509
  }
24474
24510
  }
24511
+ _waitForOpen(timeout) {
24512
+ return new Promise((resolve, reject) => {
24513
+ if (!this._ws) return reject(new Error("No WebSocket"));
24514
+ if (this._ws.readyState === WebSocket.OPEN) {
24515
+ return resolve();
24516
+ }
24517
+ const timer = setTimeout(() => {
24518
+ this._wsLog("Connection timeout after", timeout, "ms");
24519
+ reject(new Error("WebSocket connection timeout"));
24520
+ }, timeout);
24521
+ const ws = this._ws;
24522
+ const origOnOpen = ws.onopen;
24523
+ ws.onopen = (event) => {
24524
+ clearTimeout(timer);
24525
+ origOnOpen?.call(ws, event);
24526
+ resolve();
24527
+ };
24528
+ const origOnError = ws.onerror;
24529
+ ws.onerror = (error) => {
24530
+ clearTimeout(timer);
24531
+ origOnError?.call(ws, error);
24532
+ reject(error);
24533
+ };
24534
+ });
24535
+ }
24475
24536
  _setupWebSocketHandlers() {
24476
24537
  if (!this._ws) return;
24538
+ this._ws.onopen = () => {
24539
+ this._wsLog("Opened");
24540
+ };
24477
24541
  this._ws.onmessage = async (msg) => {
24478
24542
  let data;
24479
24543
  if (msg.data.arrayBuffer) {
@@ -24482,49 +24546,52 @@ var Client = class _Client {
24482
24546
  data = msg.data;
24483
24547
  }
24484
24548
  const decodedMsg = JSON.parse(data);
24549
+ this._wsLog("Received:", decodedMsg.type, decodedMsg.content);
24485
24550
  const topic = getTopicFromMessage(decodedMsg);
24486
24551
  const callback = this._subscriptions.get(topic);
24487
24552
  if (callback) {
24488
24553
  callback(decodedMsg);
24554
+ } else {
24555
+ this._wsLog("No handler for topic:", topic);
24489
24556
  }
24490
24557
  };
24491
- }
24492
- static async initWebSocket(url, timeout = 5e3) {
24493
- return new Promise((resolve, reject) => {
24494
- const ws = new WebSocket(
24495
- `${url.replace("http", "ws").replace("https", "wss")}` + "/v1/ws" /* Ws */
24558
+ this._ws.onclose = (event) => {
24559
+ this._wsLog(
24560
+ "Closed: code=" + event.code,
24561
+ "reason=" + event.reason,
24562
+ "clean=" + event.wasClean
24496
24563
  );
24497
- const timer = setTimeout(() => {
24498
- reject(new Error("WebSocket connection timeout"));
24499
- }, timeout);
24500
- ws.onopen = () => {
24501
- clearTimeout(timer);
24502
- resolve(ws);
24503
- };
24504
- ws.onerror = (error) => {
24505
- clearTimeout(timer);
24506
- reject(error);
24507
- };
24508
- });
24564
+ this._ws = void 0;
24565
+ this._subscriptions.clear();
24566
+ this.onWsClose?.(event);
24567
+ };
24568
+ this._ws.onerror = (error) => {
24569
+ this._wsLog("Error:", error);
24570
+ };
24509
24571
  }
24510
24572
  async disconnectWebSocket() {
24511
24573
  if (!this._ws) {
24512
24574
  console.warn("WebSocket is not connected");
24513
24575
  return;
24514
24576
  }
24577
+ this._wsLog("Disconnecting, clearing", this._subscriptions.size, "subscriptions");
24515
24578
  this._subscriptions.clear();
24516
24579
  this._ws.close();
24517
24580
  this._ws = void 0;
24518
24581
  }
24519
24582
  // Method to check if WebSocket is connected
24520
24583
  isWebSocketConnected() {
24521
- return this._ws !== void 0 && this._ws.readyState === WebSocket.OPEN;
24584
+ const connected = this._ws !== void 0 && this._ws.readyState === WebSocket.OPEN;
24585
+ this._wsLog("isWebSocketConnected:", connected);
24586
+ return connected;
24522
24587
  }
24523
24588
  sendWsMessage(message) {
24524
24589
  if (!this._ws) throw new Error("WebSocket is not connected");
24525
24590
  return new Promise((resolve, reject) => {
24526
24591
  const topic = message.content.id;
24592
+ this._wsLog("Sending:", message.type, "id=" + topic);
24527
24593
  const timer = setTimeout(() => {
24594
+ this._wsLog("Timeout waiting for response:", message.type, "id=" + topic);
24528
24595
  reject(new Error(`Connection timed out after ${this.timeout} ms`));
24529
24596
  }, this.timeout);
24530
24597
  let handler = (response) => {
@@ -24532,11 +24599,13 @@ var Client = class _Client {
24532
24599
  this._subscriptions.delete(topic);
24533
24600
  if (response.type === "Error") {
24534
24601
  const errorMessage = response.content.message || "Unknown websocket error without message";
24602
+ this._wsLog("Error response:", errorMessage, "id=" + topic);
24535
24603
  reject(
24536
24604
  new Error(`WebSocket error (id: ${response.content.id}): ${errorMessage}`)
24537
24605
  );
24538
24606
  return;
24539
24607
  }
24608
+ this._wsLog("Ack received for:", message.type, "id=" + topic);
24540
24609
  resolve(response);
24541
24610
  };
24542
24611
  this._subscriptions.set(topic, handler);
package/dist/index.d.cts CHANGED
@@ -3682,6 +3682,7 @@ interface TokenConfigEntry {
3682
3682
  contractAddress: string;
3683
3683
  tokenDecimals: number;
3684
3684
  vaultId?: string;
3685
+ createdAt?: string;
3685
3686
  }
3686
3687
  interface MarginStep {
3687
3688
  initialMarginRatio: string;
@@ -3709,6 +3710,7 @@ interface PerpMarketConfigEntry {
3709
3710
  fundingRate: FundingRate;
3710
3711
  basicMakerFee: string;
3711
3712
  basicTakerFee: string;
3713
+ createdAt?: string;
3712
3714
  }
3713
3715
  interface SpotMarketConfigEntry {
3714
3716
  marketName: string;
@@ -3718,6 +3720,7 @@ interface SpotMarketConfigEntry {
3718
3720
  tickSize: string;
3719
3721
  basicMakerFee: string;
3720
3722
  basicTakerFee: string;
3723
+ createdAt?: string;
3721
3724
  }
3722
3725
  interface FeeData {
3723
3726
  feeToVaultAccount: string;
@@ -3731,6 +3734,19 @@ interface ExchangeConfig {
3731
3734
  feeData: FeeData;
3732
3735
  systemHaircut: string;
3733
3736
  }
3737
+ interface TvlTokenEntry {
3738
+ tokenAddress: string;
3739
+ amount: string;
3740
+ valueUsd: string;
3741
+ }
3742
+ interface ExchangeStatsEntry {
3743
+ timestampOpen: string;
3744
+ timestampClose: string;
3745
+ tvlBreakdown: TvlTokenEntry[];
3746
+ perpVolumeUsd: string;
3747
+ spotVolumeUsd: string;
3748
+ openInterestUsd: string;
3749
+ }
3734
3750
  interface FeeTier {
3735
3751
  volume: string;
3736
3752
  cashback: string;
@@ -3762,13 +3778,6 @@ interface GetAccountValueRankingResponse {
3762
3778
  usersRanking: AccountValueRankingEntry[];
3763
3779
  paginationCursor?: PaginationCursor;
3764
3780
  }
3765
- interface GetUserAccountValueRankingRequest {
3766
- userId?: string;
3767
- userAddress?: string;
3768
- }
3769
- interface GetUserAccountValueRankingResponse {
3770
- usersRanking: AccountValueRankingEntry[];
3771
- }
3772
3781
  interface GetAllVaultsIdsResponse {
3773
3782
  vaultsIds: string[];
3774
3783
  }
@@ -3811,6 +3820,15 @@ interface GetChartCandlesInRangeResponse {
3811
3820
  chartCandles: ChartCandle[];
3812
3821
  paginationCursor?: PaginationCursor;
3813
3822
  }
3823
+ interface GetExchangeStatsHistoryRequest {
3824
+ olderTimestampMs?: string;
3825
+ newerTimestampMs?: string;
3826
+ paginationCursor?: PaginationCursor;
3827
+ }
3828
+ interface GetExchangeStatsHistoryResponse {
3829
+ data: ExchangeStatsEntry[];
3830
+ paginationCursor?: PaginationCursor;
3831
+ }
3814
3832
  interface GetIndexPriceHistoryRequest {
3815
3833
  priceIndex: string;
3816
3834
  olderTimestampMs?: string;
@@ -4154,6 +4172,13 @@ interface PointsRankingEntry {
4154
4172
  interface GetTopPointsRankingResponse {
4155
4173
  usersRanking: PointsRankingEntry[];
4156
4174
  }
4175
+ interface GetUserAccountValueRankingRequest {
4176
+ userId?: string;
4177
+ userAddress?: string;
4178
+ }
4179
+ interface GetUserAccountValueRankingResponse {
4180
+ usersRanking: AccountValueRankingEntry[];
4181
+ }
4157
4182
  interface GetUserAggregatedBoxRewardsStatsRequest {
4158
4183
  userId: string;
4159
4184
  }
@@ -5159,7 +5184,8 @@ declare enum EndpointsV1 {
5159
5184
  GetUserPersonalPointsRanking = "/v1/get_user_personal_points_ranking",
5160
5185
  GetIndexPrices = "/v1/get_index_prices",
5161
5186
  GetAccountValueRanking = "/v1/get_account_value_ranking",
5162
- GetUserAccountValueRanking = "/v1/get_user_account_value_ranking"
5187
+ GetUserAccountValueRanking = "/v1/get_user_account_value_ranking",
5188
+ GetExchangeStatsHistory = "/v1/get_exchange_stats_history"
5163
5189
  }
5164
5190
  type Topic = {
5165
5191
  type: "PerpMarket";
@@ -5748,10 +5774,12 @@ declare class Client {
5748
5774
  _gasUnitPrice: number;
5749
5775
  _expirationTimestampDelay: number;
5750
5776
  timeout: number;
5777
+ wsDebug: boolean;
5778
+ onWsClose: ((event: CloseEvent) => void) | undefined;
5751
5779
  _abis: ReturnType<typeof getABIsForNetwork>;
5752
5780
  _contractAddress: string;
5753
- static init(connection: Aptos, enableWs?: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode): Promise<Client>;
5754
- constructor(connection: Aptos, enableWs: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode);
5781
+ static init(connection: Aptos, enableWs?: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode, wsDebug?: boolean, timeout?: number): Promise<Client>;
5782
+ constructor(connection: Aptos, enableWs: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode, wsDebug?: boolean, timeout?: number);
5755
5783
  /**
5756
5784
  * Create a new Client instance
5757
5785
  *
@@ -5780,15 +5808,17 @@ declare class Client {
5780
5808
  * myApiKeyAccount // custom API key
5781
5809
  * )
5782
5810
  */
5783
- static create(connection: Aptos, networkMode?: NetworkMode, enableWs?: boolean, url?: string, apiKey?: Account): Promise<Client>;
5811
+ static create(connection: Aptos, networkMode?: NetworkMode, enableWs?: boolean, url?: string, apiKey?: Account, wsDebug?: boolean, timeout?: number): Promise<Client>;
5784
5812
  setApiKey(apiKey: Account): Promise<void>;
5785
5813
  getContractAddress(): string;
5786
5814
  getApiKeySequenceNumber(): Promise<bigint | null>;
5787
5815
  fetchApiKeySequenceNumber(): Promise<number>;
5788
5816
  setTxParams(params: TxParams): void;
5817
+ private _wsLog;
5818
+ setWsDebugActive(active: boolean): void;
5789
5819
  connectWebSocket(): Promise<void>;
5820
+ private _waitForOpen;
5790
5821
  private _setupWebSocketHandlers;
5791
- static initWebSocket(url: string, timeout?: number): Promise<WebSocket>;
5792
5822
  disconnectWebSocket(): Promise<void>;
5793
5823
  isWebSocketConnected(): boolean;
5794
5824
  sendWsMessage(message: WsCommand): Promise<WsMessage>;
@@ -5947,4 +5977,4 @@ declare const generateApiKey: () => _aptos_labs_ts_sdk.Ed25519Account;
5947
5977
  declare const getTopicFromCommand: (data: WsCommand) => string;
5948
5978
  declare const getTopicFromMessage: (data: WsMessage) => string;
5949
5979
 
5950
- export { ABIs, type AccountValueRankingEntry, type AddApiCreditsParams, type AddApiKey, type AddApiKeyParams, type Address, AdminEndpoints, type ApiCreditsChange, type ApiStatus, type BalanceChange, BaseEndpoints, type Borrow, type BorrowLendUpdate, type BorrowLending, type BorrowLendingAggregatedData, type BorrowLendingHistoricalData, type BoxOpeningEvent, type BoxReward, BoxRewardTier, type CancelAllPerpOrdersParams, type CancelAllSpotOrdersParams, type CancelPerpOrdersParams, type CancelSpotOrdersParams, type CanceledPerpOrderData, type CanceledPerpOrders, type CanceledPerpTriggerOrderData, type CanceledPerpTriggerOrders, type CanceledSpotOrderData, type CanceledSpotOrders, type ChangePerpOrderParams, type ChangeSpotOrderParams, type ChartCandle, ChartInterval, type CheckReferralCodeRequest, type CheckReferralCodeResponse, type ClaimDepositParams, type ClaimKickbackFeeParams, type ClaimReferralFee, type ClaimReferralFeesParams, type ClaimUserKickbackFee, type ClaimedKickback, type ClaimedReferralKickback, Client, type Content, type CreateUserParams, type Deposit, type DepositToVaultParams, type DepositTokenParams, EndpointsV1, type ErrorResponse, type ExchangeConfig, ExchangeProxies, type FeeData, type FeeTier, type Fees, type FundingCheckpoint, type FundingPayment, type FundingRate, GLOBAL_DENOMINATOR, type GetAccountValueRankingRequest, type GetAccountValueRankingResponse, type GetAllVaultsIdsResponse, type GetBorrowLendingAggregatedStatsRequest, type GetBorrowLendingAggregatedStatsResponse, type GetBorrowLendingDataResponse, type GetBorrowLendingHistoricalDataRequest, type GetBorrowLendingHistoricalDataResponse, type GetChartCandlesInRangeRequest, type GetChartCandlesInRangeResponse, type GetIndexPriceHistoryRequest, type GetIndexPriceHistoryResponse, type GetIndexPricesResponse, type GetIndexerStatusResponse, type GetOrderBookDataRequest, type GetOrderBookDataResponse, type GetPerpMarketsConfigResponse, type GetPerpMarketsDataRequest, type GetPerpMarketsDataResponse, type GetPerpRecentTradesRequest, type GetPerpRecentTradesResponse, type GetPerpUserFillsRequest, type GetPerpUserFillsResponse, type GetPerpUserOrdersRequest, type GetPerpUserOrdersResponse, type GetPerpUserTriggerOrdersRequest, type GetPerpUserTriggerOrdersResponse, type GetPriceIndexesResponse, type GetServicesStatusResponse, type GetSpotMarketsConfigResponse, type GetSpotMarketsDataRequest, type GetSpotMarketsDataResponse, type GetSpotRecentTradesRequest, type GetSpotRecentTradesResponse, type GetSpotUserFillsRequest, type GetSpotUserFillsResponse, type GetSpotUserOrdersRequest, type GetSpotUserOrdersResponse, type GetTokenAggregatedStatsRequest, type GetTokenAggregatedStatsResponse, type GetTokenStatsHistoryRequest, type GetTokenStatsHistoryResponse, type GetTokensConfigResponse, type GetTopPointsRankingResponse, type GetUserAccountValueRankingRequest, type GetUserAccountValueRankingResponse, type GetUserAggregatedBoxRewardsStatsRequest, type GetUserAggregatedBoxRewardsStatsResponse, type GetUserAggregatedReferralStatsRequest, type GetUserAggregatedReferralStatsResponse, type GetUserAggregatedStatsRequest, type GetUserAggregatedStatsResponse, type GetUserAggregatedVaultStatsRequest, type GetUserAggregatedVaultStatsResponse, type GetUserBoxRewardsStatsHistoryRequest, type GetUserBoxRewardsStatsHistoryResponse, type GetUserBoxesHistoryRequest, type GetUserBoxesHistoryResponse, type GetUserClaimedKickbackHistoryRequest, type GetUserClaimedKickbackHistoryResponse, type GetUserClaimedReferralKickbackHistoryRequest, type GetUserClaimedReferralKickbackHistoryResponse, type GetUserDataRequest, type GetUserDataResponse, type GetUserDepositsRequest, type GetUserDepositsResponse, type GetUserFullLiquidationsHistoryRequest, type GetUserFundingHistoryRequest, type GetUserFundingHistoryResponse, type GetUserLiquidationsCancelHistoryResponse, type GetUserLiquidationsCancelOrdersHistoryRequest, type GetUserLiquidationsHistoryResponse, type GetUserPartialLiquidationsHistoryRequest, type GetUserPartialLiquidationsHistoryResponse, type GetUserPersonalPointsRankingRequest, type GetUserPersonalPointsRankingResponse, type GetUserPointsHistoryRequest, type GetUserPointsHistoryResponse, type GetUserPortfolioValueRequest, type GetUserPortfolioValueResponse, type GetUserReferralStatsHistoryRequest, type GetUserReferralStatsHistoryResponse, type GetUserRewardsValueRequest, type GetUserRewardsValueResponse, type GetUserTradeStatsHistoryRequest, type GetUserTradeStatsHistoryResponse, type GetUserTransferHistoryRequest, type GetUserTransferHistoryResponse, type GetUserVaultDepositsRequest, type GetUserVaultDepositsResponse, type GetUserVaultWithdrawsRequest, type GetUserVaultWithdrawsResponse, type GetUserVolumeForReferralRequest, type GetUserVolumeForReferralResponse, type GetUserWithdrawalsRequest, type GetUserWithdrawalsResponse, type GetUsersByAddressRequest, type GetUsersByAddressResponse, type GetVaultDepositsRequest, type GetVaultDepositsResponse, type GetVaultHistoricalDataRequest, type GetVaultHistoricalDataResponse, type GetVaultWithdrawalsRequest, type GetVaultWithdrawalsResponse, type GlobalLiquidation, type GlobalPartialLiquidation, type HistoricBoxReward, type HistoricalBoxRewardsStats, type HistoricalDeposit, type HistoricalFullLiquidation, type HistoricalFunding, type HistoricalLiquidatedBorrow, type HistoricalLiquidatedCollateral, type HistoricalLiquidatedLend, type HistoricalLiquidatedPosition, type HistoricalLiquidationCancelOrders, type HistoricalPartialLiquidatedPosition, type HistoricalPartialLiquidation, type HistoricalPerpOrder, type HistoricalPoints, type HistoricalReferralStats, type HistoricalSpotOrder, type HistoricalTokenStats, type HistoricalTradeStats, type HistoricalUserTransfer, type HistoricalVaultDeposit, type HistoricalVaultWithdraw, type HistoricalWithdraw, type IndexPriceHistory, type IndexPriceLive, type Lend, type LendTokenParams, type Liquidation, type LiquidationCancelledOrderData, type LiquidationCancelledTriggerOrderData, MAINNET_CONFIG, type MarginStep, Network, type NetworkConfig, type NetworkMode, type NodeStatus, type OpenBoxesRequest, type OpenBoxesResponse, type OpenBoxesSignRequest, type OracleUpdate, type OracleUpdates, type OrderBookData, OrderSide, OrderStatus, OrderType, type PaginationCursor, type PartialLiquidation, type PerpFill, type PerpMarketConfigEntry, type PerpMarketData, type PerpOrder, type PerpOrderData, type PerpOrderDataForMarket, type PerpOrderFills, type PerpOrderbookState, type PerpOrderbookUpdate, type PerpPosition, type PerpTrade, type PerpTradesUpdate, type PerpTriggerOrder, type PerpTriggerOrderTriggered, type PlaceMultiplePerpOrdersParams, type PlaceMultipleSpotOrdersParams, type PlacePerpLimitOrder, type PlacePerpMarketOrder, type PlacePerpOrderParams, type PlacePerpTriggerOrder, type PlacePerpTriggerOrderParams, type PlaceSpotLimitOrder, type PlaceSpotMarketOrder, type PlaceSpotOrderParams, type PointsRankingEntry, type PriceIndex, type RedeemTokenParams, type Referral, type ReferralUpdate, type RemoveApiKey, type RemoveApiKeyParams, type RemoveApiKeySignerParams, type RepayBorrow, type ReplaceMultipleOrdersParams, type ReplaceMultipleSpotOrdersParams, type SetAlias, type SetAliasNameParams, type SetAutoLend, type SetAutolendParams, type SetReferralCodeParams, type SetReferralParamsRequest, type SetReferralParamsResponse, type SpotFill, type SpotMarketConfigEntry, type SpotMarketData, type SpotOrder, type SpotOrderData, type SpotOrderDataForMarket, type SpotOrderFills, type SpotOrderbookState, type SpotOrderbookUpdate, type SpotTrade, type SpotTradesUpdate, Status, type StatusResponse, type SubServiceStatus, type SubmitSponsoredTransactionRequest, type SubmitSponsoredTransactionResponse, TESTNET_CONFIG, TestFaucet, type TimeResponse, type TokenAggregatedStats, type TokenConfigEntry, type TokenizeUserVaultInvestmentParams, type Topic, type Trade, TradeRole, TransferAction, type TransferToUserParams, type TriggerOrder, type TxParams, type UpdateUserFeeTier, type User, type UserAggregatedBoxRewardsStats, type UserAggregatedReferralStats, type UserAggregatedStats, type UserAggregatedVaultStats, type UserBoxOpeningEvent, type UserPointsBreakdown, type UserPortfolioValue, type UserRewardsValue, UserStatus, type UserTransfer, type UtilizationCurve, type Vault, type VaultDeposit, type VaultHistoricalData, type VaultInvestment, type VaultWithdraw, type Withdraw, type WithdrawFromVaultParams, type WithdrawLend, type WithdrawTokenParams, type WsBorrowLendUpdate, type WsBoxOpeningUpdate, type WsCommand, type WsFill, type WsLiquidatedBorrow, type WsLiquidatedCollateral, type WsLiquidatedLend, type WsLiquidatedPosition, type WsLiquidationUpdate, type WsMessage, type WsOracleUpdates, type WsPartialLiquidatedPosition, type WsPerpMarketUpdates, type WsSpotMarketUpdates, type WsUserUpdates, createAptosClient, createAptosClientFromEnv, generateApiKey, getABIsForNetwork, getNetworkConfig, getNetworkModeFromEnv, getRandomId, getTopicFromCommand, getTopicFromMessage, nowInMiliseconds, parseEntryFunctionAbi, sleep, toSystemValue };
5980
+ export { ABIs, type AccountValueRankingEntry, type AddApiCreditsParams, type AddApiKey, type AddApiKeyParams, type Address, AdminEndpoints, type ApiCreditsChange, type ApiStatus, type BalanceChange, BaseEndpoints, type Borrow, type BorrowLendUpdate, type BorrowLending, type BorrowLendingAggregatedData, type BorrowLendingHistoricalData, type BoxOpeningEvent, type BoxReward, BoxRewardTier, type CancelAllPerpOrdersParams, type CancelAllSpotOrdersParams, type CancelPerpOrdersParams, type CancelSpotOrdersParams, type CanceledPerpOrderData, type CanceledPerpOrders, type CanceledPerpTriggerOrderData, type CanceledPerpTriggerOrders, type CanceledSpotOrderData, type CanceledSpotOrders, type ChangePerpOrderParams, type ChangeSpotOrderParams, type ChartCandle, ChartInterval, type CheckReferralCodeRequest, type CheckReferralCodeResponse, type ClaimDepositParams, type ClaimKickbackFeeParams, type ClaimReferralFee, type ClaimReferralFeesParams, type ClaimUserKickbackFee, type ClaimedKickback, type ClaimedReferralKickback, Client, type Content, type CreateUserParams, type Deposit, type DepositToVaultParams, type DepositTokenParams, EndpointsV1, type ErrorResponse, type ExchangeConfig, ExchangeProxies, type ExchangeStatsEntry, type FeeData, type FeeTier, type Fees, type FundingCheckpoint, type FundingPayment, type FundingRate, GLOBAL_DENOMINATOR, type GetAccountValueRankingRequest, type GetAccountValueRankingResponse, type GetAllVaultsIdsResponse, type GetBorrowLendingAggregatedStatsRequest, type GetBorrowLendingAggregatedStatsResponse, type GetBorrowLendingDataResponse, type GetBorrowLendingHistoricalDataRequest, type GetBorrowLendingHistoricalDataResponse, type GetChartCandlesInRangeRequest, type GetChartCandlesInRangeResponse, type GetExchangeStatsHistoryRequest, type GetExchangeStatsHistoryResponse, type GetIndexPriceHistoryRequest, type GetIndexPriceHistoryResponse, type GetIndexPricesResponse, type GetIndexerStatusResponse, type GetOrderBookDataRequest, type GetOrderBookDataResponse, type GetPerpMarketsConfigResponse, type GetPerpMarketsDataRequest, type GetPerpMarketsDataResponse, type GetPerpRecentTradesRequest, type GetPerpRecentTradesResponse, type GetPerpUserFillsRequest, type GetPerpUserFillsResponse, type GetPerpUserOrdersRequest, type GetPerpUserOrdersResponse, type GetPerpUserTriggerOrdersRequest, type GetPerpUserTriggerOrdersResponse, type GetPriceIndexesResponse, type GetServicesStatusResponse, type GetSpotMarketsConfigResponse, type GetSpotMarketsDataRequest, type GetSpotMarketsDataResponse, type GetSpotRecentTradesRequest, type GetSpotRecentTradesResponse, type GetSpotUserFillsRequest, type GetSpotUserFillsResponse, type GetSpotUserOrdersRequest, type GetSpotUserOrdersResponse, type GetTokenAggregatedStatsRequest, type GetTokenAggregatedStatsResponse, type GetTokenStatsHistoryRequest, type GetTokenStatsHistoryResponse, type GetTokensConfigResponse, type GetTopPointsRankingResponse, type GetUserAccountValueRankingRequest, type GetUserAccountValueRankingResponse, type GetUserAggregatedBoxRewardsStatsRequest, type GetUserAggregatedBoxRewardsStatsResponse, type GetUserAggregatedReferralStatsRequest, type GetUserAggregatedReferralStatsResponse, type GetUserAggregatedStatsRequest, type GetUserAggregatedStatsResponse, type GetUserAggregatedVaultStatsRequest, type GetUserAggregatedVaultStatsResponse, type GetUserBoxRewardsStatsHistoryRequest, type GetUserBoxRewardsStatsHistoryResponse, type GetUserBoxesHistoryRequest, type GetUserBoxesHistoryResponse, type GetUserClaimedKickbackHistoryRequest, type GetUserClaimedKickbackHistoryResponse, type GetUserClaimedReferralKickbackHistoryRequest, type GetUserClaimedReferralKickbackHistoryResponse, type GetUserDataRequest, type GetUserDataResponse, type GetUserDepositsRequest, type GetUserDepositsResponse, type GetUserFullLiquidationsHistoryRequest, type GetUserFundingHistoryRequest, type GetUserFundingHistoryResponse, type GetUserLiquidationsCancelHistoryResponse, type GetUserLiquidationsCancelOrdersHistoryRequest, type GetUserLiquidationsHistoryResponse, type GetUserPartialLiquidationsHistoryRequest, type GetUserPartialLiquidationsHistoryResponse, type GetUserPersonalPointsRankingRequest, type GetUserPersonalPointsRankingResponse, type GetUserPointsHistoryRequest, type GetUserPointsHistoryResponse, type GetUserPortfolioValueRequest, type GetUserPortfolioValueResponse, type GetUserReferralStatsHistoryRequest, type GetUserReferralStatsHistoryResponse, type GetUserRewardsValueRequest, type GetUserRewardsValueResponse, type GetUserTradeStatsHistoryRequest, type GetUserTradeStatsHistoryResponse, type GetUserTransferHistoryRequest, type GetUserTransferHistoryResponse, type GetUserVaultDepositsRequest, type GetUserVaultDepositsResponse, type GetUserVaultWithdrawsRequest, type GetUserVaultWithdrawsResponse, type GetUserVolumeForReferralRequest, type GetUserVolumeForReferralResponse, type GetUserWithdrawalsRequest, type GetUserWithdrawalsResponse, type GetUsersByAddressRequest, type GetUsersByAddressResponse, type GetVaultDepositsRequest, type GetVaultDepositsResponse, type GetVaultHistoricalDataRequest, type GetVaultHistoricalDataResponse, type GetVaultWithdrawalsRequest, type GetVaultWithdrawalsResponse, type GlobalLiquidation, type GlobalPartialLiquidation, type HistoricBoxReward, type HistoricalBoxRewardsStats, type HistoricalDeposit, type HistoricalFullLiquidation, type HistoricalFunding, type HistoricalLiquidatedBorrow, type HistoricalLiquidatedCollateral, type HistoricalLiquidatedLend, type HistoricalLiquidatedPosition, type HistoricalLiquidationCancelOrders, type HistoricalPartialLiquidatedPosition, type HistoricalPartialLiquidation, type HistoricalPerpOrder, type HistoricalPoints, type HistoricalReferralStats, type HistoricalSpotOrder, type HistoricalTokenStats, type HistoricalTradeStats, type HistoricalUserTransfer, type HistoricalVaultDeposit, type HistoricalVaultWithdraw, type HistoricalWithdraw, type IndexPriceHistory, type IndexPriceLive, type Lend, type LendTokenParams, type Liquidation, type LiquidationCancelledOrderData, type LiquidationCancelledTriggerOrderData, MAINNET_CONFIG, type MarginStep, Network, type NetworkConfig, type NetworkMode, type NodeStatus, type OpenBoxesRequest, type OpenBoxesResponse, type OpenBoxesSignRequest, type OracleUpdate, type OracleUpdates, type OrderBookData, OrderSide, OrderStatus, OrderType, type PaginationCursor, type PartialLiquidation, type PerpFill, type PerpMarketConfigEntry, type PerpMarketData, type PerpOrder, type PerpOrderData, type PerpOrderDataForMarket, type PerpOrderFills, type PerpOrderbookState, type PerpOrderbookUpdate, type PerpPosition, type PerpTrade, type PerpTradesUpdate, type PerpTriggerOrder, type PerpTriggerOrderTriggered, type PlaceMultiplePerpOrdersParams, type PlaceMultipleSpotOrdersParams, type PlacePerpLimitOrder, type PlacePerpMarketOrder, type PlacePerpOrderParams, type PlacePerpTriggerOrder, type PlacePerpTriggerOrderParams, type PlaceSpotLimitOrder, type PlaceSpotMarketOrder, type PlaceSpotOrderParams, type PointsRankingEntry, type PriceIndex, type RedeemTokenParams, type Referral, type ReferralUpdate, type RemoveApiKey, type RemoveApiKeyParams, type RemoveApiKeySignerParams, type RepayBorrow, type ReplaceMultipleOrdersParams, type ReplaceMultipleSpotOrdersParams, type SetAlias, type SetAliasNameParams, type SetAutoLend, type SetAutolendParams, type SetReferralCodeParams, type SetReferralParamsRequest, type SetReferralParamsResponse, type SpotFill, type SpotMarketConfigEntry, type SpotMarketData, type SpotOrder, type SpotOrderData, type SpotOrderDataForMarket, type SpotOrderFills, type SpotOrderbookState, type SpotOrderbookUpdate, type SpotTrade, type SpotTradesUpdate, Status, type StatusResponse, type SubServiceStatus, type SubmitSponsoredTransactionRequest, type SubmitSponsoredTransactionResponse, TESTNET_CONFIG, TestFaucet, type TimeResponse, type TokenAggregatedStats, type TokenConfigEntry, type TokenizeUserVaultInvestmentParams, type Topic, type Trade, TradeRole, TransferAction, type TransferToUserParams, type TriggerOrder, type TvlTokenEntry, type TxParams, type UpdateUserFeeTier, type User, type UserAggregatedBoxRewardsStats, type UserAggregatedReferralStats, type UserAggregatedStats, type UserAggregatedVaultStats, type UserBoxOpeningEvent, type UserPointsBreakdown, type UserPortfolioValue, type UserRewardsValue, UserStatus, type UserTransfer, type UtilizationCurve, type Vault, type VaultDeposit, type VaultHistoricalData, type VaultInvestment, type VaultWithdraw, type Withdraw, type WithdrawFromVaultParams, type WithdrawLend, type WithdrawTokenParams, type WsBorrowLendUpdate, type WsBoxOpeningUpdate, type WsCommand, type WsFill, type WsLiquidatedBorrow, type WsLiquidatedCollateral, type WsLiquidatedLend, type WsLiquidatedPosition, type WsLiquidationUpdate, type WsMessage, type WsOracleUpdates, type WsPartialLiquidatedPosition, type WsPerpMarketUpdates, type WsSpotMarketUpdates, type WsUserUpdates, createAptosClient, createAptosClientFromEnv, generateApiKey, getABIsForNetwork, getNetworkConfig, getNetworkModeFromEnv, getRandomId, getTopicFromCommand, getTopicFromMessage, nowInMiliseconds, parseEntryFunctionAbi, sleep, toSystemValue };
package/dist/index.d.ts CHANGED
@@ -3682,6 +3682,7 @@ interface TokenConfigEntry {
3682
3682
  contractAddress: string;
3683
3683
  tokenDecimals: number;
3684
3684
  vaultId?: string;
3685
+ createdAt?: string;
3685
3686
  }
3686
3687
  interface MarginStep {
3687
3688
  initialMarginRatio: string;
@@ -3709,6 +3710,7 @@ interface PerpMarketConfigEntry {
3709
3710
  fundingRate: FundingRate;
3710
3711
  basicMakerFee: string;
3711
3712
  basicTakerFee: string;
3713
+ createdAt?: string;
3712
3714
  }
3713
3715
  interface SpotMarketConfigEntry {
3714
3716
  marketName: string;
@@ -3718,6 +3720,7 @@ interface SpotMarketConfigEntry {
3718
3720
  tickSize: string;
3719
3721
  basicMakerFee: string;
3720
3722
  basicTakerFee: string;
3723
+ createdAt?: string;
3721
3724
  }
3722
3725
  interface FeeData {
3723
3726
  feeToVaultAccount: string;
@@ -3731,6 +3734,19 @@ interface ExchangeConfig {
3731
3734
  feeData: FeeData;
3732
3735
  systemHaircut: string;
3733
3736
  }
3737
+ interface TvlTokenEntry {
3738
+ tokenAddress: string;
3739
+ amount: string;
3740
+ valueUsd: string;
3741
+ }
3742
+ interface ExchangeStatsEntry {
3743
+ timestampOpen: string;
3744
+ timestampClose: string;
3745
+ tvlBreakdown: TvlTokenEntry[];
3746
+ perpVolumeUsd: string;
3747
+ spotVolumeUsd: string;
3748
+ openInterestUsd: string;
3749
+ }
3734
3750
  interface FeeTier {
3735
3751
  volume: string;
3736
3752
  cashback: string;
@@ -3762,13 +3778,6 @@ interface GetAccountValueRankingResponse {
3762
3778
  usersRanking: AccountValueRankingEntry[];
3763
3779
  paginationCursor?: PaginationCursor;
3764
3780
  }
3765
- interface GetUserAccountValueRankingRequest {
3766
- userId?: string;
3767
- userAddress?: string;
3768
- }
3769
- interface GetUserAccountValueRankingResponse {
3770
- usersRanking: AccountValueRankingEntry[];
3771
- }
3772
3781
  interface GetAllVaultsIdsResponse {
3773
3782
  vaultsIds: string[];
3774
3783
  }
@@ -3811,6 +3820,15 @@ interface GetChartCandlesInRangeResponse {
3811
3820
  chartCandles: ChartCandle[];
3812
3821
  paginationCursor?: PaginationCursor;
3813
3822
  }
3823
+ interface GetExchangeStatsHistoryRequest {
3824
+ olderTimestampMs?: string;
3825
+ newerTimestampMs?: string;
3826
+ paginationCursor?: PaginationCursor;
3827
+ }
3828
+ interface GetExchangeStatsHistoryResponse {
3829
+ data: ExchangeStatsEntry[];
3830
+ paginationCursor?: PaginationCursor;
3831
+ }
3814
3832
  interface GetIndexPriceHistoryRequest {
3815
3833
  priceIndex: string;
3816
3834
  olderTimestampMs?: string;
@@ -4154,6 +4172,13 @@ interface PointsRankingEntry {
4154
4172
  interface GetTopPointsRankingResponse {
4155
4173
  usersRanking: PointsRankingEntry[];
4156
4174
  }
4175
+ interface GetUserAccountValueRankingRequest {
4176
+ userId?: string;
4177
+ userAddress?: string;
4178
+ }
4179
+ interface GetUserAccountValueRankingResponse {
4180
+ usersRanking: AccountValueRankingEntry[];
4181
+ }
4157
4182
  interface GetUserAggregatedBoxRewardsStatsRequest {
4158
4183
  userId: string;
4159
4184
  }
@@ -5159,7 +5184,8 @@ declare enum EndpointsV1 {
5159
5184
  GetUserPersonalPointsRanking = "/v1/get_user_personal_points_ranking",
5160
5185
  GetIndexPrices = "/v1/get_index_prices",
5161
5186
  GetAccountValueRanking = "/v1/get_account_value_ranking",
5162
- GetUserAccountValueRanking = "/v1/get_user_account_value_ranking"
5187
+ GetUserAccountValueRanking = "/v1/get_user_account_value_ranking",
5188
+ GetExchangeStatsHistory = "/v1/get_exchange_stats_history"
5163
5189
  }
5164
5190
  type Topic = {
5165
5191
  type: "PerpMarket";
@@ -5748,10 +5774,12 @@ declare class Client {
5748
5774
  _gasUnitPrice: number;
5749
5775
  _expirationTimestampDelay: number;
5750
5776
  timeout: number;
5777
+ wsDebug: boolean;
5778
+ onWsClose: ((event: CloseEvent) => void) | undefined;
5751
5779
  _abis: ReturnType<typeof getABIsForNetwork>;
5752
5780
  _contractAddress: string;
5753
- static init(connection: Aptos, enableWs?: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode): Promise<Client>;
5754
- constructor(connection: Aptos, enableWs: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode);
5781
+ static init(connection: Aptos, enableWs?: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode, wsDebug?: boolean, timeout?: number): Promise<Client>;
5782
+ constructor(connection: Aptos, enableWs: boolean, url?: string, apiKey?: Account, chainId?: number, params?: TxParams, networkMode?: NetworkMode, wsDebug?: boolean, timeout?: number);
5755
5783
  /**
5756
5784
  * Create a new Client instance
5757
5785
  *
@@ -5780,15 +5808,17 @@ declare class Client {
5780
5808
  * myApiKeyAccount // custom API key
5781
5809
  * )
5782
5810
  */
5783
- static create(connection: Aptos, networkMode?: NetworkMode, enableWs?: boolean, url?: string, apiKey?: Account): Promise<Client>;
5811
+ static create(connection: Aptos, networkMode?: NetworkMode, enableWs?: boolean, url?: string, apiKey?: Account, wsDebug?: boolean, timeout?: number): Promise<Client>;
5784
5812
  setApiKey(apiKey: Account): Promise<void>;
5785
5813
  getContractAddress(): string;
5786
5814
  getApiKeySequenceNumber(): Promise<bigint | null>;
5787
5815
  fetchApiKeySequenceNumber(): Promise<number>;
5788
5816
  setTxParams(params: TxParams): void;
5817
+ private _wsLog;
5818
+ setWsDebugActive(active: boolean): void;
5789
5819
  connectWebSocket(): Promise<void>;
5820
+ private _waitForOpen;
5790
5821
  private _setupWebSocketHandlers;
5791
- static initWebSocket(url: string, timeout?: number): Promise<WebSocket>;
5792
5822
  disconnectWebSocket(): Promise<void>;
5793
5823
  isWebSocketConnected(): boolean;
5794
5824
  sendWsMessage(message: WsCommand): Promise<WsMessage>;
@@ -5947,4 +5977,4 @@ declare const generateApiKey: () => _aptos_labs_ts_sdk.Ed25519Account;
5947
5977
  declare const getTopicFromCommand: (data: WsCommand) => string;
5948
5978
  declare const getTopicFromMessage: (data: WsMessage) => string;
5949
5979
 
5950
- export { ABIs, type AccountValueRankingEntry, type AddApiCreditsParams, type AddApiKey, type AddApiKeyParams, type Address, AdminEndpoints, type ApiCreditsChange, type ApiStatus, type BalanceChange, BaseEndpoints, type Borrow, type BorrowLendUpdate, type BorrowLending, type BorrowLendingAggregatedData, type BorrowLendingHistoricalData, type BoxOpeningEvent, type BoxReward, BoxRewardTier, type CancelAllPerpOrdersParams, type CancelAllSpotOrdersParams, type CancelPerpOrdersParams, type CancelSpotOrdersParams, type CanceledPerpOrderData, type CanceledPerpOrders, type CanceledPerpTriggerOrderData, type CanceledPerpTriggerOrders, type CanceledSpotOrderData, type CanceledSpotOrders, type ChangePerpOrderParams, type ChangeSpotOrderParams, type ChartCandle, ChartInterval, type CheckReferralCodeRequest, type CheckReferralCodeResponse, type ClaimDepositParams, type ClaimKickbackFeeParams, type ClaimReferralFee, type ClaimReferralFeesParams, type ClaimUserKickbackFee, type ClaimedKickback, type ClaimedReferralKickback, Client, type Content, type CreateUserParams, type Deposit, type DepositToVaultParams, type DepositTokenParams, EndpointsV1, type ErrorResponse, type ExchangeConfig, ExchangeProxies, type FeeData, type FeeTier, type Fees, type FundingCheckpoint, type FundingPayment, type FundingRate, GLOBAL_DENOMINATOR, type GetAccountValueRankingRequest, type GetAccountValueRankingResponse, type GetAllVaultsIdsResponse, type GetBorrowLendingAggregatedStatsRequest, type GetBorrowLendingAggregatedStatsResponse, type GetBorrowLendingDataResponse, type GetBorrowLendingHistoricalDataRequest, type GetBorrowLendingHistoricalDataResponse, type GetChartCandlesInRangeRequest, type GetChartCandlesInRangeResponse, type GetIndexPriceHistoryRequest, type GetIndexPriceHistoryResponse, type GetIndexPricesResponse, type GetIndexerStatusResponse, type GetOrderBookDataRequest, type GetOrderBookDataResponse, type GetPerpMarketsConfigResponse, type GetPerpMarketsDataRequest, type GetPerpMarketsDataResponse, type GetPerpRecentTradesRequest, type GetPerpRecentTradesResponse, type GetPerpUserFillsRequest, type GetPerpUserFillsResponse, type GetPerpUserOrdersRequest, type GetPerpUserOrdersResponse, type GetPerpUserTriggerOrdersRequest, type GetPerpUserTriggerOrdersResponse, type GetPriceIndexesResponse, type GetServicesStatusResponse, type GetSpotMarketsConfigResponse, type GetSpotMarketsDataRequest, type GetSpotMarketsDataResponse, type GetSpotRecentTradesRequest, type GetSpotRecentTradesResponse, type GetSpotUserFillsRequest, type GetSpotUserFillsResponse, type GetSpotUserOrdersRequest, type GetSpotUserOrdersResponse, type GetTokenAggregatedStatsRequest, type GetTokenAggregatedStatsResponse, type GetTokenStatsHistoryRequest, type GetTokenStatsHistoryResponse, type GetTokensConfigResponse, type GetTopPointsRankingResponse, type GetUserAccountValueRankingRequest, type GetUserAccountValueRankingResponse, type GetUserAggregatedBoxRewardsStatsRequest, type GetUserAggregatedBoxRewardsStatsResponse, type GetUserAggregatedReferralStatsRequest, type GetUserAggregatedReferralStatsResponse, type GetUserAggregatedStatsRequest, type GetUserAggregatedStatsResponse, type GetUserAggregatedVaultStatsRequest, type GetUserAggregatedVaultStatsResponse, type GetUserBoxRewardsStatsHistoryRequest, type GetUserBoxRewardsStatsHistoryResponse, type GetUserBoxesHistoryRequest, type GetUserBoxesHistoryResponse, type GetUserClaimedKickbackHistoryRequest, type GetUserClaimedKickbackHistoryResponse, type GetUserClaimedReferralKickbackHistoryRequest, type GetUserClaimedReferralKickbackHistoryResponse, type GetUserDataRequest, type GetUserDataResponse, type GetUserDepositsRequest, type GetUserDepositsResponse, type GetUserFullLiquidationsHistoryRequest, type GetUserFundingHistoryRequest, type GetUserFundingHistoryResponse, type GetUserLiquidationsCancelHistoryResponse, type GetUserLiquidationsCancelOrdersHistoryRequest, type GetUserLiquidationsHistoryResponse, type GetUserPartialLiquidationsHistoryRequest, type GetUserPartialLiquidationsHistoryResponse, type GetUserPersonalPointsRankingRequest, type GetUserPersonalPointsRankingResponse, type GetUserPointsHistoryRequest, type GetUserPointsHistoryResponse, type GetUserPortfolioValueRequest, type GetUserPortfolioValueResponse, type GetUserReferralStatsHistoryRequest, type GetUserReferralStatsHistoryResponse, type GetUserRewardsValueRequest, type GetUserRewardsValueResponse, type GetUserTradeStatsHistoryRequest, type GetUserTradeStatsHistoryResponse, type GetUserTransferHistoryRequest, type GetUserTransferHistoryResponse, type GetUserVaultDepositsRequest, type GetUserVaultDepositsResponse, type GetUserVaultWithdrawsRequest, type GetUserVaultWithdrawsResponse, type GetUserVolumeForReferralRequest, type GetUserVolumeForReferralResponse, type GetUserWithdrawalsRequest, type GetUserWithdrawalsResponse, type GetUsersByAddressRequest, type GetUsersByAddressResponse, type GetVaultDepositsRequest, type GetVaultDepositsResponse, type GetVaultHistoricalDataRequest, type GetVaultHistoricalDataResponse, type GetVaultWithdrawalsRequest, type GetVaultWithdrawalsResponse, type GlobalLiquidation, type GlobalPartialLiquidation, type HistoricBoxReward, type HistoricalBoxRewardsStats, type HistoricalDeposit, type HistoricalFullLiquidation, type HistoricalFunding, type HistoricalLiquidatedBorrow, type HistoricalLiquidatedCollateral, type HistoricalLiquidatedLend, type HistoricalLiquidatedPosition, type HistoricalLiquidationCancelOrders, type HistoricalPartialLiquidatedPosition, type HistoricalPartialLiquidation, type HistoricalPerpOrder, type HistoricalPoints, type HistoricalReferralStats, type HistoricalSpotOrder, type HistoricalTokenStats, type HistoricalTradeStats, type HistoricalUserTransfer, type HistoricalVaultDeposit, type HistoricalVaultWithdraw, type HistoricalWithdraw, type IndexPriceHistory, type IndexPriceLive, type Lend, type LendTokenParams, type Liquidation, type LiquidationCancelledOrderData, type LiquidationCancelledTriggerOrderData, MAINNET_CONFIG, type MarginStep, Network, type NetworkConfig, type NetworkMode, type NodeStatus, type OpenBoxesRequest, type OpenBoxesResponse, type OpenBoxesSignRequest, type OracleUpdate, type OracleUpdates, type OrderBookData, OrderSide, OrderStatus, OrderType, type PaginationCursor, type PartialLiquidation, type PerpFill, type PerpMarketConfigEntry, type PerpMarketData, type PerpOrder, type PerpOrderData, type PerpOrderDataForMarket, type PerpOrderFills, type PerpOrderbookState, type PerpOrderbookUpdate, type PerpPosition, type PerpTrade, type PerpTradesUpdate, type PerpTriggerOrder, type PerpTriggerOrderTriggered, type PlaceMultiplePerpOrdersParams, type PlaceMultipleSpotOrdersParams, type PlacePerpLimitOrder, type PlacePerpMarketOrder, type PlacePerpOrderParams, type PlacePerpTriggerOrder, type PlacePerpTriggerOrderParams, type PlaceSpotLimitOrder, type PlaceSpotMarketOrder, type PlaceSpotOrderParams, type PointsRankingEntry, type PriceIndex, type RedeemTokenParams, type Referral, type ReferralUpdate, type RemoveApiKey, type RemoveApiKeyParams, type RemoveApiKeySignerParams, type RepayBorrow, type ReplaceMultipleOrdersParams, type ReplaceMultipleSpotOrdersParams, type SetAlias, type SetAliasNameParams, type SetAutoLend, type SetAutolendParams, type SetReferralCodeParams, type SetReferralParamsRequest, type SetReferralParamsResponse, type SpotFill, type SpotMarketConfigEntry, type SpotMarketData, type SpotOrder, type SpotOrderData, type SpotOrderDataForMarket, type SpotOrderFills, type SpotOrderbookState, type SpotOrderbookUpdate, type SpotTrade, type SpotTradesUpdate, Status, type StatusResponse, type SubServiceStatus, type SubmitSponsoredTransactionRequest, type SubmitSponsoredTransactionResponse, TESTNET_CONFIG, TestFaucet, type TimeResponse, type TokenAggregatedStats, type TokenConfigEntry, type TokenizeUserVaultInvestmentParams, type Topic, type Trade, TradeRole, TransferAction, type TransferToUserParams, type TriggerOrder, type TxParams, type UpdateUserFeeTier, type User, type UserAggregatedBoxRewardsStats, type UserAggregatedReferralStats, type UserAggregatedStats, type UserAggregatedVaultStats, type UserBoxOpeningEvent, type UserPointsBreakdown, type UserPortfolioValue, type UserRewardsValue, UserStatus, type UserTransfer, type UtilizationCurve, type Vault, type VaultDeposit, type VaultHistoricalData, type VaultInvestment, type VaultWithdraw, type Withdraw, type WithdrawFromVaultParams, type WithdrawLend, type WithdrawTokenParams, type WsBorrowLendUpdate, type WsBoxOpeningUpdate, type WsCommand, type WsFill, type WsLiquidatedBorrow, type WsLiquidatedCollateral, type WsLiquidatedLend, type WsLiquidatedPosition, type WsLiquidationUpdate, type WsMessage, type WsOracleUpdates, type WsPartialLiquidatedPosition, type WsPerpMarketUpdates, type WsSpotMarketUpdates, type WsUserUpdates, createAptosClient, createAptosClientFromEnv, generateApiKey, getABIsForNetwork, getNetworkConfig, getNetworkModeFromEnv, getRandomId, getTopicFromCommand, getTopicFromMessage, nowInMiliseconds, parseEntryFunctionAbi, sleep, toSystemValue };
5980
+ export { ABIs, type AccountValueRankingEntry, type AddApiCreditsParams, type AddApiKey, type AddApiKeyParams, type Address, AdminEndpoints, type ApiCreditsChange, type ApiStatus, type BalanceChange, BaseEndpoints, type Borrow, type BorrowLendUpdate, type BorrowLending, type BorrowLendingAggregatedData, type BorrowLendingHistoricalData, type BoxOpeningEvent, type BoxReward, BoxRewardTier, type CancelAllPerpOrdersParams, type CancelAllSpotOrdersParams, type CancelPerpOrdersParams, type CancelSpotOrdersParams, type CanceledPerpOrderData, type CanceledPerpOrders, type CanceledPerpTriggerOrderData, type CanceledPerpTriggerOrders, type CanceledSpotOrderData, type CanceledSpotOrders, type ChangePerpOrderParams, type ChangeSpotOrderParams, type ChartCandle, ChartInterval, type CheckReferralCodeRequest, type CheckReferralCodeResponse, type ClaimDepositParams, type ClaimKickbackFeeParams, type ClaimReferralFee, type ClaimReferralFeesParams, type ClaimUserKickbackFee, type ClaimedKickback, type ClaimedReferralKickback, Client, type Content, type CreateUserParams, type Deposit, type DepositToVaultParams, type DepositTokenParams, EndpointsV1, type ErrorResponse, type ExchangeConfig, ExchangeProxies, type ExchangeStatsEntry, type FeeData, type FeeTier, type Fees, type FundingCheckpoint, type FundingPayment, type FundingRate, GLOBAL_DENOMINATOR, type GetAccountValueRankingRequest, type GetAccountValueRankingResponse, type GetAllVaultsIdsResponse, type GetBorrowLendingAggregatedStatsRequest, type GetBorrowLendingAggregatedStatsResponse, type GetBorrowLendingDataResponse, type GetBorrowLendingHistoricalDataRequest, type GetBorrowLendingHistoricalDataResponse, type GetChartCandlesInRangeRequest, type GetChartCandlesInRangeResponse, type GetExchangeStatsHistoryRequest, type GetExchangeStatsHistoryResponse, type GetIndexPriceHistoryRequest, type GetIndexPriceHistoryResponse, type GetIndexPricesResponse, type GetIndexerStatusResponse, type GetOrderBookDataRequest, type GetOrderBookDataResponse, type GetPerpMarketsConfigResponse, type GetPerpMarketsDataRequest, type GetPerpMarketsDataResponse, type GetPerpRecentTradesRequest, type GetPerpRecentTradesResponse, type GetPerpUserFillsRequest, type GetPerpUserFillsResponse, type GetPerpUserOrdersRequest, type GetPerpUserOrdersResponse, type GetPerpUserTriggerOrdersRequest, type GetPerpUserTriggerOrdersResponse, type GetPriceIndexesResponse, type GetServicesStatusResponse, type GetSpotMarketsConfigResponse, type GetSpotMarketsDataRequest, type GetSpotMarketsDataResponse, type GetSpotRecentTradesRequest, type GetSpotRecentTradesResponse, type GetSpotUserFillsRequest, type GetSpotUserFillsResponse, type GetSpotUserOrdersRequest, type GetSpotUserOrdersResponse, type GetTokenAggregatedStatsRequest, type GetTokenAggregatedStatsResponse, type GetTokenStatsHistoryRequest, type GetTokenStatsHistoryResponse, type GetTokensConfigResponse, type GetTopPointsRankingResponse, type GetUserAccountValueRankingRequest, type GetUserAccountValueRankingResponse, type GetUserAggregatedBoxRewardsStatsRequest, type GetUserAggregatedBoxRewardsStatsResponse, type GetUserAggregatedReferralStatsRequest, type GetUserAggregatedReferralStatsResponse, type GetUserAggregatedStatsRequest, type GetUserAggregatedStatsResponse, type GetUserAggregatedVaultStatsRequest, type GetUserAggregatedVaultStatsResponse, type GetUserBoxRewardsStatsHistoryRequest, type GetUserBoxRewardsStatsHistoryResponse, type GetUserBoxesHistoryRequest, type GetUserBoxesHistoryResponse, type GetUserClaimedKickbackHistoryRequest, type GetUserClaimedKickbackHistoryResponse, type GetUserClaimedReferralKickbackHistoryRequest, type GetUserClaimedReferralKickbackHistoryResponse, type GetUserDataRequest, type GetUserDataResponse, type GetUserDepositsRequest, type GetUserDepositsResponse, type GetUserFullLiquidationsHistoryRequest, type GetUserFundingHistoryRequest, type GetUserFundingHistoryResponse, type GetUserLiquidationsCancelHistoryResponse, type GetUserLiquidationsCancelOrdersHistoryRequest, type GetUserLiquidationsHistoryResponse, type GetUserPartialLiquidationsHistoryRequest, type GetUserPartialLiquidationsHistoryResponse, type GetUserPersonalPointsRankingRequest, type GetUserPersonalPointsRankingResponse, type GetUserPointsHistoryRequest, type GetUserPointsHistoryResponse, type GetUserPortfolioValueRequest, type GetUserPortfolioValueResponse, type GetUserReferralStatsHistoryRequest, type GetUserReferralStatsHistoryResponse, type GetUserRewardsValueRequest, type GetUserRewardsValueResponse, type GetUserTradeStatsHistoryRequest, type GetUserTradeStatsHistoryResponse, type GetUserTransferHistoryRequest, type GetUserTransferHistoryResponse, type GetUserVaultDepositsRequest, type GetUserVaultDepositsResponse, type GetUserVaultWithdrawsRequest, type GetUserVaultWithdrawsResponse, type GetUserVolumeForReferralRequest, type GetUserVolumeForReferralResponse, type GetUserWithdrawalsRequest, type GetUserWithdrawalsResponse, type GetUsersByAddressRequest, type GetUsersByAddressResponse, type GetVaultDepositsRequest, type GetVaultDepositsResponse, type GetVaultHistoricalDataRequest, type GetVaultHistoricalDataResponse, type GetVaultWithdrawalsRequest, type GetVaultWithdrawalsResponse, type GlobalLiquidation, type GlobalPartialLiquidation, type HistoricBoxReward, type HistoricalBoxRewardsStats, type HistoricalDeposit, type HistoricalFullLiquidation, type HistoricalFunding, type HistoricalLiquidatedBorrow, type HistoricalLiquidatedCollateral, type HistoricalLiquidatedLend, type HistoricalLiquidatedPosition, type HistoricalLiquidationCancelOrders, type HistoricalPartialLiquidatedPosition, type HistoricalPartialLiquidation, type HistoricalPerpOrder, type HistoricalPoints, type HistoricalReferralStats, type HistoricalSpotOrder, type HistoricalTokenStats, type HistoricalTradeStats, type HistoricalUserTransfer, type HistoricalVaultDeposit, type HistoricalVaultWithdraw, type HistoricalWithdraw, type IndexPriceHistory, type IndexPriceLive, type Lend, type LendTokenParams, type Liquidation, type LiquidationCancelledOrderData, type LiquidationCancelledTriggerOrderData, MAINNET_CONFIG, type MarginStep, Network, type NetworkConfig, type NetworkMode, type NodeStatus, type OpenBoxesRequest, type OpenBoxesResponse, type OpenBoxesSignRequest, type OracleUpdate, type OracleUpdates, type OrderBookData, OrderSide, OrderStatus, OrderType, type PaginationCursor, type PartialLiquidation, type PerpFill, type PerpMarketConfigEntry, type PerpMarketData, type PerpOrder, type PerpOrderData, type PerpOrderDataForMarket, type PerpOrderFills, type PerpOrderbookState, type PerpOrderbookUpdate, type PerpPosition, type PerpTrade, type PerpTradesUpdate, type PerpTriggerOrder, type PerpTriggerOrderTriggered, type PlaceMultiplePerpOrdersParams, type PlaceMultipleSpotOrdersParams, type PlacePerpLimitOrder, type PlacePerpMarketOrder, type PlacePerpOrderParams, type PlacePerpTriggerOrder, type PlacePerpTriggerOrderParams, type PlaceSpotLimitOrder, type PlaceSpotMarketOrder, type PlaceSpotOrderParams, type PointsRankingEntry, type PriceIndex, type RedeemTokenParams, type Referral, type ReferralUpdate, type RemoveApiKey, type RemoveApiKeyParams, type RemoveApiKeySignerParams, type RepayBorrow, type ReplaceMultipleOrdersParams, type ReplaceMultipleSpotOrdersParams, type SetAlias, type SetAliasNameParams, type SetAutoLend, type SetAutolendParams, type SetReferralCodeParams, type SetReferralParamsRequest, type SetReferralParamsResponse, type SpotFill, type SpotMarketConfigEntry, type SpotMarketData, type SpotOrder, type SpotOrderData, type SpotOrderDataForMarket, type SpotOrderFills, type SpotOrderbookState, type SpotOrderbookUpdate, type SpotTrade, type SpotTradesUpdate, Status, type StatusResponse, type SubServiceStatus, type SubmitSponsoredTransactionRequest, type SubmitSponsoredTransactionResponse, TESTNET_CONFIG, TestFaucet, type TimeResponse, type TokenAggregatedStats, type TokenConfigEntry, type TokenizeUserVaultInvestmentParams, type Topic, type Trade, TradeRole, TransferAction, type TransferToUserParams, type TriggerOrder, type TvlTokenEntry, type TxParams, type UpdateUserFeeTier, type User, type UserAggregatedBoxRewardsStats, type UserAggregatedReferralStats, type UserAggregatedStats, type UserAggregatedVaultStats, type UserBoxOpeningEvent, type UserPointsBreakdown, type UserPortfolioValue, type UserRewardsValue, UserStatus, type UserTransfer, type UtilizationCurve, type Vault, type VaultDeposit, type VaultHistoricalData, type VaultInvestment, type VaultWithdraw, type Withdraw, type WithdrawFromVaultParams, type WithdrawLend, type WithdrawTokenParams, type WsBorrowLendUpdate, type WsBoxOpeningUpdate, type WsCommand, type WsFill, type WsLiquidatedBorrow, type WsLiquidatedCollateral, type WsLiquidatedLend, type WsLiquidatedPosition, type WsLiquidationUpdate, type WsMessage, type WsOracleUpdates, type WsPartialLiquidatedPosition, type WsPerpMarketUpdates, type WsSpotMarketUpdates, type WsUserUpdates, createAptosClient, createAptosClientFromEnv, generateApiKey, getABIsForNetwork, getNetworkConfig, getNetworkModeFromEnv, getRandomId, getTopicFromCommand, getTopicFromMessage, nowInMiliseconds, parseEntryFunctionAbi, sleep, toSystemValue };
package/dist/index.js CHANGED
@@ -23536,6 +23536,7 @@ var EndpointsV1 = /* @__PURE__ */ ((EndpointsV12) => {
23536
23536
  EndpointsV12["GetIndexPrices"] = "/v1/get_index_prices";
23537
23537
  EndpointsV12["GetAccountValueRanking"] = "/v1/get_account_value_ranking";
23538
23538
  EndpointsV12["GetUserAccountValueRanking"] = "/v1/get_user_account_value_ranking";
23539
+ EndpointsV12["GetExchangeStatsHistory"] = "/v1/get_exchange_stats_history";
23539
23540
  return EndpointsV12;
23540
23541
  })(EndpointsV1 || {});
23541
23542
  var UserStatus = /* @__PURE__ */ ((UserStatus2) => {
@@ -23891,13 +23892,15 @@ var AccountSequenceNumber = class {
23891
23892
  // src/client.ts
23892
23893
  var getRandomId = () => uuidv7();
23893
23894
  var Client = class _Client {
23894
- constructor(connection, enableWs, url, apiKey, chainId, params, networkMode = "testnet") {
23895
+ constructor(connection, enableWs, url, apiKey, chainId, params, networkMode = "testnet", wsDebug = false, timeout = 5e3) {
23895
23896
  this._apiKeySequenceNumber = 0;
23896
23897
  this._subscriptions = /* @__PURE__ */ new Map();
23897
23898
  this._gasUnitPrice = 100;
23898
23899
  this._expirationTimestampDelay = 20;
23899
23900
  // 20 seconds
23900
23901
  this.timeout = 5e3;
23902
+ // Same as below in init
23903
+ this.wsDebug = false;
23901
23904
  /////////////////////////////////// Sponsored transactions
23902
23905
  this.submitSponsoredTransaction = async (tx, signature) => {
23903
23906
  const payload = {
@@ -24347,13 +24350,25 @@ var Client = class _Client {
24347
24350
  this._maxGas = params?.maxGas || 2e4;
24348
24351
  this._gasUnitPrice = params?.gasUnitPrice || 100;
24349
24352
  this._expirationTimestampDelay = params?.expirationTimestampSecs || 20;
24353
+ this.wsDebug = wsDebug;
24354
+ this.timeout = timeout;
24350
24355
  if (enableWs) {
24351
24356
  this.connectWebSocket();
24352
24357
  }
24353
24358
  }
24354
- static async init(connection, enableWs = true, url, apiKey, chainId, params, networkMode = "testnet") {
24359
+ static async init(connection, enableWs = true, url, apiKey, chainId, params, networkMode = "testnet", wsDebug = false, timeout = 5e3) {
24355
24360
  const id = chainId || await connection.getChainId();
24356
- const client = new _Client(connection, enableWs, url, apiKey, id, params, networkMode);
24361
+ const client = new _Client(
24362
+ connection,
24363
+ enableWs,
24364
+ url,
24365
+ apiKey,
24366
+ id,
24367
+ params,
24368
+ networkMode,
24369
+ wsDebug,
24370
+ timeout
24371
+ );
24357
24372
  if (enableWs) {
24358
24373
  client.connectWebSocket();
24359
24374
  }
@@ -24387,11 +24402,21 @@ var Client = class _Client {
24387
24402
  * myApiKeyAccount // custom API key
24388
24403
  * )
24389
24404
  */
24390
- static async create(connection, networkMode = "testnet", enableWs = true, url, apiKey) {
24405
+ static async create(connection, networkMode = "testnet", enableWs = true, url, apiKey, wsDebug = false, timeout = 5e3) {
24391
24406
  const networkConfig = getNetworkConfig(networkMode);
24392
24407
  const apiUrl = url || networkConfig.apiUrl;
24393
24408
  const chainId = networkConfig.chainId;
24394
- return _Client.init(connection, enableWs, apiUrl, apiKey, chainId, void 0, networkMode);
24409
+ return _Client.init(
24410
+ connection,
24411
+ enableWs,
24412
+ apiUrl,
24413
+ apiKey,
24414
+ chainId,
24415
+ void 0,
24416
+ networkMode,
24417
+ wsDebug,
24418
+ timeout
24419
+ );
24395
24420
  }
24396
24421
  async setApiKey(apiKey) {
24397
24422
  this._apiKey = apiKey;
@@ -24417,21 +24442,60 @@ var Client = class _Client {
24417
24442
  this._expirationTimestampDelay = params.expirationTimestampSecs;
24418
24443
  }
24419
24444
  //////////////////////////////////////// Websocket functions
24445
+ _wsLog(...args) {
24446
+ if (this.wsDebug) console.log("[WS]", ...args);
24447
+ }
24448
+ setWsDebugActive(active) {
24449
+ this.wsDebug = active;
24450
+ }
24420
24451
  async connectWebSocket() {
24421
24452
  if (this._ws) {
24422
24453
  console.warn("WebSocket is already connected");
24423
24454
  return;
24424
24455
  }
24425
24456
  try {
24426
- this._ws = await _Client.initWebSocket(this._serverUrl, this.timeout);
24457
+ const wsUrl = `${this._serverUrl.replace("http", "ws").replace("https", "wss")}` + "/v1/ws" /* Ws */;
24458
+ this._wsLog("Connecting to", wsUrl);
24459
+ this._ws = new WebSocket(wsUrl);
24427
24460
  this._setupWebSocketHandlers();
24428
- return;
24461
+ await this._waitForOpen(this.timeout);
24462
+ this._wsLog("Connected");
24429
24463
  } catch (error) {
24464
+ this._wsLog("Connection failed:", error);
24465
+ this._ws = void 0;
24430
24466
  throw new Error(`Failed to connect WebSocket: ${error}`);
24431
24467
  }
24432
24468
  }
24469
+ _waitForOpen(timeout) {
24470
+ return new Promise((resolve, reject) => {
24471
+ if (!this._ws) return reject(new Error("No WebSocket"));
24472
+ if (this._ws.readyState === WebSocket.OPEN) {
24473
+ return resolve();
24474
+ }
24475
+ const timer = setTimeout(() => {
24476
+ this._wsLog("Connection timeout after", timeout, "ms");
24477
+ reject(new Error("WebSocket connection timeout"));
24478
+ }, timeout);
24479
+ const ws = this._ws;
24480
+ const origOnOpen = ws.onopen;
24481
+ ws.onopen = (event) => {
24482
+ clearTimeout(timer);
24483
+ origOnOpen?.call(ws, event);
24484
+ resolve();
24485
+ };
24486
+ const origOnError = ws.onerror;
24487
+ ws.onerror = (error) => {
24488
+ clearTimeout(timer);
24489
+ origOnError?.call(ws, error);
24490
+ reject(error);
24491
+ };
24492
+ });
24493
+ }
24433
24494
  _setupWebSocketHandlers() {
24434
24495
  if (!this._ws) return;
24496
+ this._ws.onopen = () => {
24497
+ this._wsLog("Opened");
24498
+ };
24435
24499
  this._ws.onmessage = async (msg) => {
24436
24500
  let data;
24437
24501
  if (msg.data.arrayBuffer) {
@@ -24440,49 +24504,52 @@ var Client = class _Client {
24440
24504
  data = msg.data;
24441
24505
  }
24442
24506
  const decodedMsg = JSON.parse(data);
24507
+ this._wsLog("Received:", decodedMsg.type, decodedMsg.content);
24443
24508
  const topic = getTopicFromMessage(decodedMsg);
24444
24509
  const callback = this._subscriptions.get(topic);
24445
24510
  if (callback) {
24446
24511
  callback(decodedMsg);
24512
+ } else {
24513
+ this._wsLog("No handler for topic:", topic);
24447
24514
  }
24448
24515
  };
24449
- }
24450
- static async initWebSocket(url, timeout = 5e3) {
24451
- return new Promise((resolve, reject) => {
24452
- const ws = new WebSocket(
24453
- `${url.replace("http", "ws").replace("https", "wss")}` + "/v1/ws" /* Ws */
24516
+ this._ws.onclose = (event) => {
24517
+ this._wsLog(
24518
+ "Closed: code=" + event.code,
24519
+ "reason=" + event.reason,
24520
+ "clean=" + event.wasClean
24454
24521
  );
24455
- const timer = setTimeout(() => {
24456
- reject(new Error("WebSocket connection timeout"));
24457
- }, timeout);
24458
- ws.onopen = () => {
24459
- clearTimeout(timer);
24460
- resolve(ws);
24461
- };
24462
- ws.onerror = (error) => {
24463
- clearTimeout(timer);
24464
- reject(error);
24465
- };
24466
- });
24522
+ this._ws = void 0;
24523
+ this._subscriptions.clear();
24524
+ this.onWsClose?.(event);
24525
+ };
24526
+ this._ws.onerror = (error) => {
24527
+ this._wsLog("Error:", error);
24528
+ };
24467
24529
  }
24468
24530
  async disconnectWebSocket() {
24469
24531
  if (!this._ws) {
24470
24532
  console.warn("WebSocket is not connected");
24471
24533
  return;
24472
24534
  }
24535
+ this._wsLog("Disconnecting, clearing", this._subscriptions.size, "subscriptions");
24473
24536
  this._subscriptions.clear();
24474
24537
  this._ws.close();
24475
24538
  this._ws = void 0;
24476
24539
  }
24477
24540
  // Method to check if WebSocket is connected
24478
24541
  isWebSocketConnected() {
24479
- return this._ws !== void 0 && this._ws.readyState === WebSocket.OPEN;
24542
+ const connected = this._ws !== void 0 && this._ws.readyState === WebSocket.OPEN;
24543
+ this._wsLog("isWebSocketConnected:", connected);
24544
+ return connected;
24480
24545
  }
24481
24546
  sendWsMessage(message) {
24482
24547
  if (!this._ws) throw new Error("WebSocket is not connected");
24483
24548
  return new Promise((resolve, reject) => {
24484
24549
  const topic = message.content.id;
24550
+ this._wsLog("Sending:", message.type, "id=" + topic);
24485
24551
  const timer = setTimeout(() => {
24552
+ this._wsLog("Timeout waiting for response:", message.type, "id=" + topic);
24486
24553
  reject(new Error(`Connection timed out after ${this.timeout} ms`));
24487
24554
  }, this.timeout);
24488
24555
  let handler = (response) => {
@@ -24490,11 +24557,13 @@ var Client = class _Client {
24490
24557
  this._subscriptions.delete(topic);
24491
24558
  if (response.type === "Error") {
24492
24559
  const errorMessage = response.content.message || "Unknown websocket error without message";
24560
+ this._wsLog("Error response:", errorMessage, "id=" + topic);
24493
24561
  reject(
24494
24562
  new Error(`WebSocket error (id: ${response.content.id}): ${errorMessage}`)
24495
24563
  );
24496
24564
  return;
24497
24565
  }
24566
+ this._wsLog("Ack received for:", message.type, "id=" + topic);
24498
24567
  resolve(response);
24499
24568
  };
24500
24569
  this._subscriptions.set(topic, handler);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nightlylabs/dex-sdk",
3
- "version": "0.3.35",
3
+ "version": "0.3.37",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {