@pear-protocol/symmio-client 0.2.25 → 0.2.26

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.
@@ -25003,634 +25003,128 @@ function useSymmHedgerMarkets(params) {
25003
25003
  enabled: internalEnabled && consumerEnabled
25004
25004
  });
25005
25005
  }
25006
- function useSymmFunding(params) {
25007
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25008
- const chainId = params?.chainId ?? ctxChainId;
25009
- const internalEnabled = !!symmCoreClient;
25010
- return reactQuery.useQuery({
25011
- ...params?.query,
25012
- queryKey: symmKeys.fundingRates(chainId),
25013
- queryFn: () => symmCoreClient.funding.getRates({ chainId }),
25014
- enabled: internalEnabled && (params?.query?.enabled ?? true)
25015
- });
25016
- }
25017
- function useSymmFundingHistory(params) {
25018
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25019
- const chainId = params.chainId ?? ctxChainId;
25020
- const {
25021
- period,
25022
- longSymbols,
25023
- shortSymbols,
25024
- interval,
25025
- weightMode,
25026
- includeContributions
25027
- } = params;
25028
- const internalEnabled = !!symmCoreClient;
25029
- const request = {
25030
- chainId,
25031
- period,
25032
- longSymbols,
25033
- shortSymbols,
25006
+
25007
+ // src/utils/binance-api.ts
25008
+ var BINANCE_FAPI_BASE = "https://fapi.binance.com";
25009
+ async function fetchMarkPriceKlines(symbol, interval, startTime, endTime, limit = 1500) {
25010
+ const params = new URLSearchParams({
25011
+ symbol,
25034
25012
  interval,
25035
- weightMode,
25036
- includeContributions
25037
- };
25038
- return reactQuery.useQuery({
25039
- ...params.query,
25040
- queryKey: symmKeys.fundingHistory(request),
25041
- queryFn: () => symmCoreClient.funding.getHistory(request),
25042
- enabled: internalEnabled && (params.query?.enabled ?? true)
25013
+ startTime: String(startTime),
25014
+ endTime: String(endTime),
25015
+ limit: String(Math.min(limit, 1500))
25043
25016
  });
25017
+ const response = await fetch(`${BINANCE_FAPI_BASE}/fapi/v1/markPriceKlines?${params}`);
25018
+ if (!response.ok) {
25019
+ throw new Error(`Binance markPriceKlines failed: ${response.status}`);
25020
+ }
25021
+ const data = await response.json();
25022
+ return data.map((k) => ({
25023
+ openTime: Number(k[0]),
25024
+ open: parseFloat(k[1]),
25025
+ high: parseFloat(k[2]),
25026
+ low: parseFloat(k[3]),
25027
+ close: parseFloat(k[4]),
25028
+ volume: parseFloat(k[5]),
25029
+ closeTime: Number(k[6])
25030
+ }));
25044
25031
  }
25045
- function useSymmFundingPayments(params) {
25046
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25047
- const { address, positionId, limit, offset } = params;
25048
- const chainId = params.chainId ?? ctxChainId;
25049
- const internalEnabled = !!symmCoreClient && !!(address || positionId);
25050
- const request = {
25051
- address,
25052
- positionId,
25053
- chainId,
25054
- limit,
25055
- offset
25032
+ async function fetch24hrTicker(symbol) {
25033
+ const params = new URLSearchParams({ symbol });
25034
+ const response = await fetch(`${BINANCE_FAPI_BASE}/fapi/v1/ticker/24hr?${params}`);
25035
+ if (!response.ok) return null;
25036
+ const data = await response.json();
25037
+ return {
25038
+ lastPrice: parseFloat(data.lastPrice),
25039
+ prevClosePrice: parseFloat(data.prevClosePrice),
25040
+ priceChangePercent: parseFloat(data.priceChangePercent)
25056
25041
  };
25057
- return reactQuery.useQuery({
25058
- ...params.query,
25059
- queryKey: symmKeys.fundingPayments({
25060
- address,
25061
- positionId,
25062
- chainId,
25063
- limit,
25064
- offset
25065
- }),
25066
- queryFn: () => symmCoreClient.funding.getPayments(request),
25067
- enabled: internalEnabled && (params.query?.enabled ?? true)
25068
- });
25069
- }
25070
- function useSymmPortfolio(params) {
25071
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25072
- const { accountAddress, address } = params;
25073
- const resolvedAddress = accountAddress ? void 0 : address;
25074
- const chainId = params.chainId ?? ctxChainId;
25075
- const internalEnabled = !!symmCoreClient && !!(accountAddress || resolvedAddress);
25076
- return reactQuery.useQuery({
25077
- ...params.query,
25078
- queryKey: symmKeys.portfolio({
25079
- accountAddress,
25080
- address: resolvedAddress,
25081
- chainId
25082
- }),
25083
- queryFn: () => {
25084
- const request = {
25085
- accountAddress,
25086
- address: resolvedAddress,
25087
- chainId
25088
- };
25089
- return symmCoreClient.portfolio.getMetrics(request);
25090
- },
25091
- enabled: internalEnabled && (params.query?.enabled ?? true)
25092
- });
25093
25042
  }
25094
- function useResolvedNotificationsParams(params) {
25095
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25096
- const chainId = params.chainId ?? ctxChainId;
25043
+
25044
+ // src/utils/binance-symbol-map.ts
25045
+ var SYMBOL_OVERRIDES = {
25046
+ // Add overrides here as needed for SYMM markets that don't map 1:1 to Binance
25047
+ // e.g., 'SOME_SYMM_SYMBOL': 'BINANCE_SYMBOL',
25048
+ };
25049
+ var UNSUPPORTED_SYMBOLS = /* @__PURE__ */ new Set([
25050
+ // Add symbols here that have no Binance equivalent
25051
+ ]);
25052
+ function resolveBinanceSymbol(symmSymbol) {
25053
+ if (!symmSymbol || !symmSymbol.trim()) {
25054
+ return {
25055
+ symmSymbol,
25056
+ normalizedSymbol: "",
25057
+ binanceSymbol: null,
25058
+ supported: false,
25059
+ reason: "missing_symbol"
25060
+ };
25061
+ }
25062
+ const normalized = symmSymbol.toUpperCase().trim();
25063
+ if (!/^[A-Z0-9]+$/.test(normalized)) {
25064
+ return {
25065
+ symmSymbol,
25066
+ normalizedSymbol: normalized,
25067
+ binanceSymbol: null,
25068
+ supported: false,
25069
+ reason: "invalid_symbol"
25070
+ };
25071
+ }
25072
+ if (UNSUPPORTED_SYMBOLS.has(normalized)) {
25073
+ return {
25074
+ symmSymbol,
25075
+ normalizedSymbol: normalized,
25076
+ binanceSymbol: null,
25077
+ supported: false,
25078
+ reason: "unsupported_symbol"
25079
+ };
25080
+ }
25081
+ const binanceSymbol = SYMBOL_OVERRIDES[normalized] ?? (normalized.endsWith("USDT") ? normalized : `${normalized}USDT`);
25097
25082
  return {
25098
- symmCoreClient,
25099
- chainId,
25100
- userAddress: params.userAddress,
25101
- query: params.query
25083
+ symmSymbol,
25084
+ normalizedSymbol: normalized,
25085
+ binanceSymbol,
25086
+ supported: true,
25087
+ reason: null
25102
25088
  };
25103
25089
  }
25104
- function useSymmNotificationsQuery(params) {
25105
- const { symmCoreClient, chainId, userAddress, query } = useResolvedNotificationsParams(params);
25106
- const internalEnabled = !!symmCoreClient && !!userAddress;
25107
- return reactQuery.useQuery({
25108
- ...query,
25109
- queryKey: symmKeys.notifications(userAddress, chainId),
25110
- queryFn: () => symmCoreClient.notifications.list({
25111
- userAddress,
25112
- chainId
25113
- }),
25114
- enabled: internalEnabled && (query?.enabled ?? true)
25115
- });
25090
+ function getUnsupportedBinanceSymbols(symbols) {
25091
+ return symbols.filter((symbol) => !resolveBinanceSymbol(symbol).supported);
25116
25092
  }
25117
- function useSymmUnreadCountQuery(params) {
25118
- const { symmCoreClient, chainId, userAddress, query } = useResolvedNotificationsParams(params);
25119
- const internalEnabled = !!symmCoreClient && !!userAddress;
25120
- return reactQuery.useQuery({
25121
- ...query,
25122
- queryKey: symmKeys.unreadCount(userAddress, chainId),
25123
- queryFn: () => symmCoreClient.notifications.getUnreadCount({
25124
- userAddress,
25125
- chainId
25126
- }),
25127
- enabled: internalEnabled && (query?.enabled ?? true)
25128
- });
25093
+ function toBinanceSymbol(symmSymbol) {
25094
+ return resolveBinanceSymbol(symmSymbol).binanceSymbol;
25129
25095
  }
25130
- function useSymmMarkReadNotificationMutation(params, options) {
25131
- const { symmCoreClient, chainId, userAddress } = useResolvedNotificationsParams(params);
25132
- const queryClient = reactQuery.useQueryClient();
25133
- return reactQuery.useMutation({
25134
- ...withSymmMutationConfig(options?.mutation, {
25135
- onSuccess: () => {
25136
- queryClient.invalidateQueries({
25137
- queryKey: symmKeys.notifications(userAddress, chainId)
25138
- });
25139
- queryClient.invalidateQueries({
25140
- queryKey: symmKeys.unreadCount(userAddress, chainId)
25141
- });
25142
- }
25143
- }),
25144
- mutationFn: async ({ id, timestamp }) => {
25145
- if (!symmCoreClient || !userAddress) {
25146
- throw new Error("symm-core client not available");
25147
- }
25148
- return symmCoreClient.notifications.markRead({
25149
- id,
25150
- timestamp,
25151
- userAddress,
25152
- chainId
25153
- });
25154
- }
25155
- });
25156
- }
25157
- function useSymmPendingIds(params) {
25158
- const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25159
- const { accountAddress } = params;
25160
- const chainId = params.chainId ?? ctxChainId;
25161
- const internalEnabled = !!symmCoreClient && !!accountAddress;
25162
- return reactQuery.useQuery({
25163
- ...params.query,
25164
- queryKey: symmKeys.pendingIds(accountAddress, chainId),
25165
- queryFn: () => symmCoreClient.positions.getPendingIds({
25166
- address: accountAddress,
25167
- chainId
25168
- }),
25169
- enabled: internalEnabled && (params.query?.enabled ?? true)
25170
- });
25171
- }
25172
- function useSymmPendingInstantOpens(params) {
25173
- const {
25174
- symmCoreClient,
25175
- chainId: ctxChainId
25176
- } = useSymmContext();
25177
- const { accountAddress, authToken: providedAuthToken } = params;
25178
- const chainId = params.chainId ?? ctxChainId;
25179
- const internalEnabled = !!symmCoreClient && !!accountAddress;
25180
- return reactQuery.useQuery({
25181
- ...params.query,
25182
- queryKey: symmKeys.pendingInstantOpens(accountAddress, chainId),
25183
- queryFn: async () => {
25184
- const authToken = providedAuthToken ?? useSymmAuthStore.getState().getToken(accountAddress, chainId);
25185
- if (!authToken) {
25186
- throw new Error("failed to acquire auth token for pending instant opens");
25187
- }
25188
- return symmCoreClient.positions.getPendingInstantOpens({
25189
- accountAddress,
25190
- chainId,
25191
- authToken
25192
- });
25193
- },
25194
- enabled: internalEnabled && (params.query?.enabled ?? true)
25195
- });
25196
- }
25197
- function useSymmTwapOrder(params) {
25198
- const { symmCoreClient } = useSymmContext();
25199
- const { orderId } = params;
25200
- const internalEnabled = !!symmCoreClient && !!orderId;
25201
- return reactQuery.useQuery({
25202
- ...params.query,
25203
- queryKey: symmKeys.twapOrder(orderId),
25204
- queryFn: () => symmCoreClient.orders.getTwapOrder(orderId),
25205
- enabled: internalEnabled && (params.query?.enabled ?? true)
25206
- });
25207
- }
25208
- var useSymmWsStore = zustand.create((set) => ({
25209
- isConnected: false,
25210
- setConnected: (isConnected) => set({ isConnected })
25211
- }));
25212
-
25213
- // src/react/hooks/use-symm-ws.ts
25214
- function asUnsubscribeFn(value) {
25215
- return typeof value === "function" ? value : null;
25216
- }
25217
- function useSymmWs(params = {}) {
25218
- const {
25219
- symmCoreClient: ctxClient,
25220
- address: ctxAddress,
25221
- chainId: ctxChainId
25222
- } = useSymmContext();
25223
- const queryClient = reactQuery.useQueryClient();
25224
- const isConnected = useSymmWsStore((state) => state.isConnected);
25225
- const setConnected = useSymmWsStore((state) => state.setConnected);
25226
- const symmCoreClient = params.symmCoreClient ?? ctxClient;
25227
- const accountAddress = params.accountAddress ?? ctxAddress;
25228
- const chainId = params.chainId ?? ctxChainId;
25229
- react.useEffect(() => {
25230
- if (!symmCoreClient || !accountAddress) {
25231
- setConnected(false);
25232
- return;
25233
- }
25234
- const ws = symmCoreClient.ws;
25235
- const addr = accountAddress;
25236
- const unsubscribers = [];
25237
- const removeOnConnect = ws.onConnect(() => setConnected(true));
25238
- const removeOnDisconnect = ws.onDisconnect(() => setConnected(false));
25239
- unsubscribers.push(removeOnConnect, removeOnDisconnect);
25240
- const positionsUnsub = asUnsubscribeFn(
25241
- ws.subscribeToPositions(addr, chainId, () => {
25242
- queryClient.invalidateQueries({
25243
- queryKey: ["symm", "positions"]
25244
- });
25245
- })
25246
- );
25247
- if (positionsUnsub) unsubscribers.push(positionsUnsub);
25248
- const openOrdersUnsub = asUnsubscribeFn(
25249
- ws.subscribeToOpenOrders(addr, chainId, () => {
25250
- queryClient.invalidateQueries({
25251
- queryKey: ["symm", "openOrders"]
25252
- });
25253
- })
25254
- );
25255
- if (openOrdersUnsub) unsubscribers.push(openOrdersUnsub);
25256
- const tradesUnsub = asUnsubscribeFn(
25257
- ws.subscribeToTrades(addr, chainId, () => {
25258
- queryClient.invalidateQueries({
25259
- queryKey: ["symm", "tradeHistory"]
25260
- });
25261
- })
25262
- );
25263
- if (tradesUnsub) unsubscribers.push(tradesUnsub);
25264
- const accountSummaryUnsub = asUnsubscribeFn(
25265
- ws.subscribeToAccountSummary(addr, chainId, () => {
25266
- queryClient.invalidateQueries({
25267
- queryKey: symmKeys.balances(accountAddress, chainId)
25268
- });
25269
- queryClient.invalidateQueries({
25270
- queryKey: symmKeys.accountSummary(accountAddress, chainId)
25271
- });
25272
- })
25273
- );
25274
- if (accountSummaryUnsub) unsubscribers.push(accountSummaryUnsub);
25275
- const notificationsUnsub = asUnsubscribeFn(
25276
- ws.subscribeToNotifications(addr, chainId, () => {
25277
- queryClient.invalidateQueries({
25278
- queryKey: symmKeys.notifications(accountAddress, chainId)
25279
- });
25280
- queryClient.invalidateQueries({
25281
- queryKey: symmKeys.unreadCount(accountAddress, chainId)
25282
- });
25283
- })
25284
- );
25285
- if (notificationsUnsub) unsubscribers.push(notificationsUnsub);
25286
- const tpslUnsub = asUnsubscribeFn(
25287
- ws.subscribeToTpsl(addr, chainId, () => {
25288
- queryClient.invalidateQueries({ queryKey: ["symm", "tpslOrders"] });
25289
- queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25290
- })
25291
- );
25292
- if (tpslUnsub) unsubscribers.push(tpslUnsub);
25293
- const twapUnsub = asUnsubscribeFn(
25294
- ws.subscribeToTwapOrders(addr, chainId, () => {
25295
- queryClient.invalidateQueries({ queryKey: ["symm", "twapOrders"] });
25296
- queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25297
- })
25298
- );
25299
- if (twapUnsub) unsubscribers.push(twapUnsub);
25300
- const triggerOrdersUnsub = asUnsubscribeFn(
25301
- ws.subscribeToTriggerOrders(addr, chainId, () => {
25302
- queryClient.invalidateQueries({ queryKey: ["symm", "triggerOrders"] });
25303
- queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25304
- })
25305
- );
25306
- if (triggerOrdersUnsub) unsubscribers.push(triggerOrdersUnsub);
25307
- const executionsUnsub = asUnsubscribeFn(
25308
- ws.subscribeToExecutions(addr, chainId, () => {
25309
- queryClient.invalidateQueries({
25310
- queryKey: ["symm", "positions"]
25311
- });
25312
- queryClient.invalidateQueries({
25313
- queryKey: ["symm", "portfolio"]
25314
- });
25315
- })
25316
- );
25317
- if (executionsUnsub) unsubscribers.push(executionsUnsub);
25318
- return () => {
25319
- unsubscribers.forEach((unsubscribe) => unsubscribe());
25320
- };
25321
- }, [symmCoreClient, accountAddress, chainId, queryClient, setConnected]);
25322
- return { isConnected };
25323
- }
25324
- var STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT", "USDE", "USDH", "USDT0"]);
25325
- function useSymmChartSelection(input) {
25326
- const {
25327
- longSymbol,
25328
- shortSymbol,
25329
- longWeight = 100,
25330
- shortWeight = 100,
25331
- longTokens: explicitLongTokens,
25332
- shortTokens: explicitShortTokens
25333
- } = input;
25334
- return react.useMemo(() => {
25335
- const longTokens = explicitLongTokens?.length ? explicitLongTokens : longSymbol ? [{ symbol: longSymbol, weight: longWeight }] : [];
25336
- const shortTokens = explicitShortTokens?.length ? explicitShortTokens : shortSymbol ? [{ symbol: shortSymbol, weight: shortWeight }] : [];
25337
- const selectedSymbols = [
25338
- ...longTokens.map((t) => t.symbol),
25339
- ...shortTokens.map((t) => t.symbol)
25340
- ];
25341
- const uniqueSelectedSymbols = Array.from(new Set(selectedSymbols));
25342
- const longPrimarySymbol = longTokens[0]?.symbol ?? null;
25343
- const shortPrimarySymbol = shortTokens[0]?.symbol ?? null;
25344
- const longIsStable = longPrimarySymbol ? STABLE_SYMBOLS.has(longPrimarySymbol.toUpperCase()) : true;
25345
- const shortIsStable = shortPrimarySymbol ? STABLE_SYMBOLS.has(shortPrimarySymbol.toUpperCase()) : true;
25346
- let isSingleSided = false;
25347
- let activeSide = null;
25348
- let activeTokenSymbol;
25349
- if (longTokens.length > 0 && !longIsStable && (shortTokens.length === 0 || shortIsStable)) {
25350
- isSingleSided = true;
25351
- activeSide = "long";
25352
- activeTokenSymbol = longPrimarySymbol ?? void 0;
25353
- } else if (shortTokens.length > 0 && !shortIsStable && (longTokens.length === 0 || longIsStable)) {
25354
- isSingleSided = true;
25355
- activeSide = "short";
25356
- activeTokenSymbol = shortPrimarySymbol ?? void 0;
25357
- }
25358
- const longLabel = longTokens.map((token) => token.symbol).join("+") || "USDC";
25359
- const shortLabel = shortTokens.map((token) => token.symbol).join("+") || "USDC";
25360
- const pairLabel = `${longLabel}/${shortLabel}`;
25361
- return {
25362
- longTokens,
25363
- shortTokens,
25364
- isSingleSided,
25365
- activeSide,
25366
- activeTokenSymbol,
25367
- pairLabel,
25368
- selectedSymbols: uniqueSelectedSymbols
25369
- };
25370
- }, [
25371
- explicitLongTokens,
25372
- explicitShortTokens,
25373
- longSymbol,
25374
- shortSymbol,
25375
- longWeight,
25376
- shortWeight
25377
- ]);
25378
- }
25379
-
25380
- // src/utils/binance-symbol-map.ts
25381
- var SYMBOL_OVERRIDES = {
25382
- // Add overrides here as needed for SYMM markets that don't map 1:1 to Binance
25383
- // e.g., 'SOME_SYMM_SYMBOL': 'BINANCE_SYMBOL',
25384
- };
25385
- var UNSUPPORTED_SYMBOLS = /* @__PURE__ */ new Set([
25386
- // Add symbols here that have no Binance equivalent
25387
- ]);
25388
- function resolveBinanceSymbol(symmSymbol) {
25389
- if (!symmSymbol || !symmSymbol.trim()) {
25390
- return {
25391
- symmSymbol,
25392
- normalizedSymbol: "",
25393
- binanceSymbol: null,
25394
- supported: false,
25395
- reason: "missing_symbol"
25396
- };
25397
- }
25398
- const normalized = symmSymbol.toUpperCase().trim();
25399
- if (!/^[A-Z0-9]+$/.test(normalized)) {
25400
- return {
25401
- symmSymbol,
25402
- normalizedSymbol: normalized,
25403
- binanceSymbol: null,
25404
- supported: false,
25405
- reason: "invalid_symbol"
25406
- };
25407
- }
25408
- if (UNSUPPORTED_SYMBOLS.has(normalized)) {
25409
- return {
25410
- symmSymbol,
25411
- normalizedSymbol: normalized,
25412
- binanceSymbol: null,
25413
- supported: false,
25414
- reason: "unsupported_symbol"
25415
- };
25416
- }
25417
- const binanceSymbol = SYMBOL_OVERRIDES[normalized] ?? (normalized.endsWith("USDT") ? normalized : `${normalized}USDT`);
25418
- return {
25419
- symmSymbol,
25420
- normalizedSymbol: normalized,
25421
- binanceSymbol,
25422
- supported: true,
25423
- reason: null
25424
- };
25425
- }
25426
- function getUnsupportedBinanceSymbols(symbols) {
25427
- return symbols.filter((symbol) => !resolveBinanceSymbol(symbol).supported);
25428
- }
25429
- function toBinanceSymbol(symmSymbol) {
25430
- return resolveBinanceSymbol(symmSymbol).binanceSymbol;
25431
- }
25432
-
25433
- // src/utils/binance-api.ts
25434
- var BINANCE_FAPI_BASE = "https://fapi.binance.com";
25435
- async function fetchMarkPriceKlines(symbol, interval, startTime, endTime, limit = 1500) {
25436
- const params = new URLSearchParams({
25437
- symbol,
25438
- interval,
25439
- startTime: String(startTime),
25440
- endTime: String(endTime),
25441
- limit: String(Math.min(limit, 1500))
25442
- });
25443
- const response = await fetch(`${BINANCE_FAPI_BASE}/fapi/v1/markPriceKlines?${params}`);
25444
- if (!response.ok) {
25445
- throw new Error(`Binance markPriceKlines failed: ${response.status}`);
25446
- }
25447
- const data = await response.json();
25448
- return data.map((k) => ({
25449
- openTime: Number(k[0]),
25450
- open: parseFloat(k[1]),
25451
- high: parseFloat(k[2]),
25452
- low: parseFloat(k[3]),
25453
- close: parseFloat(k[4]),
25454
- volume: parseFloat(k[5]),
25455
- closeTime: Number(k[6])
25456
- }));
25457
- }
25458
- async function fetch24hrTicker(symbol) {
25459
- const params = new URLSearchParams({ symbol });
25460
- const response = await fetch(`${BINANCE_FAPI_BASE}/fapi/v1/ticker/24hr?${params}`);
25461
- if (!response.ok) return null;
25462
- const data = await response.json();
25463
- return {
25464
- lastPrice: parseFloat(data.lastPrice),
25465
- prevClosePrice: parseFloat(data.prevClosePrice),
25466
- priceChangePercent: parseFloat(data.priceChangePercent)
25467
- };
25468
- }
25469
-
25470
- // src/utils/chart-metrics.ts
25471
- function getPositiveValue(metadata, field) {
25472
- const value = metadata?.[field];
25473
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
25474
- return null;
25475
- }
25476
- return value;
25477
- }
25478
- function computeWeightedProduct(tokens, metadataMap, field, invert = false) {
25479
- let product = 1;
25480
- let hasToken = false;
25481
- for (const token of tokens) {
25482
- if (!(token.weight > 0)) {
25483
- continue;
25484
- }
25485
- const price = getPositiveValue(metadataMap[token.symbol], field);
25486
- if (price === null) {
25487
- return null;
25488
- }
25489
- hasToken = true;
25490
- const exponent = invert ? -(token.weight / 100) : token.weight / 100;
25491
- product *= Math.pow(price, exponent);
25492
- }
25493
- return hasToken ? product : 1;
25494
- }
25495
- function computePriceRatio({
25496
- longTokens,
25497
- shortTokens,
25498
- longTokensMetadata,
25499
- shortTokensMetadata
25500
- }) {
25501
- const firstLong = longTokens[0];
25502
- const firstShort = shortTokens[0];
25503
- const longPrice = firstLong ? getPositiveValue(longTokensMetadata[firstLong.symbol], "currentPrice") : null;
25504
- const shortPrice = firstShort ? getPositiveValue(shortTokensMetadata[firstShort.symbol], "currentPrice") : null;
25505
- if (longPrice !== null && shortPrice !== null) {
25506
- return longPrice / shortPrice;
25507
- }
25508
- if (longPrice !== null && shortTokens.length === 0) {
25509
- return longPrice;
25510
- }
25511
- if (shortPrice !== null && longTokens.length === 0) {
25512
- return shortPrice;
25513
- }
25514
- return null;
25515
- }
25516
- function computePriceRatio24h({
25517
- longTokens,
25518
- shortTokens,
25519
- longTokensMetadata,
25520
- shortTokensMetadata
25521
- }) {
25522
- const firstLong = longTokens[0];
25523
- const firstShort = shortTokens[0];
25524
- const longPrice = firstLong ? getPositiveValue(longTokensMetadata[firstLong.symbol], "prevDayPrice") : null;
25525
- const shortPrice = firstShort ? getPositiveValue(shortTokensMetadata[firstShort.symbol], "prevDayPrice") : null;
25526
- if (longPrice !== null && shortPrice !== null) {
25527
- return longPrice / shortPrice;
25528
- }
25529
- if (longPrice !== null && shortTokens.length === 0) {
25530
- return longPrice;
25531
- }
25532
- if (shortPrice !== null && longTokens.length === 0) {
25533
- return shortPrice;
25534
- }
25535
- return null;
25536
- }
25537
- function computeWeightedRatio({
25538
- longTokens,
25539
- shortTokens,
25540
- longTokensMetadata,
25541
- shortTokensMetadata
25542
- }) {
25543
- const longProduct = computeWeightedProduct(
25544
- longTokens,
25545
- longTokensMetadata,
25546
- "currentPrice"
25547
- );
25548
- const shortProduct = computeWeightedProduct(
25549
- shortTokens,
25550
- shortTokensMetadata,
25551
- "currentPrice",
25552
- true
25553
- );
25554
- if (longProduct === null || shortProduct === null) {
25555
- return null;
25556
- }
25557
- return longProduct * shortProduct;
25558
- }
25559
- function computeWeightedRatio24h({
25560
- longTokens,
25561
- shortTokens,
25562
- longTokensMetadata,
25563
- shortTokensMetadata
25564
- }) {
25565
- const longProduct = computeWeightedProduct(
25566
- longTokens,
25567
- longTokensMetadata,
25568
- "prevDayPrice"
25569
- );
25570
- const shortProduct = computeWeightedProduct(
25571
- shortTokens,
25572
- shortTokensMetadata,
25573
- "prevDayPrice",
25574
- true
25575
- );
25576
- if (longProduct === null || shortProduct === null) {
25577
- return null;
25578
- }
25579
- return longProduct * shortProduct;
25580
- }
25581
- function computeNetFundingSum({
25582
- longTokens,
25583
- shortTokens,
25584
- longTokensMetadata,
25585
- shortTokensMetadata
25586
- }) {
25587
- let funding = 0;
25588
- for (const token of longTokens) {
25589
- const value = longTokensMetadata[token.symbol]?.netFunding;
25590
- if (typeof value === "number" && Number.isFinite(value)) {
25591
- funding += value;
25592
- }
25593
- }
25594
- for (const token of shortTokens) {
25595
- const value = shortTokensMetadata[token.symbol]?.netFunding;
25596
- if (typeof value === "number" && Number.isFinite(value)) {
25597
- funding += value;
25598
- }
25599
- }
25600
- return funding;
25601
- }
25602
-
25603
- // src/utils/binance-ws.ts
25604
- var BINANCE_WS_URL = "wss://fstream.binance.com/ws";
25605
- var RECONNECT_DELAYS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
25606
- var BinanceWsManager = class {
25607
- ws = null;
25608
- streams = /* @__PURE__ */ new Map();
25609
- reconnectAttempt = 0;
25610
- reconnectTimer = null;
25611
- intentionalClose = false;
25612
- pendingSubscribes = [];
25613
- idCounter = 0;
25614
- /**
25615
- * Subscribe to a kline stream. Returns an unsubscribe function.
25616
- */
25617
- subscribeKline(symbol, interval, cb) {
25618
- const streamName = `${symbol.toLowerCase()}@kline_${interval}`;
25619
- const id = this.generateId();
25620
- const wrappedCb = (raw) => {
25621
- const k = raw.k;
25622
- if (!k) return;
25623
- cb({
25624
- symbol: raw.s,
25625
- interval: k.i,
25626
- openTime: k.t,
25627
- closeTime: k.T,
25628
- open: parseFloat(k.o),
25629
- high: parseFloat(k.h),
25630
- low: parseFloat(k.l),
25631
- close: parseFloat(k.c),
25632
- volume: parseFloat(k.v),
25633
- isFinal: k.x
25096
+
25097
+ // src/utils/binance-ws.ts
25098
+ var BINANCE_WS_URL = "wss://fstream.binance.com/ws";
25099
+ var RECONNECT_DELAYS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
25100
+ var BinanceWsManager = class {
25101
+ ws = null;
25102
+ streams = /* @__PURE__ */ new Map();
25103
+ reconnectAttempt = 0;
25104
+ reconnectTimer = null;
25105
+ intentionalClose = false;
25106
+ pendingSubscribes = [];
25107
+ idCounter = 0;
25108
+ /**
25109
+ * Subscribe to a kline stream. Returns an unsubscribe function.
25110
+ */
25111
+ subscribeKline(symbol, interval, cb) {
25112
+ const streamName = `${symbol.toLowerCase()}@kline_${interval}`;
25113
+ const id = this.generateId();
25114
+ const wrappedCb = (raw) => {
25115
+ const k = raw.k;
25116
+ if (!k) return;
25117
+ cb({
25118
+ symbol: raw.s,
25119
+ interval: k.i,
25120
+ openTime: k.t,
25121
+ closeTime: k.T,
25122
+ open: parseFloat(k.o),
25123
+ high: parseFloat(k.h),
25124
+ low: parseFloat(k.l),
25125
+ close: parseFloat(k.c),
25126
+ volume: parseFloat(k.v),
25127
+ isFinal: k.x
25634
25128
  });
25635
25129
  };
25636
25130
  this.addStreamCallback(streamName, id, wrappedCb);
@@ -25649,225 +25143,837 @@ var BinanceWsManager = class {
25649
25143
  indexPrice: parseFloat(raw.i),
25650
25144
  time: raw.E
25651
25145
  });
25652
- };
25653
- this.addStreamCallback(streamName, id, wrappedCb);
25654
- return () => this.removeStreamCallback(streamName, id);
25655
- }
25656
- /**
25657
- * Destroy the manager and close the connection.
25658
- */
25659
- destroy() {
25660
- this.intentionalClose = true;
25661
- if (this.reconnectTimer) {
25662
- clearTimeout(this.reconnectTimer);
25663
- this.reconnectTimer = null;
25664
- }
25665
- if (this.ws) {
25666
- this.ws.close();
25667
- this.ws = null;
25146
+ };
25147
+ this.addStreamCallback(streamName, id, wrappedCb);
25148
+ return () => this.removeStreamCallback(streamName, id);
25149
+ }
25150
+ /**
25151
+ * Destroy the manager and close the connection.
25152
+ */
25153
+ destroy() {
25154
+ this.intentionalClose = true;
25155
+ if (this.reconnectTimer) {
25156
+ clearTimeout(this.reconnectTimer);
25157
+ this.reconnectTimer = null;
25158
+ }
25159
+ if (this.ws) {
25160
+ this.ws.close();
25161
+ this.ws = null;
25162
+ }
25163
+ this.streams.clear();
25164
+ }
25165
+ // --- Private ---
25166
+ generateId() {
25167
+ return `sub_${++this.idCounter}_${Date.now()}`;
25168
+ }
25169
+ addStreamCallback(streamName, id, cb) {
25170
+ let sub = this.streams.get(streamName);
25171
+ const isNew = !sub;
25172
+ if (!sub) {
25173
+ sub = { callbacks: /* @__PURE__ */ new Map() };
25174
+ this.streams.set(streamName, sub);
25175
+ }
25176
+ sub.callbacks.set(id, cb);
25177
+ if (isNew) {
25178
+ this.ensureConnected();
25179
+ this.sendSubscribe([streamName]);
25180
+ }
25181
+ }
25182
+ removeStreamCallback(streamName, id) {
25183
+ const sub = this.streams.get(streamName);
25184
+ if (!sub) return;
25185
+ sub.callbacks.delete(id);
25186
+ if (sub.callbacks.size === 0) {
25187
+ this.streams.delete(streamName);
25188
+ this.sendUnsubscribe([streamName]);
25189
+ if (this.streams.size === 0 && this.ws) {
25190
+ this.intentionalClose = true;
25191
+ this.ws.close();
25192
+ this.ws = null;
25193
+ this.intentionalClose = false;
25194
+ }
25195
+ }
25196
+ }
25197
+ ensureConnected() {
25198
+ if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
25199
+ return;
25200
+ }
25201
+ this.connect();
25202
+ }
25203
+ connect() {
25204
+ if (typeof WebSocket === "undefined") return;
25205
+ this.intentionalClose = false;
25206
+ this.ws = new WebSocket(BINANCE_WS_URL);
25207
+ this.ws.onopen = () => {
25208
+ this.reconnectAttempt = 0;
25209
+ const activeStreams = Array.from(this.streams.keys());
25210
+ if (activeStreams.length > 0) {
25211
+ this.sendSubscribe(activeStreams);
25212
+ }
25213
+ if (this.pendingSubscribes.length > 0) {
25214
+ this.sendSubscribe(this.pendingSubscribes);
25215
+ this.pendingSubscribes = [];
25216
+ }
25217
+ };
25218
+ this.ws.onmessage = (event) => {
25219
+ try {
25220
+ const data = JSON.parse(event.data);
25221
+ this.handleMessage(data);
25222
+ } catch {
25223
+ }
25224
+ };
25225
+ this.ws.onclose = () => {
25226
+ if (this.intentionalClose) return;
25227
+ this.scheduleReconnect();
25228
+ };
25229
+ this.ws.onerror = () => {
25230
+ };
25231
+ }
25232
+ handleMessage(data) {
25233
+ if (data.e === "kline") {
25234
+ const k = data.k;
25235
+ const streamName = `${data.s.toLowerCase()}@kline_${k.i}`;
25236
+ this.dispatchToStream(streamName, data);
25237
+ } else if (data.e === "markPriceUpdate") {
25238
+ const streamName = `${data.s.toLowerCase()}@markPrice@1s`;
25239
+ this.dispatchToStream(streamName, data);
25240
+ }
25241
+ }
25242
+ dispatchToStream(streamName, data) {
25243
+ const sub = this.streams.get(streamName);
25244
+ if (!sub) return;
25245
+ sub.callbacks.forEach((cb) => {
25246
+ try {
25247
+ cb(data);
25248
+ } catch {
25249
+ }
25250
+ });
25251
+ }
25252
+ sendSubscribe(streams) {
25253
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
25254
+ this.pendingSubscribes.push(...streams);
25255
+ return;
25256
+ }
25257
+ this.ws.send(JSON.stringify({
25258
+ method: "SUBSCRIBE",
25259
+ params: streams,
25260
+ id: Date.now()
25261
+ }));
25262
+ }
25263
+ sendUnsubscribe(streams) {
25264
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
25265
+ this.pendingSubscribes = this.pendingSubscribes.filter(
25266
+ (s) => !streams.includes(s)
25267
+ );
25268
+ return;
25269
+ }
25270
+ this.ws.send(JSON.stringify({
25271
+ method: "UNSUBSCRIBE",
25272
+ params: streams,
25273
+ id: Date.now()
25274
+ }));
25275
+ }
25276
+ scheduleReconnect() {
25277
+ if (this.reconnectTimer) return;
25278
+ if (this.streams.size === 0) return;
25279
+ const delay = RECONNECT_DELAYS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS.length - 1)];
25280
+ this.reconnectAttempt++;
25281
+ this.reconnectTimer = setTimeout(() => {
25282
+ this.reconnectTimer = null;
25283
+ this.connect();
25284
+ }, delay);
25285
+ }
25286
+ };
25287
+ var _instance = null;
25288
+ function getBinanceWsManager() {
25289
+ if (!_instance) {
25290
+ _instance = new BinanceWsManager();
25291
+ }
25292
+ return _instance;
25293
+ }
25294
+
25295
+ // src/react/stores/use-binance-mark-price-store.ts
25296
+ var refCounts = /* @__PURE__ */ new Map();
25297
+ var streamUnsubs = /* @__PURE__ */ new Map();
25298
+ var streamSymbols = /* @__PURE__ */ new Map();
25299
+ function normalizeBinanceSymbol(symbol) {
25300
+ return symbol.toUpperCase().trim();
25301
+ }
25302
+ function getNextRefCount(binanceSymbol) {
25303
+ return (refCounts.get(binanceSymbol) ?? 0) + 1;
25304
+ }
25305
+ function getPrevRefCount(binanceSymbol) {
25306
+ return Math.max(0, (refCounts.get(binanceSymbol) ?? 0) - 1);
25307
+ }
25308
+ var useBinanceMarkPriceStore = zustand.create((set) => ({
25309
+ markPrices: {},
25310
+ subscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
25311
+ const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
25312
+ const nextRefCount = getNextRefCount(binanceSymbol);
25313
+ refCounts.set(binanceSymbol, nextRefCount);
25314
+ const symbols = streamSymbols.get(binanceSymbol) ?? /* @__PURE__ */ new Set();
25315
+ symbols.add(symmSymbol);
25316
+ streamSymbols.set(binanceSymbol, symbols);
25317
+ if (nextRefCount === 1) {
25318
+ const wsManager = getBinanceWsManager();
25319
+ const unsubscribe = wsManager.subscribeMarkPrice(binanceSymbol, (data) => {
25320
+ const canonicalSymbol = normalizeBinanceSymbol(data.symbol);
25321
+ const mappedSymbols = streamSymbols.get(canonicalSymbol);
25322
+ if (!mappedSymbols || mappedSymbols.size === 0) return;
25323
+ set((state) => {
25324
+ const nextMarkPrices = { ...state.markPrices };
25325
+ mappedSymbols.forEach((mappedSymbol) => {
25326
+ nextMarkPrices[mappedSymbol] = data.markPrice;
25327
+ });
25328
+ return { markPrices: nextMarkPrices };
25329
+ });
25330
+ });
25331
+ streamUnsubs.set(binanceSymbol, unsubscribe);
25668
25332
  }
25669
- this.streams.clear();
25670
- }
25671
- // --- Private ---
25672
- generateId() {
25673
- return `sub_${++this.idCounter}_${Date.now()}`;
25674
- }
25675
- addStreamCallback(streamName, id, cb) {
25676
- let sub = this.streams.get(streamName);
25677
- const isNew = !sub;
25678
- if (!sub) {
25679
- sub = { callbacks: /* @__PURE__ */ new Map() };
25680
- this.streams.set(streamName, sub);
25333
+ },
25334
+ unsubscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
25335
+ const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
25336
+ const symbols = streamSymbols.get(binanceSymbol);
25337
+ if (symbols) {
25338
+ symbols.delete(symmSymbol);
25339
+ if (symbols.size === 0) {
25340
+ streamSymbols.delete(binanceSymbol);
25341
+ } else {
25342
+ streamSymbols.set(binanceSymbol, symbols);
25343
+ }
25681
25344
  }
25682
- sub.callbacks.set(id, cb);
25683
- if (isNew) {
25684
- this.ensureConnected();
25685
- this.sendSubscribe([streamName]);
25345
+ const nextRefCount = getPrevRefCount(binanceSymbol);
25346
+ if (nextRefCount === 0) {
25347
+ const unsubscribe = streamUnsubs.get(binanceSymbol);
25348
+ if (unsubscribe) unsubscribe();
25349
+ streamUnsubs.delete(binanceSymbol);
25350
+ refCounts.delete(binanceSymbol);
25351
+ } else {
25352
+ refCounts.set(binanceSymbol, nextRefCount);
25686
25353
  }
25354
+ set((state) => {
25355
+ if (state.markPrices[symmSymbol] == null) return state;
25356
+ const nextMarkPrices = { ...state.markPrices };
25357
+ delete nextMarkPrices[symmSymbol];
25358
+ return { markPrices: nextMarkPrices };
25359
+ });
25687
25360
  }
25688
- removeStreamCallback(streamName, id) {
25689
- const sub = this.streams.get(streamName);
25690
- if (!sub) return;
25691
- sub.callbacks.delete(id);
25692
- if (sub.callbacks.size === 0) {
25693
- this.streams.delete(streamName);
25694
- this.sendUnsubscribe([streamName]);
25695
- if (this.streams.size === 0 && this.ws) {
25696
- this.intentionalClose = true;
25697
- this.ws.close();
25698
- this.ws = null;
25699
- this.intentionalClose = false;
25361
+ }));
25362
+
25363
+ // src/react/hooks/use-symm-token-selection-markets.ts
25364
+ async function fetchTickerSnapshot(symbol) {
25365
+ const resolution = resolveBinanceSymbol(symbol);
25366
+ if (!resolution.binanceSymbol) return null;
25367
+ const ticker = await fetch24hrTicker(resolution.binanceSymbol);
25368
+ if (!ticker) return null;
25369
+ return {
25370
+ prevClosePrice: ticker.prevClosePrice
25371
+ };
25372
+ }
25373
+ function useSymmTokenSelectionMarkets(params) {
25374
+ const query = useSymmHedgerMarkets(params);
25375
+ const baseMarkets = query.data?.filteredMarkets ?? query.data?.markets ?? [];
25376
+ const marketSymbols = react.useMemo(
25377
+ () => Array.from(
25378
+ new Set(
25379
+ baseMarkets.map((market) => market.symbol).filter((symbol) => !!symbol)
25380
+ )
25381
+ ),
25382
+ [baseMarkets]
25383
+ );
25384
+ const symbolsKey = react.useMemo(
25385
+ () => [...marketSymbols].sort().join(","),
25386
+ [marketSymbols]
25387
+ );
25388
+ const symbolToBinanceMap = react.useMemo(
25389
+ () => new Map(
25390
+ marketSymbols.map((symbol) => {
25391
+ const binanceSymbol = resolveBinanceSymbol(symbol).binanceSymbol;
25392
+ if (!binanceSymbol) return null;
25393
+ return [symbol, binanceSymbol];
25394
+ }).filter((entry) => !!entry)
25395
+ ),
25396
+ [marketSymbols]
25397
+ );
25398
+ const liveMarkPrices = useBinanceMarkPriceStore((state) => state.markPrices);
25399
+ const subscribeSymbol = useBinanceMarkPriceStore((state) => state.subscribeSymbol);
25400
+ const unsubscribeSymbol = useBinanceMarkPriceStore((state) => state.unsubscribeSymbol);
25401
+ const priceQuery = reactQuery.useQuery({
25402
+ queryKey: ["symm", "token-selection-markets-price", symbolsKey],
25403
+ queryFn: async () => {
25404
+ const tickerSnapshots = {};
25405
+ await Promise.all(
25406
+ marketSymbols.map(async (symbol) => {
25407
+ tickerSnapshots[symbol] = await fetchTickerSnapshot(symbol);
25408
+ })
25409
+ );
25410
+ return { tickerSnapshots };
25411
+ },
25412
+ enabled: query.isSuccess && marketSymbols.length > 0,
25413
+ staleTime: 6e4,
25414
+ gcTime: 5 * 6e4
25415
+ });
25416
+ react.useEffect(() => {
25417
+ if (!query.isSuccess || symbolToBinanceMap.size === 0) {
25418
+ return;
25419
+ }
25420
+ const symbolEntries = Array.from(symbolToBinanceMap.entries());
25421
+ symbolEntries.forEach(
25422
+ ([symbol, binanceSymbol]) => subscribeSymbol(symbol, binanceSymbol)
25423
+ );
25424
+ return () => {
25425
+ symbolEntries.forEach(
25426
+ ([symbol, binanceSymbol]) => unsubscribeSymbol(symbol, binanceSymbol)
25427
+ );
25428
+ };
25429
+ }, [query.isSuccess, symbolsKey, symbolToBinanceMap, subscribeSymbol, unsubscribeSymbol]);
25430
+ const markets = react.useMemo(() => {
25431
+ const snapshots = priceQuery.data?.tickerSnapshots ?? {};
25432
+ return baseMarkets.map((market) => {
25433
+ const symbol = market.symbol ?? "";
25434
+ const markPrice = symbol ? liveMarkPrices[symbol] ?? null : null;
25435
+ const prevDayPrice = symbol ? snapshots[symbol]?.prevClosePrice ?? null : null;
25436
+ const priceChange24h = markPrice != null && prevDayPrice != null ? markPrice - prevDayPrice : null;
25437
+ const priceChange24hPercent = markPrice != null && prevDayPrice != null && prevDayPrice !== 0 ? (markPrice - prevDayPrice) / prevDayPrice * 100 : null;
25438
+ return {
25439
+ ...market,
25440
+ collateralToken: "USDC",
25441
+ markPrice,
25442
+ prevDayPrice,
25443
+ priceChange24h,
25444
+ priceChange24hPercent
25445
+ };
25446
+ });
25447
+ }, [baseMarkets, liveMarkPrices, priceQuery.data]);
25448
+ const marketsBySymbol = react.useMemo(
25449
+ () => new Map(
25450
+ markets.filter((m) => !!m.symbol).map((m) => [m.symbol, m])
25451
+ ),
25452
+ [markets]
25453
+ );
25454
+ const marketsById = react.useMemo(
25455
+ () => new Map(markets.map((market) => [market.id, market])),
25456
+ [markets]
25457
+ );
25458
+ return {
25459
+ query,
25460
+ priceQuery,
25461
+ markets,
25462
+ marketsBySymbol,
25463
+ marketsById,
25464
+ isLoading: query.isLoading || priceQuery.isLoading,
25465
+ isPriceLoading: priceQuery.isLoading
25466
+ };
25467
+ }
25468
+ function useSymmFunding(params) {
25469
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25470
+ const chainId = params?.chainId ?? ctxChainId;
25471
+ const internalEnabled = !!symmCoreClient;
25472
+ return reactQuery.useQuery({
25473
+ ...params?.query,
25474
+ queryKey: symmKeys.fundingRates(chainId),
25475
+ queryFn: () => symmCoreClient.funding.getRates({ chainId }),
25476
+ enabled: internalEnabled && (params?.query?.enabled ?? true)
25477
+ });
25478
+ }
25479
+ function useSymmFundingHistory(params) {
25480
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25481
+ const chainId = params.chainId ?? ctxChainId;
25482
+ const {
25483
+ period,
25484
+ longSymbols,
25485
+ shortSymbols,
25486
+ interval,
25487
+ weightMode,
25488
+ includeContributions
25489
+ } = params;
25490
+ const internalEnabled = !!symmCoreClient;
25491
+ const request = {
25492
+ chainId,
25493
+ period,
25494
+ longSymbols,
25495
+ shortSymbols,
25496
+ interval,
25497
+ weightMode,
25498
+ includeContributions
25499
+ };
25500
+ return reactQuery.useQuery({
25501
+ ...params.query,
25502
+ queryKey: symmKeys.fundingHistory(request),
25503
+ queryFn: () => symmCoreClient.funding.getHistory(request),
25504
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25505
+ });
25506
+ }
25507
+ function useSymmFundingPayments(params) {
25508
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25509
+ const { address, positionId, limit, offset } = params;
25510
+ const chainId = params.chainId ?? ctxChainId;
25511
+ const internalEnabled = !!symmCoreClient && !!(address || positionId);
25512
+ const request = {
25513
+ address,
25514
+ positionId,
25515
+ chainId,
25516
+ limit,
25517
+ offset
25518
+ };
25519
+ return reactQuery.useQuery({
25520
+ ...params.query,
25521
+ queryKey: symmKeys.fundingPayments({
25522
+ address,
25523
+ positionId,
25524
+ chainId,
25525
+ limit,
25526
+ offset
25527
+ }),
25528
+ queryFn: () => symmCoreClient.funding.getPayments(request),
25529
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25530
+ });
25531
+ }
25532
+ function useSymmPortfolio(params) {
25533
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25534
+ const { accountAddress, address } = params;
25535
+ const resolvedAddress = accountAddress ? void 0 : address;
25536
+ const chainId = params.chainId ?? ctxChainId;
25537
+ const internalEnabled = !!symmCoreClient && !!(accountAddress || resolvedAddress);
25538
+ return reactQuery.useQuery({
25539
+ ...params.query,
25540
+ queryKey: symmKeys.portfolio({
25541
+ accountAddress,
25542
+ address: resolvedAddress,
25543
+ chainId
25544
+ }),
25545
+ queryFn: () => {
25546
+ const request = {
25547
+ accountAddress,
25548
+ address: resolvedAddress,
25549
+ chainId
25550
+ };
25551
+ return symmCoreClient.portfolio.getMetrics(request);
25552
+ },
25553
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25554
+ });
25555
+ }
25556
+ function useResolvedNotificationsParams(params) {
25557
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25558
+ const chainId = params.chainId ?? ctxChainId;
25559
+ return {
25560
+ symmCoreClient,
25561
+ chainId,
25562
+ userAddress: params.userAddress,
25563
+ query: params.query
25564
+ };
25565
+ }
25566
+ function useSymmNotificationsQuery(params) {
25567
+ const { symmCoreClient, chainId, userAddress, query } = useResolvedNotificationsParams(params);
25568
+ const internalEnabled = !!symmCoreClient && !!userAddress;
25569
+ return reactQuery.useQuery({
25570
+ ...query,
25571
+ queryKey: symmKeys.notifications(userAddress, chainId),
25572
+ queryFn: () => symmCoreClient.notifications.list({
25573
+ userAddress,
25574
+ chainId
25575
+ }),
25576
+ enabled: internalEnabled && (query?.enabled ?? true)
25577
+ });
25578
+ }
25579
+ function useSymmUnreadCountQuery(params) {
25580
+ const { symmCoreClient, chainId, userAddress, query } = useResolvedNotificationsParams(params);
25581
+ const internalEnabled = !!symmCoreClient && !!userAddress;
25582
+ return reactQuery.useQuery({
25583
+ ...query,
25584
+ queryKey: symmKeys.unreadCount(userAddress, chainId),
25585
+ queryFn: () => symmCoreClient.notifications.getUnreadCount({
25586
+ userAddress,
25587
+ chainId
25588
+ }),
25589
+ enabled: internalEnabled && (query?.enabled ?? true)
25590
+ });
25591
+ }
25592
+ function useSymmMarkReadNotificationMutation(params, options) {
25593
+ const { symmCoreClient, chainId, userAddress } = useResolvedNotificationsParams(params);
25594
+ const queryClient = reactQuery.useQueryClient();
25595
+ return reactQuery.useMutation({
25596
+ ...withSymmMutationConfig(options?.mutation, {
25597
+ onSuccess: () => {
25598
+ queryClient.invalidateQueries({
25599
+ queryKey: symmKeys.notifications(userAddress, chainId)
25600
+ });
25601
+ queryClient.invalidateQueries({
25602
+ queryKey: symmKeys.unreadCount(userAddress, chainId)
25603
+ });
25604
+ }
25605
+ }),
25606
+ mutationFn: async ({ id, timestamp }) => {
25607
+ if (!symmCoreClient || !userAddress) {
25608
+ throw new Error("symm-core client not available");
25700
25609
  }
25610
+ return symmCoreClient.notifications.markRead({
25611
+ id,
25612
+ timestamp,
25613
+ userAddress,
25614
+ chainId
25615
+ });
25701
25616
  }
25702
- }
25703
- ensureConnected() {
25704
- if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
25617
+ });
25618
+ }
25619
+ function useSymmPendingIds(params) {
25620
+ const { symmCoreClient, chainId: ctxChainId } = useSymmContext();
25621
+ const { accountAddress } = params;
25622
+ const chainId = params.chainId ?? ctxChainId;
25623
+ const internalEnabled = !!symmCoreClient && !!accountAddress;
25624
+ return reactQuery.useQuery({
25625
+ ...params.query,
25626
+ queryKey: symmKeys.pendingIds(accountAddress, chainId),
25627
+ queryFn: () => symmCoreClient.positions.getPendingIds({
25628
+ address: accountAddress,
25629
+ chainId
25630
+ }),
25631
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25632
+ });
25633
+ }
25634
+ function useSymmPendingInstantOpens(params) {
25635
+ const {
25636
+ symmCoreClient,
25637
+ chainId: ctxChainId
25638
+ } = useSymmContext();
25639
+ const { accountAddress, authToken: providedAuthToken } = params;
25640
+ const chainId = params.chainId ?? ctxChainId;
25641
+ const internalEnabled = !!symmCoreClient && !!accountAddress;
25642
+ return reactQuery.useQuery({
25643
+ ...params.query,
25644
+ queryKey: symmKeys.pendingInstantOpens(accountAddress, chainId),
25645
+ queryFn: async () => {
25646
+ const authToken = providedAuthToken ?? useSymmAuthStore.getState().getToken(accountAddress, chainId);
25647
+ if (!authToken) {
25648
+ throw new Error("failed to acquire auth token for pending instant opens");
25649
+ }
25650
+ return symmCoreClient.positions.getPendingInstantOpens({
25651
+ accountAddress,
25652
+ chainId,
25653
+ authToken
25654
+ });
25655
+ },
25656
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25657
+ });
25658
+ }
25659
+ function useSymmTwapOrder(params) {
25660
+ const { symmCoreClient } = useSymmContext();
25661
+ const { orderId } = params;
25662
+ const internalEnabled = !!symmCoreClient && !!orderId;
25663
+ return reactQuery.useQuery({
25664
+ ...params.query,
25665
+ queryKey: symmKeys.twapOrder(orderId),
25666
+ queryFn: () => symmCoreClient.orders.getTwapOrder(orderId),
25667
+ enabled: internalEnabled && (params.query?.enabled ?? true)
25668
+ });
25669
+ }
25670
+ var useSymmWsStore = zustand.create((set) => ({
25671
+ isConnected: false,
25672
+ setConnected: (isConnected) => set({ isConnected })
25673
+ }));
25674
+
25675
+ // src/react/hooks/use-symm-ws.ts
25676
+ function asUnsubscribeFn(value) {
25677
+ return typeof value === "function" ? value : null;
25678
+ }
25679
+ function useSymmWs(params = {}) {
25680
+ const {
25681
+ symmCoreClient: ctxClient,
25682
+ address: ctxAddress,
25683
+ chainId: ctxChainId
25684
+ } = useSymmContext();
25685
+ const queryClient = reactQuery.useQueryClient();
25686
+ const isConnected = useSymmWsStore((state) => state.isConnected);
25687
+ const setConnected = useSymmWsStore((state) => state.setConnected);
25688
+ const symmCoreClient = params.symmCoreClient ?? ctxClient;
25689
+ const accountAddress = params.accountAddress ?? ctxAddress;
25690
+ const chainId = params.chainId ?? ctxChainId;
25691
+ react.useEffect(() => {
25692
+ if (!symmCoreClient || !accountAddress) {
25693
+ setConnected(false);
25705
25694
  return;
25706
25695
  }
25707
- this.connect();
25708
- }
25709
- connect() {
25710
- if (typeof WebSocket === "undefined") return;
25711
- this.intentionalClose = false;
25712
- this.ws = new WebSocket(BINANCE_WS_URL);
25713
- this.ws.onopen = () => {
25714
- this.reconnectAttempt = 0;
25715
- const activeStreams = Array.from(this.streams.keys());
25716
- if (activeStreams.length > 0) {
25717
- this.sendSubscribe(activeStreams);
25718
- }
25719
- if (this.pendingSubscribes.length > 0) {
25720
- this.sendSubscribe(this.pendingSubscribes);
25721
- this.pendingSubscribes = [];
25722
- }
25723
- };
25724
- this.ws.onmessage = (event) => {
25725
- try {
25726
- const data = JSON.parse(event.data);
25727
- this.handleMessage(data);
25728
- } catch {
25729
- }
25730
- };
25731
- this.ws.onclose = () => {
25732
- if (this.intentionalClose) return;
25733
- this.scheduleReconnect();
25696
+ const ws = symmCoreClient.ws;
25697
+ const addr = accountAddress;
25698
+ const unsubscribers = [];
25699
+ const removeOnConnect = ws.onConnect(() => setConnected(true));
25700
+ const removeOnDisconnect = ws.onDisconnect(() => setConnected(false));
25701
+ unsubscribers.push(removeOnConnect, removeOnDisconnect);
25702
+ const positionsUnsub = asUnsubscribeFn(
25703
+ ws.subscribeToPositions(addr, chainId, () => {
25704
+ queryClient.invalidateQueries({
25705
+ queryKey: ["symm", "positions"]
25706
+ });
25707
+ })
25708
+ );
25709
+ if (positionsUnsub) unsubscribers.push(positionsUnsub);
25710
+ const openOrdersUnsub = asUnsubscribeFn(
25711
+ ws.subscribeToOpenOrders(addr, chainId, () => {
25712
+ queryClient.invalidateQueries({
25713
+ queryKey: ["symm", "openOrders"]
25714
+ });
25715
+ })
25716
+ );
25717
+ if (openOrdersUnsub) unsubscribers.push(openOrdersUnsub);
25718
+ const tradesUnsub = asUnsubscribeFn(
25719
+ ws.subscribeToTrades(addr, chainId, () => {
25720
+ queryClient.invalidateQueries({
25721
+ queryKey: ["symm", "tradeHistory"]
25722
+ });
25723
+ })
25724
+ );
25725
+ if (tradesUnsub) unsubscribers.push(tradesUnsub);
25726
+ const accountSummaryUnsub = asUnsubscribeFn(
25727
+ ws.subscribeToAccountSummary(addr, chainId, () => {
25728
+ queryClient.invalidateQueries({
25729
+ queryKey: symmKeys.balances(accountAddress, chainId)
25730
+ });
25731
+ queryClient.invalidateQueries({
25732
+ queryKey: symmKeys.accountSummary(accountAddress, chainId)
25733
+ });
25734
+ })
25735
+ );
25736
+ if (accountSummaryUnsub) unsubscribers.push(accountSummaryUnsub);
25737
+ const notificationsUnsub = asUnsubscribeFn(
25738
+ ws.subscribeToNotifications(addr, chainId, () => {
25739
+ queryClient.invalidateQueries({
25740
+ queryKey: symmKeys.notifications(accountAddress, chainId)
25741
+ });
25742
+ queryClient.invalidateQueries({
25743
+ queryKey: symmKeys.unreadCount(accountAddress, chainId)
25744
+ });
25745
+ })
25746
+ );
25747
+ if (notificationsUnsub) unsubscribers.push(notificationsUnsub);
25748
+ const tpslUnsub = asUnsubscribeFn(
25749
+ ws.subscribeToTpsl(addr, chainId, () => {
25750
+ queryClient.invalidateQueries({ queryKey: ["symm", "tpslOrders"] });
25751
+ queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25752
+ })
25753
+ );
25754
+ if (tpslUnsub) unsubscribers.push(tpslUnsub);
25755
+ const twapUnsub = asUnsubscribeFn(
25756
+ ws.subscribeToTwapOrders(addr, chainId, () => {
25757
+ queryClient.invalidateQueries({ queryKey: ["symm", "twapOrders"] });
25758
+ queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25759
+ })
25760
+ );
25761
+ if (twapUnsub) unsubscribers.push(twapUnsub);
25762
+ const triggerOrdersUnsub = asUnsubscribeFn(
25763
+ ws.subscribeToTriggerOrders(addr, chainId, () => {
25764
+ queryClient.invalidateQueries({ queryKey: ["symm", "triggerOrders"] });
25765
+ queryClient.invalidateQueries({ queryKey: ["symm", "openOrders"] });
25766
+ })
25767
+ );
25768
+ if (triggerOrdersUnsub) unsubscribers.push(triggerOrdersUnsub);
25769
+ const executionsUnsub = asUnsubscribeFn(
25770
+ ws.subscribeToExecutions(addr, chainId, () => {
25771
+ queryClient.invalidateQueries({
25772
+ queryKey: ["symm", "positions"]
25773
+ });
25774
+ queryClient.invalidateQueries({
25775
+ queryKey: ["symm", "portfolio"]
25776
+ });
25777
+ })
25778
+ );
25779
+ if (executionsUnsub) unsubscribers.push(executionsUnsub);
25780
+ return () => {
25781
+ unsubscribers.forEach((unsubscribe) => unsubscribe());
25734
25782
  };
25735
- this.ws.onerror = () => {
25783
+ }, [symmCoreClient, accountAddress, chainId, queryClient, setConnected]);
25784
+ return { isConnected };
25785
+ }
25786
+ var STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT", "USDE", "USDH", "USDT0"]);
25787
+ function useSymmChartSelection(input) {
25788
+ const {
25789
+ longSymbol,
25790
+ shortSymbol,
25791
+ longWeight = 100,
25792
+ shortWeight = 100,
25793
+ longTokens: explicitLongTokens,
25794
+ shortTokens: explicitShortTokens
25795
+ } = input;
25796
+ return react.useMemo(() => {
25797
+ const longTokens = explicitLongTokens?.length ? explicitLongTokens : longSymbol ? [{ symbol: longSymbol, weight: longWeight }] : [];
25798
+ const shortTokens = explicitShortTokens?.length ? explicitShortTokens : shortSymbol ? [{ symbol: shortSymbol, weight: shortWeight }] : [];
25799
+ const selectedSymbols = [
25800
+ ...longTokens.map((t) => t.symbol),
25801
+ ...shortTokens.map((t) => t.symbol)
25802
+ ];
25803
+ const uniqueSelectedSymbols = Array.from(new Set(selectedSymbols));
25804
+ const longPrimarySymbol = longTokens[0]?.symbol ?? null;
25805
+ const shortPrimarySymbol = shortTokens[0]?.symbol ?? null;
25806
+ const longIsStable = longPrimarySymbol ? STABLE_SYMBOLS.has(longPrimarySymbol.toUpperCase()) : true;
25807
+ const shortIsStable = shortPrimarySymbol ? STABLE_SYMBOLS.has(shortPrimarySymbol.toUpperCase()) : true;
25808
+ let isSingleSided = false;
25809
+ let activeSide = null;
25810
+ let activeTokenSymbol;
25811
+ if (longTokens.length > 0 && !longIsStable && (shortTokens.length === 0 || shortIsStable)) {
25812
+ isSingleSided = true;
25813
+ activeSide = "long";
25814
+ activeTokenSymbol = longPrimarySymbol ?? void 0;
25815
+ } else if (shortTokens.length > 0 && !shortIsStable && (longTokens.length === 0 || longIsStable)) {
25816
+ isSingleSided = true;
25817
+ activeSide = "short";
25818
+ activeTokenSymbol = shortPrimarySymbol ?? void 0;
25819
+ }
25820
+ const longLabel = longTokens.map((token) => token.symbol).join("+") || "USDC";
25821
+ const shortLabel = shortTokens.map((token) => token.symbol).join("+") || "USDC";
25822
+ const pairLabel = `${longLabel}/${shortLabel}`;
25823
+ return {
25824
+ longTokens,
25825
+ shortTokens,
25826
+ isSingleSided,
25827
+ activeSide,
25828
+ activeTokenSymbol,
25829
+ pairLabel,
25830
+ selectedSymbols: uniqueSelectedSymbols
25736
25831
  };
25832
+ }, [
25833
+ explicitLongTokens,
25834
+ explicitShortTokens,
25835
+ longSymbol,
25836
+ shortSymbol,
25837
+ longWeight,
25838
+ shortWeight
25839
+ ]);
25840
+ }
25841
+
25842
+ // src/utils/chart-metrics.ts
25843
+ function getPositiveValue(metadata, field) {
25844
+ const value = metadata?.[field];
25845
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
25846
+ return null;
25737
25847
  }
25738
- handleMessage(data) {
25739
- if (data.e === "kline") {
25740
- const k = data.k;
25741
- const streamName = `${data.s.toLowerCase()}@kline_${k.i}`;
25742
- this.dispatchToStream(streamName, data);
25743
- } else if (data.e === "markPriceUpdate") {
25744
- const streamName = `${data.s.toLowerCase()}@markPrice@1s`;
25745
- this.dispatchToStream(streamName, data);
25848
+ return value;
25849
+ }
25850
+ function computeWeightedProduct(tokens, metadataMap, field, invert = false) {
25851
+ let product = 1;
25852
+ let hasToken = false;
25853
+ for (const token of tokens) {
25854
+ if (!(token.weight > 0)) {
25855
+ continue;
25746
25856
  }
25747
- }
25748
- dispatchToStream(streamName, data) {
25749
- const sub = this.streams.get(streamName);
25750
- if (!sub) return;
25751
- sub.callbacks.forEach((cb) => {
25752
- try {
25753
- cb(data);
25754
- } catch {
25755
- }
25756
- });
25757
- }
25758
- sendSubscribe(streams) {
25759
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
25760
- this.pendingSubscribes.push(...streams);
25761
- return;
25857
+ const price = getPositiveValue(metadataMap[token.symbol], field);
25858
+ if (price === null) {
25859
+ return null;
25762
25860
  }
25763
- this.ws.send(JSON.stringify({
25764
- method: "SUBSCRIBE",
25765
- params: streams,
25766
- id: Date.now()
25767
- }));
25861
+ hasToken = true;
25862
+ const exponent = invert ? -(token.weight / 100) : token.weight / 100;
25863
+ product *= Math.pow(price, exponent);
25768
25864
  }
25769
- sendUnsubscribe(streams) {
25770
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
25771
- this.pendingSubscribes = this.pendingSubscribes.filter(
25772
- (s) => !streams.includes(s)
25773
- );
25774
- return;
25775
- }
25776
- this.ws.send(JSON.stringify({
25777
- method: "UNSUBSCRIBE",
25778
- params: streams,
25779
- id: Date.now()
25780
- }));
25865
+ return hasToken ? product : 1;
25866
+ }
25867
+ function computePriceRatio({
25868
+ longTokens,
25869
+ shortTokens,
25870
+ longTokensMetadata,
25871
+ shortTokensMetadata
25872
+ }) {
25873
+ const firstLong = longTokens[0];
25874
+ const firstShort = shortTokens[0];
25875
+ const longPrice = firstLong ? getPositiveValue(longTokensMetadata[firstLong.symbol], "currentPrice") : null;
25876
+ const shortPrice = firstShort ? getPositiveValue(shortTokensMetadata[firstShort.symbol], "currentPrice") : null;
25877
+ if (longPrice !== null && shortPrice !== null) {
25878
+ return longPrice / shortPrice;
25781
25879
  }
25782
- scheduleReconnect() {
25783
- if (this.reconnectTimer) return;
25784
- if (this.streams.size === 0) return;
25785
- const delay = RECONNECT_DELAYS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS.length - 1)];
25786
- this.reconnectAttempt++;
25787
- this.reconnectTimer = setTimeout(() => {
25788
- this.reconnectTimer = null;
25789
- this.connect();
25790
- }, delay);
25880
+ if (longPrice !== null && shortTokens.length === 0) {
25881
+ return longPrice;
25791
25882
  }
25792
- };
25793
- var _instance = null;
25794
- function getBinanceWsManager() {
25795
- if (!_instance) {
25796
- _instance = new BinanceWsManager();
25883
+ if (shortPrice !== null && longTokens.length === 0) {
25884
+ return shortPrice;
25797
25885
  }
25798
- return _instance;
25886
+ return null;
25799
25887
  }
25800
-
25801
- // src/react/stores/use-binance-mark-price-store.ts
25802
- var refCounts = /* @__PURE__ */ new Map();
25803
- var streamUnsubs = /* @__PURE__ */ new Map();
25804
- var streamSymbols = /* @__PURE__ */ new Map();
25805
- function normalizeBinanceSymbol(symbol) {
25806
- return symbol.toUpperCase().trim();
25888
+ function computePriceRatio24h({
25889
+ longTokens,
25890
+ shortTokens,
25891
+ longTokensMetadata,
25892
+ shortTokensMetadata
25893
+ }) {
25894
+ const firstLong = longTokens[0];
25895
+ const firstShort = shortTokens[0];
25896
+ const longPrice = firstLong ? getPositiveValue(longTokensMetadata[firstLong.symbol], "prevDayPrice") : null;
25897
+ const shortPrice = firstShort ? getPositiveValue(shortTokensMetadata[firstShort.symbol], "prevDayPrice") : null;
25898
+ if (longPrice !== null && shortPrice !== null) {
25899
+ return longPrice / shortPrice;
25900
+ }
25901
+ if (longPrice !== null && shortTokens.length === 0) {
25902
+ return longPrice;
25903
+ }
25904
+ if (shortPrice !== null && longTokens.length === 0) {
25905
+ return shortPrice;
25906
+ }
25907
+ return null;
25807
25908
  }
25808
- function getNextRefCount(binanceSymbol) {
25809
- return (refCounts.get(binanceSymbol) ?? 0) + 1;
25909
+ function computeWeightedRatio({
25910
+ longTokens,
25911
+ shortTokens,
25912
+ longTokensMetadata,
25913
+ shortTokensMetadata
25914
+ }) {
25915
+ const longProduct = computeWeightedProduct(
25916
+ longTokens,
25917
+ longTokensMetadata,
25918
+ "currentPrice"
25919
+ );
25920
+ const shortProduct = computeWeightedProduct(
25921
+ shortTokens,
25922
+ shortTokensMetadata,
25923
+ "currentPrice",
25924
+ true
25925
+ );
25926
+ if (longProduct === null || shortProduct === null) {
25927
+ return null;
25928
+ }
25929
+ return longProduct * shortProduct;
25810
25930
  }
25811
- function getPrevRefCount(binanceSymbol) {
25812
- return Math.max(0, (refCounts.get(binanceSymbol) ?? 0) - 1);
25931
+ function computeWeightedRatio24h({
25932
+ longTokens,
25933
+ shortTokens,
25934
+ longTokensMetadata,
25935
+ shortTokensMetadata
25936
+ }) {
25937
+ const longProduct = computeWeightedProduct(
25938
+ longTokens,
25939
+ longTokensMetadata,
25940
+ "prevDayPrice"
25941
+ );
25942
+ const shortProduct = computeWeightedProduct(
25943
+ shortTokens,
25944
+ shortTokensMetadata,
25945
+ "prevDayPrice",
25946
+ true
25947
+ );
25948
+ if (longProduct === null || shortProduct === null) {
25949
+ return null;
25950
+ }
25951
+ return longProduct * shortProduct;
25813
25952
  }
25814
- var useBinanceMarkPriceStore = zustand.create((set) => ({
25815
- markPrices: {},
25816
- subscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
25817
- const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
25818
- const nextRefCount = getNextRefCount(binanceSymbol);
25819
- refCounts.set(binanceSymbol, nextRefCount);
25820
- const symbols = streamSymbols.get(binanceSymbol) ?? /* @__PURE__ */ new Set();
25821
- symbols.add(symmSymbol);
25822
- streamSymbols.set(binanceSymbol, symbols);
25823
- if (nextRefCount === 1) {
25824
- const wsManager = getBinanceWsManager();
25825
- const unsubscribe = wsManager.subscribeMarkPrice(binanceSymbol, (data) => {
25826
- const canonicalSymbol = normalizeBinanceSymbol(data.symbol);
25827
- const mappedSymbols = streamSymbols.get(canonicalSymbol);
25828
- if (!mappedSymbols || mappedSymbols.size === 0) return;
25829
- set((state) => {
25830
- const nextMarkPrices = { ...state.markPrices };
25831
- mappedSymbols.forEach((mappedSymbol) => {
25832
- nextMarkPrices[mappedSymbol] = data.markPrice;
25833
- });
25834
- return { markPrices: nextMarkPrices };
25835
- });
25836
- });
25837
- streamUnsubs.set(binanceSymbol, unsubscribe);
25838
- }
25839
- },
25840
- unsubscribeSymbol: (symmSymbol, rawBinanceSymbol) => {
25841
- const binanceSymbol = normalizeBinanceSymbol(rawBinanceSymbol);
25842
- const symbols = streamSymbols.get(binanceSymbol);
25843
- if (symbols) {
25844
- symbols.delete(symmSymbol);
25845
- if (symbols.size === 0) {
25846
- streamSymbols.delete(binanceSymbol);
25847
- } else {
25848
- streamSymbols.set(binanceSymbol, symbols);
25849
- }
25953
+ function computeNetFundingSum({
25954
+ longTokens,
25955
+ shortTokens,
25956
+ longTokensMetadata,
25957
+ shortTokensMetadata
25958
+ }) {
25959
+ let funding = 0;
25960
+ for (const token of longTokens) {
25961
+ const value = longTokensMetadata[token.symbol]?.netFunding;
25962
+ if (typeof value === "number" && Number.isFinite(value)) {
25963
+ funding += value;
25850
25964
  }
25851
- const nextRefCount = getPrevRefCount(binanceSymbol);
25852
- if (nextRefCount === 0) {
25853
- const unsubscribe = streamUnsubs.get(binanceSymbol);
25854
- if (unsubscribe) unsubscribe();
25855
- streamUnsubs.delete(binanceSymbol);
25856
- refCounts.delete(binanceSymbol);
25857
- } else {
25858
- refCounts.set(binanceSymbol, nextRefCount);
25965
+ }
25966
+ for (const token of shortTokens) {
25967
+ const value = shortTokensMetadata[token.symbol]?.netFunding;
25968
+ if (typeof value === "number" && Number.isFinite(value)) {
25969
+ funding += value;
25859
25970
  }
25860
- set((state) => {
25861
- if (state.markPrices[symmSymbol] == null) return state;
25862
- const nextMarkPrices = { ...state.markPrices };
25863
- delete nextMarkPrices[symmSymbol];
25864
- return { markPrices: nextMarkPrices };
25865
- });
25866
25971
  }
25867
- }));
25972
+ return funding;
25973
+ }
25868
25974
 
25869
25975
  // src/react/hooks/use-symm-token-selection-metadata.ts
25870
- async function fetchTickerSnapshot(symbol) {
25976
+ async function fetchTickerSnapshot2(symbol) {
25871
25977
  const resolution = resolveBinanceSymbol(symbol);
25872
25978
  if (!resolution.binanceSymbol) return null;
25873
25979
  const ticker = await fetch24hrTicker(resolution.binanceSymbol);
@@ -25923,7 +26029,7 @@ function useSymmTokenSelectionMetadata(selection, options = {}) {
25923
26029
  const results = await Promise.all(
25924
26030
  allSymbols.map(async ({ symbol }) => ({
25925
26031
  symbol,
25926
- ticker: await fetchTickerSnapshot(symbol)
26032
+ ticker: await fetchTickerSnapshot2(symbol)
25927
26033
  }))
25928
26034
  );
25929
26035
  const tickerSnapshots = {};
@@ -26455,6 +26561,7 @@ exports.useSymmSetTpslMutation = useSymmSetTpslMutation;
26455
26561
  exports.useSymmSetTriggerConfigMutation = useSymmSetTriggerConfigMutation;
26456
26562
  exports.useSymmSignTermsMutation = useSymmSignTermsMutation;
26457
26563
  exports.useSymmSignatureQuery = useSymmSignatureQuery;
26564
+ exports.useSymmTokenSelectionMarkets = useSymmTokenSelectionMarkets;
26458
26565
  exports.useSymmTokenSelectionMetadata = useSymmTokenSelectionMetadata;
26459
26566
  exports.useSymmTpslOrders = useSymmTpslOrders;
26460
26567
  exports.useSymmTradeHistory = useSymmTradeHistory;