@pear-protocol/symmio-client 0.3.15 → 0.3.17

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.
@@ -73,6 +73,7 @@ var RECONNECT_DELAYS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
73
73
  var IDLE_CLOSE_DELAY_MS = 3e4;
74
74
  var STALE_CONNECTION_MS = 3e4;
75
75
  var STALE_CHECK_INTERVAL_MS = 1e4;
76
+ var RECONNECT_RESET_MS = 6e4;
76
77
  var STABLE_QUOTES = ["USDT0", "USDT", "USDC", "USDE", "USDH", "USD"];
77
78
  function normalizeBaseSymbol(symbol) {
78
79
  const normalized = symbol.toUpperCase().trim();
@@ -124,6 +125,7 @@ var BinanceWsManager = class {
124
125
  reconnectTimer = null;
125
126
  idleCloseTimer = null;
126
127
  staleCheckTimer = null;
128
+ reconnectResetTimer = null;
127
129
  intentionalClose = false;
128
130
  pendingSubscribes = /* @__PURE__ */ new Set();
129
131
  lastMessageAt = 0;
@@ -162,6 +164,7 @@ var BinanceWsManager = class {
162
164
  const wrappedCb = (raw) => {
163
165
  cb({
164
166
  symbol: normalizeBaseSymbol(raw.s),
167
+ binanceSymbol: raw.s,
165
168
  markPrice: parseFloat(raw.p),
166
169
  indexPrice: parseFloat(raw.i),
167
170
  time: raw.E,
@@ -183,6 +186,7 @@ var BinanceWsManager = class {
183
186
  cb(
184
187
  extractTickers(raw).map((entry) => ({
185
188
  symbol: normalizeBaseSymbol(entry.s),
189
+ binanceSymbol: entry.s,
186
190
  markPrice: parseFloat(entry.p),
187
191
  indexPrice: parseFloat(entry.i),
188
192
  time: entry.E,
@@ -202,6 +206,7 @@ var BinanceWsManager = class {
202
206
  this.clearReconnectTimer();
203
207
  this.clearIdleCloseTimer();
204
208
  this.clearStaleCheckTimer();
209
+ this.clearReconnectResetTimer();
205
210
  this.pendingSubscribes.clear();
206
211
  if (this.ws) {
207
212
  this.ws.close();
@@ -255,9 +260,9 @@ var BinanceWsManager = class {
255
260
  this.intentionalClose = false;
256
261
  this.ws = new WebSocket(BINANCE_WS_URL);
257
262
  this.ws.onopen = () => {
258
- this.reconnectAttempt = 0;
259
263
  this.lastMessageAt = Date.now();
260
264
  this.startStaleCheck();
265
+ this.scheduleReconnectReset();
261
266
  const activeStreams = Array.from(
262
267
  /* @__PURE__ */ new Set([...this.streams.keys(), ...this.pendingSubscribes])
263
268
  );
@@ -270,6 +275,7 @@ var BinanceWsManager = class {
270
275
  try {
271
276
  const data = JSON.parse(event.data);
272
277
  this.lastMessageAt = Date.now();
278
+ this.resetReconnectAttempt();
273
279
  this.handleMessage(data);
274
280
  } catch {
275
281
  }
@@ -279,6 +285,7 @@ var BinanceWsManager = class {
279
285
  this.intentionalClose = false;
280
286
  this.ws = null;
281
287
  this.clearStaleCheckTimer();
288
+ this.clearReconnectResetTimer();
282
289
  if (this.streams.size === 0) {
283
290
  return;
284
291
  }
@@ -372,6 +379,17 @@ var BinanceWsManager = class {
372
379
  this.ws.close();
373
380
  }, STALE_CHECK_INTERVAL_MS);
374
381
  }
382
+ scheduleReconnectReset() {
383
+ this.clearReconnectResetTimer();
384
+ this.reconnectResetTimer = setTimeout(() => {
385
+ this.reconnectResetTimer = null;
386
+ this.resetReconnectAttempt();
387
+ }, RECONNECT_RESET_MS);
388
+ }
389
+ resetReconnectAttempt() {
390
+ this.reconnectAttempt = 0;
391
+ this.clearReconnectResetTimer();
392
+ }
375
393
  clearReconnectTimer() {
376
394
  if (!this.reconnectTimer) return;
377
395
  clearTimeout(this.reconnectTimer);
@@ -387,6 +405,11 @@ var BinanceWsManager = class {
387
405
  clearInterval(this.staleCheckTimer);
388
406
  this.staleCheckTimer = null;
389
407
  }
408
+ clearReconnectResetTimer() {
409
+ if (!this.reconnectResetTimer) return;
410
+ clearTimeout(this.reconnectResetTimer);
411
+ this.reconnectResetTimer = null;
412
+ }
390
413
  };
391
414
  var BINANCE_WS_SINGLETON_KEY = "__pearBinanceWsManager__";
392
415
  function getBinanceWsManager() {
@@ -404,15 +427,8 @@ var refCounts = /* @__PURE__ */ new Map();
404
427
  var streamSymbols = /* @__PURE__ */ new Map();
405
428
  var allMarkPricesRefCount = 0;
406
429
  var allMarkPricesUnsubscribe = null;
407
- var STABLE_QUOTES2 = ["USDT0", "USDT", "USDC", "USDE", "USDH", "USD"];
408
- function normalizeBinanceSymbol(symbol) {
409
- const normalized = symbol.toUpperCase().trim();
410
- for (const quote of STABLE_QUOTES2) {
411
- if (normalized.endsWith(quote) && normalized.length > quote.length) {
412
- return normalized.slice(0, -quote.length);
413
- }
414
- }
415
- return normalized;
430
+ function normalizeBinanceSymbolKey(symbol) {
431
+ return symbol.toUpperCase().trim();
416
432
  }
417
433
  function getNextRefCount(binanceSymbol) {
418
434
  return (refCounts.get(binanceSymbol) ?? 0) + 1;
@@ -447,7 +463,7 @@ var useBinanceMarkPriceStore = create((set) => ({
447
463
  fundingRates: {},
448
464
  nextFundingTimes: {},
449
465
  subscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
450
- const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
466
+ const binanceSymbol = normalizeBinanceSymbolKey(rawBinanceSymbol);
451
467
  const nextRefCount = getNextRefCount(binanceSymbol);
452
468
  refCounts.set(binanceSymbol, nextRefCount);
453
469
  addMappedSymbol(binanceSymbol, symmSymbol);
@@ -459,8 +475,10 @@ var useBinanceMarkPriceStore = create((set) => ({
459
475
  let nextFundingRates = null;
460
476
  let nextFundingTimes = null;
461
477
  entries.forEach((entry) => {
462
- const canonicalSymbol = normalizeBinanceSymbol(entry.symbol);
463
- const mappedSymbols = streamSymbols.get(canonicalSymbol);
478
+ const binanceSymbolKey = normalizeBinanceSymbolKey(
479
+ entry.binanceSymbol ?? entry.symbol
480
+ );
481
+ const mappedSymbols = streamSymbols.get(binanceSymbolKey);
464
482
  if (!mappedSymbols || mappedSymbols.size === 0) return;
465
483
  nextMarkPrices ??= { ...state.markPrices };
466
484
  nextFundingRates ??= { ...state.fundingRates };
@@ -485,7 +503,7 @@ var useBinanceMarkPriceStore = create((set) => ({
485
503
  allMarkPricesRefCount += 1;
486
504
  },
487
505
  unsubscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
488
- const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
506
+ const binanceSymbol = normalizeBinanceSymbolKey(rawBinanceSymbol);
489
507
  const removedSubscription = removeMappedSymbol(binanceSymbol, symmSymbol);
490
508
  if (!removedSubscription) {
491
509
  return;
@@ -525,6 +543,7 @@ var useBinanceMarkPriceStore = create((set) => ({
525
543
  }));
526
544
 
527
545
  // src/react/hooks/use-binance-ws.ts
546
+ var BOOTSTRAP_RETRY_DELAYS_MS = [1e3, 2e3, 5e3];
528
547
  function useBinanceWs(params) {
529
548
  const { symmCoreClient, chainId } = params;
530
549
  const subscribeSymbol = useBinanceMarkPriceStore((state) => state.subscribeSymbol);
@@ -535,7 +554,8 @@ function useBinanceWs(params) {
535
554
  }
536
555
  let cancelled = false;
537
556
  let subscribedPairs = [];
538
- const run = async () => {
557
+ let retryTimer = null;
558
+ const run = async (attempt = 0) => {
539
559
  try {
540
560
  const result = await symmCoreClient.markets.listSymmHedger({ chainId });
541
561
  if (cancelled) {
@@ -555,11 +575,22 @@ function useBinanceWs(params) {
555
575
  subscribeSymbol(symbol, binanceSymbol);
556
576
  });
557
577
  } catch {
578
+ const delay = BOOTSTRAP_RETRY_DELAYS_MS[attempt];
579
+ if (cancelled || delay == null) {
580
+ return;
581
+ }
582
+ retryTimer = setTimeout(() => {
583
+ retryTimer = null;
584
+ void run(attempt + 1);
585
+ }, delay);
558
586
  }
559
587
  };
560
588
  void run();
561
589
  return () => {
562
590
  cancelled = true;
591
+ if (retryTimer) {
592
+ clearTimeout(retryTimer);
593
+ }
563
594
  subscribedPairs.forEach(([symbol, binanceSymbol]) => {
564
595
  unsubscribeSymbol(symbol, binanceSymbol);
565
596
  });
@@ -600,6 +631,7 @@ var symmKeys = {
600
631
  triggerOrders: (params) => ["symm", "triggerOrders", params],
601
632
  triggerConfig: (orderId) => ["symm", "triggerConfig", orderId],
602
633
  markets: (chainId, search, pageSize) => ["symm", "markets", chainId, search, pageSize],
634
+ marketPositioning: (chainId, market) => ["symm", "marketPositioning", chainId, market],
603
635
  hedgerMarketById: (id, chainId) => ["symm", "hedgerMarketById", id, chainId],
604
636
  hedgerMarketBySymbol: (symbol, chainId) => ["symm", "hedgerMarketBySymbol", symbol, chainId],
605
637
  lockedParams: (marketName, leverage, chainId) => ["symm", "lockedParams", marketName, leverage, chainId],
@@ -1672,6 +1704,7 @@ var SymmioSDKError = class extends Error {
1672
1704
  this.code = code;
1673
1705
  this.name = "SymmioSDKError";
1674
1706
  }
1707
+ code;
1675
1708
  };
1676
1709
  function validateAddress(address, name) {
1677
1710
  if (!isAddress(address)) {
@@ -25893,15 +25926,24 @@ function readTimestamp(source) {
25893
25926
  const parsed = Number(timestamp);
25894
25927
  return Number.isFinite(parsed) ? parsed : void 0;
25895
25928
  }
25929
+ function hasAccountDataShape(value) {
25930
+ return isRecord(value) && ("equity" in value || "maintenanceMargin" in value || "availableForOrder" in value || "totalLocked" in value);
25931
+ }
25896
25932
  function getSymmAccountData(response) {
25897
25933
  if (!isRecord(response)) {
25898
25934
  return void 0;
25899
25935
  }
25900
25936
  const data = response.data;
25901
25937
  if (isRecord(data)) {
25902
- return data;
25938
+ if (hasAccountDataShape(data.accountData)) {
25939
+ return data.accountData;
25940
+ }
25941
+ if (hasAccountDataShape(data)) {
25942
+ return data;
25943
+ }
25944
+ return void 0;
25903
25945
  }
25904
- if ("equity" in response || "maintenanceMargin" in response || "availableForOrder" in response || "totalLocked" in response) {
25946
+ if (hasAccountDataShape(response)) {
25905
25947
  return response;
25906
25948
  }
25907
25949
  return void 0;
@@ -26117,7 +26159,7 @@ function useSymmAccountOverview(params) {
26117
26159
  chainId: params.chainId,
26118
26160
  query: {
26119
26161
  ...params.query,
26120
- enabled: upnlReady && (params.query?.enabled ?? true)
26162
+ enabled: params.query?.enabled ?? true
26121
26163
  }
26122
26164
  });
26123
26165
  const data = useMemo(() => {
@@ -26639,6 +26681,34 @@ function useSymmMarkets(params) {
26639
26681
  enabled: internalEnabled && (params?.query?.enabled ?? true)
26640
26682
  });
26641
26683
  }
26684
+ function normalizeMarket(market) {
26685
+ if (Array.isArray(market)) {
26686
+ const markets = market.map((marketName2) => marketName2.trim()).filter((marketName2) => marketName2.length > 0);
26687
+ return markets.length > 0 ? markets : void 0;
26688
+ }
26689
+ const marketName = market?.trim();
26690
+ return marketName ? marketName : void 0;
26691
+ }
26692
+ function hasMarket(market) {
26693
+ return Array.isArray(market) ? market.length > 0 : market !== void 0;
26694
+ }
26695
+ function useSymmMarketPositioning(params) {
26696
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
26697
+ const chainId = params?.chainId ?? ctxChainId;
26698
+ const market = normalizeMarket(params?.market);
26699
+ const internalEnabled = !!symmCoreClient && hasMarket(market);
26700
+ return useQuery({
26701
+ ...params?.query,
26702
+ queryKey: symmKeys.marketPositioning(chainId, market),
26703
+ queryFn: () => {
26704
+ if (!hasMarket(market)) {
26705
+ throw new Error("Market is required to fetch positioning");
26706
+ }
26707
+ return symmCoreClient.markets.getPositioning({ chainId, market });
26708
+ },
26709
+ enabled: internalEnabled && (params?.query?.enabled ?? true)
26710
+ });
26711
+ }
26642
26712
  function useSymmHedgerMarketById(params) {
26643
26713
  const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
26644
26714
  const { id } = params;
@@ -26744,7 +26814,9 @@ async function fetch24hrTicker(symbol) {
26744
26814
  return {
26745
26815
  lastPrice: parseFloat(data.lastPrice),
26746
26816
  openPrice: parseFloat(data.openPrice),
26747
- priceChangePercent: parseFloat(data.priceChangePercent)
26817
+ priceChangePercent: parseFloat(data.priceChangePercent),
26818
+ volume: parseFloat(data.volume),
26819
+ quoteVolume: parseFloat(data.quoteVolume)
26748
26820
  };
26749
26821
  }
26750
26822
  async function fetch24hrTickers() {
@@ -26758,7 +26830,9 @@ async function fetch24hrTickers() {
26758
26830
  result[item.symbol] = {
26759
26831
  lastPrice: parseFloat(item.lastPrice),
26760
26832
  openPrice: parseFloat(item.openPrice),
26761
- priceChangePercent: parseFloat(item.priceChangePercent)
26833
+ priceChangePercent: parseFloat(item.priceChangePercent),
26834
+ volume: parseFloat(item.volume),
26835
+ quoteVolume: parseFloat(item.quoteVolume)
26762
26836
  };
26763
26837
  }
26764
26838
  return result;
@@ -26794,7 +26868,11 @@ function useSymmTokenSelectionMarkets(params) {
26794
26868
  return;
26795
26869
  }
26796
26870
  const ticker = allTickers[binanceSymbol];
26797
- tickerSnapshots[symbol] = ticker ? { openPrice: ticker.openPrice } : null;
26871
+ tickerSnapshots[symbol] = ticker ? {
26872
+ openPrice: ticker.openPrice,
26873
+ volume: ticker.volume,
26874
+ quoteVolume: ticker.quoteVolume
26875
+ } : null;
26798
26876
  });
26799
26877
  return { tickerSnapshots };
26800
26878
  },
@@ -26804,21 +26882,30 @@ function useSymmTokenSelectionMarkets(params) {
26804
26882
  });
26805
26883
  const markets = useMemo(() => {
26806
26884
  const snapshots = priceQuery.data?.tickerSnapshots ?? {};
26807
- return baseMarkets.map((market) => {
26885
+ return baseMarkets.map((market, index) => {
26808
26886
  const symbol = market.symbol ?? "";
26809
26887
  const markPrice = symbol ? liveMarkPrices[symbol] ?? null : null;
26810
- const prevDayPrice = symbol ? snapshots[symbol]?.openPrice ?? null : null;
26888
+ const ticker = symbol ? snapshots[symbol] ?? null : null;
26889
+ const prevDayPrice = ticker?.openPrice ?? null;
26811
26890
  const priceChange24h = markPrice != null && prevDayPrice != null ? markPrice - prevDayPrice : null;
26812
26891
  const priceChange24hPercent = markPrice != null && prevDayPrice != null && prevDayPrice !== 0 ? (markPrice - prevDayPrice) / prevDayPrice * 100 : null;
26813
26892
  return {
26814
- ...market,
26815
- collateralToken: "USDC",
26816
- markPrice,
26817
- prevDayPrice,
26818
- priceChange24h,
26819
- priceChange24hPercent
26893
+ market: {
26894
+ ...market,
26895
+ collateralToken: "USDC",
26896
+ markPrice,
26897
+ prevDayPrice,
26898
+ priceChange24h,
26899
+ priceChange24hPercent,
26900
+ volume24h: ticker?.volume ?? null,
26901
+ quoteVolume24h: ticker?.quoteVolume ?? null
26902
+ },
26903
+ index
26820
26904
  };
26821
- });
26905
+ }).sort((a, b) => {
26906
+ const volumeDelta = (b.market.quoteVolume24h ?? 0) - (a.market.quoteVolume24h ?? 0);
26907
+ return volumeDelta === 0 ? a.index - b.index : volumeDelta;
26908
+ }).map(({ market }) => market);
26822
26909
  }, [baseMarkets, liveMarkPrices, priceQuery.data]);
26823
26910
  const marketsBySymbol = useMemo(
26824
26911
  () => new Map(
@@ -27823,6 +27910,6 @@ function getSymmErrorMessage(error) {
27823
27910
  return "An unexpected error occurred.";
27824
27911
  }
27825
27912
 
27826
- export { SymmProvider, computeSymmAccountOverview, computeSymmAccountOverviewFromData, computeSymmNetDeposited, computeSymmPositionUpnl, computeSymmPositionsUpnl, getSymmAccountBalanceInfo, getSymmAccountData, getSymmErrorMessage, normalizeSymmUpnlWebSocketMessage, symmKeys, useBinanceMarkPriceStore, useSymmAccountCurrentPnl, useSymmAccountData, useSymmAccountOverview, useSymmAccountSummary, useSymmAccountsApi, useSymmAccountsLength, useSymmAccountsQuery, useSymmAccountsWithPositions, useSymmAllocateCollateralMutation, useSymmApprovalQuery, useSymmApproveMutation, useSymmAuth, useSymmAvailableMargin, useSymmBalances, useSymmCancelClose, useSymmCancelOpenMutation, useSymmCancelTpslMutation, useSymmCancelTwapOrderMutation, useSymmChartCandles, useSymmChartSelection, useSymmClearTriggerConfigMutation, useSymmCloseAllPositionsMutation, useSymmCloseOrder, useSymmClosePositionMutation, useSymmContext, useSymmCoreClient, useSymmCreateAccountMutation, useSymmDeallocateCollateralMutation, useSymmDelegateAccessMutation, useSymmDelegation, useSymmDepositAndAllocateMutation, useSymmDepositMutation, useSymmEditAccountNameMutation, useSymmFunding, useSymmFundingHistory, useSymmFundingPayments, useSymmHedgerMarketById, useSymmHedgerMarketBySymbol, useSymmHedgerMarkets, useSymmInstantTradeEnsureReadyMutation, useSymmInstantTradeExecuteMutation, useSymmInternalTransferCollateralMutation, useSymmLockedParams, useSymmMarkReadNotificationMutation, useSymmMarkets, useSymmNotificationsQuery, useSymmOpenBasketMutation, useSymmOpenOrders, useSymmPendingIds, useSymmPendingInstantOpens, useSymmPerformanceOverlays, useSymmPortfolio, useSymmPositions, useSymmProposeRevokeDelegationMutation, useSymmRevokeDelegationMutation, useSymmSetTpslMutation, useSymmSetTriggerConfigMutation, useSymmSignTermsMutation, useSymmSignatureQuery, useSymmTokenMarkPrice, useSymmTokenSelectionMarkets, useSymmTokenSelectionMetadata, useSymmTpslOrders, useSymmTradeHistory, useSymmTriggerConfigQuery, useSymmTriggerOrders, useSymmTwapOrder, useSymmTwapOrdersQuery, useSymmUnreadCountQuery, useSymmUpdatePositionMutation, useSymmUpnlWebSocket, useSymmWithdraw, useSymmWsStore };
27913
+ export { SymmProvider, computeSymmAccountOverview, computeSymmAccountOverviewFromData, computeSymmNetDeposited, computeSymmPositionUpnl, computeSymmPositionsUpnl, getSymmAccountBalanceInfo, getSymmAccountData, getSymmErrorMessage, normalizeSymmUpnlWebSocketMessage, symmKeys, useBinanceMarkPriceStore, useSymmAccountCurrentPnl, useSymmAccountData, useSymmAccountOverview, useSymmAccountSummary, useSymmAccountsApi, useSymmAccountsLength, useSymmAccountsQuery, useSymmAccountsWithPositions, useSymmAllocateCollateralMutation, useSymmApprovalQuery, useSymmApproveMutation, useSymmAuth, useSymmAvailableMargin, useSymmBalances, useSymmCancelClose, useSymmCancelOpenMutation, useSymmCancelTpslMutation, useSymmCancelTwapOrderMutation, useSymmChartCandles, useSymmChartSelection, useSymmClearTriggerConfigMutation, useSymmCloseAllPositionsMutation, useSymmCloseOrder, useSymmClosePositionMutation, useSymmContext, useSymmCoreClient, useSymmCreateAccountMutation, useSymmDeallocateCollateralMutation, useSymmDelegateAccessMutation, useSymmDelegation, useSymmDepositAndAllocateMutation, useSymmDepositMutation, useSymmEditAccountNameMutation, useSymmFunding, useSymmFundingHistory, useSymmFundingPayments, useSymmHedgerMarketById, useSymmHedgerMarketBySymbol, useSymmHedgerMarkets, useSymmInstantTradeEnsureReadyMutation, useSymmInstantTradeExecuteMutation, useSymmInternalTransferCollateralMutation, useSymmLockedParams, useSymmMarkReadNotificationMutation, useSymmMarketPositioning, useSymmMarkets, useSymmNotificationsQuery, useSymmOpenBasketMutation, useSymmOpenOrders, useSymmPendingIds, useSymmPendingInstantOpens, useSymmPerformanceOverlays, useSymmPortfolio, useSymmPositions, useSymmProposeRevokeDelegationMutation, useSymmRevokeDelegationMutation, useSymmSetTpslMutation, useSymmSetTriggerConfigMutation, useSymmSignTermsMutation, useSymmSignatureQuery, useSymmTokenMarkPrice, useSymmTokenSelectionMarkets, useSymmTokenSelectionMetadata, useSymmTpslOrders, useSymmTradeHistory, useSymmTriggerConfigQuery, useSymmTriggerOrders, useSymmTwapOrder, useSymmTwapOrdersQuery, useSymmUnreadCountQuery, useSymmUpdatePositionMutation, useSymmUpnlWebSocket, useSymmWithdraw, useSymmWsStore };
27827
27914
  //# sourceMappingURL=index.mjs.map
27828
27915
  //# sourceMappingURL=index.mjs.map