@pear-protocol/hyperliquid-sdk 0.0.48 → 0.0.49-hip3-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import type { ApiResponse, CandleInterval, CandleData, ExternalFillDto } from '../types';
1
+ import type { ApiResponse, CandleInterval, CandleData, ExternalFillDto, AllPerpMetasResponse } from '../types';
2
2
  /**
3
3
  * Fetch historical candle data from HyperLiquid API
4
4
  */
@@ -7,3 +7,9 @@ export declare const fetchHistoricalCandles: (coin: string, startTime: number, e
7
7
  * Retrieve recent user fills from HyperLiquid and map to ExternalFillDto[]
8
8
  */
9
9
  export declare const fetchUserFillsFromHyperliquid: (user: string, startTime: number, aggregateByTime?: boolean) => Promise<ApiResponse<ExternalFillDto[]>>;
10
+ /**
11
+ * Fetch all perp metas from HyperLiquid API
12
+ * Endpoint: https://api.hyperliquid.xyz/info
13
+ * Payload: { "type": "allPerpMetas" }
14
+ */
15
+ export declare const fetchAllPerpMetas: () => Promise<ApiResponse<AllPerpMetasResponse>>;
package/dist/index.d.ts CHANGED
@@ -28,7 +28,7 @@ type WebSocketConnectionState = 'connecting' | 'connected' | 'disconnected' | 'e
28
28
  /**
29
29
  * WebSocket channels
30
30
  */
31
- type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'market-data' | 'market-data-all' | 'webData2' | 'allMids' | 'activeAssetData';
31
+ type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'market-data' | 'market-data-all' | 'webData3' | 'allMids' | 'activeAssetData';
32
32
  /**
33
33
  * WebSocket subscription message
34
34
  */
@@ -323,6 +323,7 @@ interface WebSocketMessage {
323
323
  method: "subscribe" | "unsubscribe";
324
324
  subscription: {
325
325
  type: string;
326
+ dex?: string;
326
327
  coin?: string;
327
328
  interval?: string;
328
329
  user?: string;
@@ -332,13 +333,44 @@ interface WebSocketMessage {
332
333
  /**
333
334
  * WebSocket response from HyperLiquid native API
334
335
  */
335
- type HLChannel = 'webData2' | 'allMids' | 'activeAssetData' | 'candle';
336
+ type HLChannel = 'webData3' | 'allMids' | 'activeAssetData' | 'candle';
336
337
  interface HLChannelDataMap {
337
- webData2: WebData2Response;
338
+ webData3: WebData3Response;
338
339
  allMids: WsAllMidsData;
339
340
  activeAssetData: ActiveAssetData;
340
341
  candle: CandleData;
341
342
  }
343
+ interface WebData3UserState {
344
+ agentAddress?: string;
345
+ agentValidUntil?: number;
346
+ cumLedger: string;
347
+ serverTime: number;
348
+ isVault: boolean;
349
+ user: string;
350
+ dexAbstractionEnabled?: boolean;
351
+ }
352
+ interface WebData3AssetCtx {
353
+ funding: string;
354
+ openInterest: string;
355
+ prevDayPx: string;
356
+ dayNtlVlm: string;
357
+ premium: string | null;
358
+ oraclePx: string;
359
+ markPx: string;
360
+ midPx: string | null;
361
+ impactPxs: string[] | null;
362
+ dayBaseVlm: string;
363
+ }
364
+ interface WebData3PerpDexState {
365
+ clearinghouseState: ClearinghouseState;
366
+ totalVaultEquity: string;
367
+ assetCtxs: WebData3AssetCtx[];
368
+ perpsAtOpenInterestCap: string[];
369
+ }
370
+ interface WebData3Response {
371
+ userState: WebData3UserState;
372
+ perpDexStates: WebData3PerpDexState[];
373
+ }
342
374
  interface HLWebSocketResponse<T extends HLChannel = HLChannel> {
343
375
  channel: T;
344
376
  data: HLChannelDataMap[T];
@@ -372,17 +404,6 @@ interface UniverseAsset {
372
404
  onlyIsolated?: boolean;
373
405
  isDelisted?: boolean;
374
406
  }
375
- /**
376
- * WebData2 response structure
377
- */
378
- interface WebData2Response {
379
- assetCtxs: AssetCtx[];
380
- meta: {
381
- universe: UniverseAsset[];
382
- };
383
- clearinghouseState: ClearinghouseState;
384
- perpsAtOpenInterestCap?: string[];
385
- }
386
407
  interface ClearinghouseState {
387
408
  assetPositions: AssetPosition[];
388
409
  crossMaintenanceMarginUsed: string;
@@ -484,9 +505,6 @@ interface ActiveAssetData {
484
505
  availableToTrade: [string, string];
485
506
  markPx: string;
486
507
  }
487
- /**
488
- * Token metadata from WebData2 and AllMids
489
- */
490
508
  interface TokenMetadata {
491
509
  currentPrice: number;
492
510
  prevDayPrice: number;
@@ -518,7 +536,7 @@ interface TokenConflict {
518
536
  conflictMessage: string;
519
537
  }
520
538
  interface AssetMarketData {
521
- asset: AssetCtx;
539
+ asset: WebData3AssetCtx | AssetCtx;
522
540
  universe: UniverseAsset;
523
541
  }
524
542
  interface PairAssetDto {
@@ -1118,19 +1136,16 @@ declare function toggleWatchlist(baseUrl: string, accessToken: string, longAsset
1118
1136
  * Account summary calculation utility class
1119
1137
  */
1120
1138
  declare class AccountSummaryCalculator {
1121
- private webData2;
1122
- constructor(webData2: WebData2Response | null);
1139
+ private clearinghouseState;
1140
+ constructor(clearinghouseState: ClearinghouseState | null);
1123
1141
  /**
1124
- * Calculate account summary from webData2 and platform orders
1142
+ * Calculate account summary from real-time clearinghouse state and platform orders
1125
1143
  */
1126
1144
  calculateAccountSummary(platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, agentWalletAddress?: string, agentWalletStatus?: string): AccountSummaryResponseDto | null;
1127
1145
  /**
1128
1146
  * Calculate total USD value of open limit orders
1129
1147
  */
1130
1148
  private calculateTotalLimitOrderValue;
1131
- /**
1132
- * Get real-time clearinghouse state from webData2
1133
- */
1134
1149
  getClearinghouseState(): ClearinghouseState | null;
1135
1150
  /**
1136
1151
  * Check if real-time data is available
@@ -1153,34 +1168,36 @@ declare class ConflictDetector {
1153
1168
  }
1154
1169
 
1155
1170
  /**
1156
- * Extracts token metadata from WebData2 and AllMids data
1171
+ * Extracts token metadata from aggregated WebData3 contexts and AllMids data
1157
1172
  */
1158
1173
  declare class TokenMetadataExtractor {
1159
1174
  /**
1160
1175
  * Extracts comprehensive token metadata
1161
1176
  * @param symbol - Token symbol
1162
- * @param webData2 - WebData2 response containing asset context and universe data
1177
+ * @param perpMetaAssets - Aggregated universe assets (flattened across dexes)
1178
+ * @param finalAssetContexts - Aggregated asset contexts (flattened across dexes)
1163
1179
  * @param allMids - AllMids data containing current prices
1164
1180
  * @param activeAssetData - Optional active asset data containing leverage information
1165
1181
  * @returns TokenMetadata or null if token not found
1166
1182
  */
1167
- static extractTokenMetadata(symbol: string, webData2: WebData2Response | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): TokenMetadata | null;
1183
+ static extractTokenMetadata(symbol: string, perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): TokenMetadata | null;
1168
1184
  /**
1169
1185
  * Extracts metadata for multiple tokens
1170
1186
  * @param symbols - Array of token symbols
1171
- * @param webData2 - WebData2 response
1187
+ * @param perpMetaAssets - Aggregated universe assets
1188
+ * @param finalAssetContexts - Aggregated asset contexts
1172
1189
  * @param allMids - AllMids data
1173
1190
  * @param activeAssetData - Optional active asset data containing leverage information
1174
1191
  * @returns Record of symbol to TokenMetadata
1175
1192
  */
1176
- static extractMultipleTokensMetadata(symbols: string[], webData2: WebData2Response | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): Record<string, TokenMetadata | null>;
1193
+ static extractMultipleTokensMetadata(symbols: string[], perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): Record<string, TokenMetadata | null>;
1177
1194
  /**
1178
- * Checks if token data is available in WebData2
1195
+ * Checks if token data is available in aggregated universe assets
1179
1196
  * @param symbol - Token symbol
1180
- * @param webData2 - WebData2 response
1197
+ * @param perpMetaAssets - Aggregated universe assets
1181
1198
  * @returns boolean indicating if token exists in universe
1182
1199
  */
1183
- static isTokenAvailable(symbol: string, webData2: WebData2Response | null): boolean;
1200
+ static isTokenAvailable(symbol: string, perpMetaAssets: UniverseAsset[] | null): boolean;
1184
1201
  }
1185
1202
 
1186
1203
  /**
@@ -1260,4 +1277,4 @@ declare function validatePositionSize(usdValue: number, longAssets?: PairAssetIn
1260
1277
  declare const useMarketData: any;
1261
1278
 
1262
1279
  export { AccountSummaryCalculator, AuthStatus, ConflictDetector, MINIMUM_ASSET_USD_VALUE, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAddress, useAgentWallet, useAllBaskets, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataAllPayload, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMinimumAssetSize, validatePositionSize };
1263
- export type { AccountSummaryResponseDto, ActiveAssetGroupItem, ActiveAssetsResponse, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AutoSyncFillsOptions, AutoSyncFillsState, BalanceSummaryDto, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ClearinghouseState, CloseAllPositionsResponseDto, CloseAllPositionsResultDto, CloseExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossMarginSummaryDto, CumFundingDto, ExecutionType, HLWebSocketResponse, HistoricalRange, LadderConfigInput, MarginSummaryDto, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderStatus, PairAssetDto, PairAssetInput, PerformanceOverlay, PortfolioBucketDto, PortfolioInterval, PortfolioIntervalsDto, PortfolioOverallDto, PortfolioResponseDto, PositionAdjustmentType, PositionAssetDetailDto, PositionAssetSummaryDto, PositionResponseStatus, RealtimeBar, RealtimeBarsCallback, ToggleWatchlistResponseDto, TokenConflict, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TpSlThresholdInput, TpSlThresholdType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TwapChunkStatusDto, TwapMonitoringDto, UniverseAsset, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAgentWalletOptions, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseNotificationsResult, UsePerformanceOverlaysReturn, UsePortfolioResult, UseTokenSelectionMetadataReturn, UserProfile, UserSelectionState, WatchlistItemDto, WebData2Response, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
1280
+ export type { AccountSummaryResponseDto, ActiveAssetGroupItem, ActiveAssetsResponse, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AutoSyncFillsOptions, AutoSyncFillsState, BalanceSummaryDto, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ClearinghouseState, CloseAllPositionsResponseDto, CloseAllPositionsResultDto, CloseExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossMarginSummaryDto, CumFundingDto, ExecutionType, HLWebSocketResponse, HistoricalRange, LadderConfigInput, MarginSummaryDto, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderStatus, PairAssetDto, PairAssetInput, PerformanceOverlay, PortfolioBucketDto, PortfolioInterval, PortfolioIntervalsDto, PortfolioOverallDto, PortfolioResponseDto, PositionAdjustmentType, PositionAssetDetailDto, PositionAssetSummaryDto, PositionResponseStatus, RealtimeBar, RealtimeBarsCallback, ToggleWatchlistResponseDto, TokenConflict, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TpSlThresholdInput, TpSlThresholdType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TwapChunkStatusDto, TwapMonitoringDto, UniverseAsset, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAgentWalletOptions, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseNotificationsResult, UsePerformanceOverlaysReturn, UsePortfolioResult, UseTokenSelectionMetadataReturn, UserProfile, UserSelectionState, WatchlistItemDto, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
package/dist/index.js CHANGED
@@ -225,11 +225,13 @@ const useHyperliquidWebSocket = ({ wsUrl, address }) => {
225
225
  };
226
226
 
227
227
  const useHyperliquidData = create((set, get) => ({
228
- webData2: null,
229
228
  allMids: null,
230
229
  activeAssetData: null,
231
230
  candleData: null,
232
- setWebData2: (value) => set({ webData2: value }),
231
+ finalAssetContexts: null,
232
+ finalAtOICaps: null,
233
+ aggregatedClearingHouseState: null,
234
+ perpMetaAssets: null,
233
235
  setAllMids: (value) => set({ allMids: value }),
234
236
  setActiveAssetData: (value) => set((state) => ({
235
237
  activeAssetData: typeof value === 'function' ? value(state.activeAssetData) : value
@@ -268,7 +270,11 @@ const useHyperliquidData = create((set, get) => ({
268
270
  ...state.activeAssetData,
269
271
  [key]: value,
270
272
  }
271
- }))
273
+ })),
274
+ setFinalAssetContexts: (value) => set({ finalAssetContexts: value }),
275
+ setFinalAtOICaps: (value) => set({ finalAtOICaps: value }),
276
+ setAggregatedClearingHouseState: (value) => set({ aggregatedClearingHouseState: value }),
277
+ setPerpMetaAssets: (value) => set({ perpMetaAssets: value })
272
278
  }));
273
279
 
274
280
  const DEFAULT_STATE = {
@@ -409,7 +415,7 @@ const useUserSelection$1 = create((set, get) => ({
409
415
  }));
410
416
 
411
417
  const useHyperliquidNativeWebSocket = ({ address, }) => {
412
- const { setWebData2, setAllMids, setActiveAssetData, upsertActiveAssetData, setCandleData, deleteCandleSymbol, deleteActiveAssetData, addCandleData } = useHyperliquidData();
418
+ const { setAllMids, setActiveAssetData, upsertActiveAssetData, setCandleData, deleteCandleSymbol, deleteActiveAssetData, addCandleData, setFinalAssetContexts, setFinalAtOICaps, setAggregatedClearingHouseState } = useHyperliquidData();
413
419
  const { candleInterval } = useUserSelection$1();
414
420
  const longTokens = useUserSelection$1((s) => s.longTokens);
415
421
  const shortTokens = useUserSelection$1((s) => s.shortTokens);
@@ -442,8 +448,44 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
442
448
  if ('channel' in message && 'data' in message) {
443
449
  const response = message;
444
450
  switch (response.channel) {
445
- case 'webData2':
446
- setWebData2(response.data);
451
+ case 'webData3':
452
+ const webData3 = response.data;
453
+ const finalAssetContexts = webData3.perpDexStates.flatMap((dex) => dex.assetCtxs);
454
+ const finalAtOICaps = webData3.perpDexStates.flatMap((dex) => dex.perpsAtOpenInterestCap);
455
+ const aggregatedClearingHouseState = (() => {
456
+ const states = webData3.perpDexStates
457
+ .map((dex) => dex.clearinghouseState)
458
+ .filter(Boolean);
459
+ const sum = (values) => values.reduce((acc, v) => acc + (parseFloat(v || '0') || 0), 0);
460
+ const toStr = (n) => (Number.isFinite(n) ? n.toString() : '0');
461
+ const assetPositions = states.flatMap((s) => s.assetPositions || []);
462
+ const crossMaintenanceMarginUsed = toStr(sum(states.map((s) => s.crossMaintenanceMarginUsed)));
463
+ const crossMarginSummary = {
464
+ accountValue: toStr(sum(states.map((s) => { var _a; return (_a = s.crossMarginSummary) === null || _a === void 0 ? void 0 : _a.accountValue; }))),
465
+ totalMarginUsed: toStr(sum(states.map((s) => { var _a; return (_a = s.crossMarginSummary) === null || _a === void 0 ? void 0 : _a.totalMarginUsed; }))),
466
+ totalNtlPos: toStr(sum(states.map((s) => { var _a; return (_a = s.crossMarginSummary) === null || _a === void 0 ? void 0 : _a.totalNtlPos; }))),
467
+ totalRawUsd: toStr(sum(states.map((s) => { var _a; return (_a = s.crossMarginSummary) === null || _a === void 0 ? void 0 : _a.totalRawUsd; }))),
468
+ };
469
+ const marginSummary = {
470
+ accountValue: toStr(sum(states.map((s) => { var _a; return (_a = s.marginSummary) === null || _a === void 0 ? void 0 : _a.accountValue; }))),
471
+ totalMarginUsed: toStr(sum(states.map((s) => { var _a; return (_a = s.marginSummary) === null || _a === void 0 ? void 0 : _a.totalMarginUsed; }))),
472
+ totalNtlPos: toStr(sum(states.map((s) => { var _a; return (_a = s.marginSummary) === null || _a === void 0 ? void 0 : _a.totalNtlPos; }))),
473
+ totalRawUsd: toStr(sum(states.map((s) => { var _a; return (_a = s.marginSummary) === null || _a === void 0 ? void 0 : _a.totalRawUsd; }))),
474
+ };
475
+ const withdrawable = toStr(sum(states.map((s) => s.withdrawable)));
476
+ const time = Math.max(0, ...states.map((s) => s.time || 0));
477
+ return {
478
+ assetPositions,
479
+ crossMaintenanceMarginUsed,
480
+ crossMarginSummary,
481
+ marginSummary,
482
+ time,
483
+ withdrawable,
484
+ };
485
+ })();
486
+ setFinalAssetContexts(finalAssetContexts);
487
+ setFinalAtOICaps(finalAtOICaps);
488
+ setAggregatedClearingHouseState(aggregatedClearingHouseState);
447
489
  break;
448
490
  case 'allMids':
449
491
  setAllMids(response.data);
@@ -466,7 +508,7 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
466
508
  console.error('[HyperLiquid WS] Parse error:', errorMessage, 'Raw message:', event.data);
467
509
  setLastError(errorMessage);
468
510
  }
469
- }, [setWebData2, setAllMids, upsertActiveAssetData, addCandleData]);
511
+ }, [setAllMids, upsertActiveAssetData, addCandleData, setFinalAssetContexts, setFinalAtOICaps, setAggregatedClearingHouseState]);
470
512
  const connect = useCallback(() => {
471
513
  try {
472
514
  manualCloseRef.current = false;
@@ -551,17 +593,17 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
551
593
  const unsubscribeMessage = {
552
594
  method: 'unsubscribe',
553
595
  subscription: {
554
- type: 'webData2',
596
+ type: 'webData3',
555
597
  user: subscribedAddress,
556
598
  },
557
599
  };
558
600
  sendJsonMessage(unsubscribeMessage);
559
601
  }
560
- // Subscribe to webData2 with new address
561
- const subscribeWebData2 = {
602
+ // Subscribe to webData3 with new address
603
+ const subscribeWebData3 = {
562
604
  method: 'subscribe',
563
605
  subscription: {
564
- type: 'webData2',
606
+ type: 'webData3',
565
607
  user: userAddress,
566
608
  },
567
609
  };
@@ -570,16 +612,18 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
570
612
  method: 'subscribe',
571
613
  subscription: {
572
614
  type: 'allMids',
615
+ dex: 'ALL_DEXS',
573
616
  },
574
617
  };
575
- sendJsonMessage(subscribeWebData2);
618
+ sendJsonMessage(subscribeWebData3);
576
619
  sendJsonMessage(subscribeAllMids);
577
620
  setSubscribedAddress(userAddress);
578
621
  // Clear previous data when address changes
579
622
  if (subscribedAddress && subscribedAddress !== userAddress) {
580
- setWebData2(null);
623
+ // clear aggregatedClearingHouseState
624
+ setAggregatedClearingHouseState(null);
581
625
  }
582
- }, [isConnected, address, subscribedAddress, sendJsonMessage, setWebData2]);
626
+ }, [isConnected, address, subscribedAddress, sendJsonMessage, setAggregatedClearingHouseState]);
583
627
  // Handle token subscriptions for activeAssetData
584
628
  useEffect(() => {
585
629
  if (!isConnected || !address)
@@ -4709,45 +4753,45 @@ const useAddress = () => {
4709
4753
  * Account summary calculation utility class
4710
4754
  */
4711
4755
  class AccountSummaryCalculator {
4712
- constructor(webData2) {
4713
- this.webData2 = webData2;
4756
+ constructor(clearinghouseState) {
4757
+ this.clearinghouseState = clearinghouseState;
4714
4758
  }
4715
4759
  /**
4716
- * Calculate account summary from webData2 and platform orders
4760
+ * Calculate account summary from real-time clearinghouse state and platform orders
4717
4761
  */
4718
4762
  calculateAccountSummary(platformAccountSummary, platformOpenOrders, agentWalletAddress, agentWalletStatus) {
4719
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
4720
- // If we don't have webData2, return platform data as-is
4721
- if (!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState)) {
4763
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
4764
+ // If we don't have real-time state, return platform data as-is
4765
+ if (!this.clearinghouseState) {
4722
4766
  return platformAccountSummary;
4723
4767
  }
4724
- const clearinghouseState = this.webData2.clearinghouseState;
4768
+ const clearinghouseState = this.clearinghouseState;
4725
4769
  // Calculate total limit order value from platform orders
4726
4770
  const totalLimitOrderValue = this.calculateTotalLimitOrderValue(platformOpenOrders || []);
4727
- // Use real-time data from webData2 clearinghouseState
4771
+ // Use real-time data from clearinghouseState
4728
4772
  const withdrawableAmount = parseFloat(clearinghouseState.withdrawable || '0');
4729
4773
  const adjustedWithdrawable = Math.max(0, withdrawableAmount - totalLimitOrderValue);
4730
4774
  const accountSummary = {
4731
4775
  balanceSummary: {
4732
4776
  crossMaintenanceMarginUsed: clearinghouseState.crossMaintenanceMarginUsed || '0',
4733
4777
  crossMarginSummary: {
4734
- accountValue: ((_b = clearinghouseState.crossMarginSummary) === null || _b === void 0 ? void 0 : _b.accountValue) || '0',
4735
- totalMarginUsed: ((_c = clearinghouseState.crossMarginSummary) === null || _c === void 0 ? void 0 : _c.totalMarginUsed) || '0',
4736
- totalNtlPos: ((_d = clearinghouseState.crossMarginSummary) === null || _d === void 0 ? void 0 : _d.totalNtlPos) || '0',
4737
- totalRawUsd: ((_e = clearinghouseState.crossMarginSummary) === null || _e === void 0 ? void 0 : _e.totalRawUsd) || '0'
4778
+ accountValue: ((_a = clearinghouseState.crossMarginSummary) === null || _a === void 0 ? void 0 : _a.accountValue) || '0',
4779
+ totalMarginUsed: ((_b = clearinghouseState.crossMarginSummary) === null || _b === void 0 ? void 0 : _b.totalMarginUsed) || '0',
4780
+ totalNtlPos: ((_c = clearinghouseState.crossMarginSummary) === null || _c === void 0 ? void 0 : _c.totalNtlPos) || '0',
4781
+ totalRawUsd: ((_d = clearinghouseState.crossMarginSummary) === null || _d === void 0 ? void 0 : _d.totalRawUsd) || '0'
4738
4782
  },
4739
4783
  marginSummary: {
4740
- accountValue: ((_f = clearinghouseState.marginSummary) === null || _f === void 0 ? void 0 : _f.accountValue) || '0',
4741
- totalMarginUsed: ((_g = clearinghouseState.marginSummary) === null || _g === void 0 ? void 0 : _g.totalMarginUsed) || '0',
4742
- totalNtlPos: ((_h = clearinghouseState.marginSummary) === null || _h === void 0 ? void 0 : _h.totalNtlPos) || '0',
4743
- totalRawUsd: ((_j = clearinghouseState.marginSummary) === null || _j === void 0 ? void 0 : _j.totalRawUsd) || '0'
4784
+ accountValue: ((_e = clearinghouseState.marginSummary) === null || _e === void 0 ? void 0 : _e.accountValue) || '0',
4785
+ totalMarginUsed: ((_f = clearinghouseState.marginSummary) === null || _f === void 0 ? void 0 : _f.totalMarginUsed) || '0',
4786
+ totalNtlPos: ((_g = clearinghouseState.marginSummary) === null || _g === void 0 ? void 0 : _g.totalNtlPos) || '0',
4787
+ totalRawUsd: ((_h = clearinghouseState.marginSummary) === null || _h === void 0 ? void 0 : _h.totalRawUsd) || '0'
4744
4788
  },
4745
4789
  time: clearinghouseState.time || Date.now(),
4746
4790
  withdrawable: adjustedWithdrawable.toString()
4747
4791
  },
4748
4792
  agentWallet: {
4749
- address: agentWalletAddress || ((_k = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _k === void 0 ? void 0 : _k.address) || '',
4750
- status: agentWalletStatus || ((_l = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _l === void 0 ? void 0 : _l.status) || 'UNKNOWN'
4793
+ address: agentWalletAddress || ((_j = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _j === void 0 ? void 0 : _j.address) || '',
4794
+ status: agentWalletStatus || ((_k = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _k === void 0 ? void 0 : _k.status) || 'UNKNOWN'
4751
4795
  }
4752
4796
  };
4753
4797
  return accountSummary;
@@ -4764,19 +4808,14 @@ class AccountSummaryCalculator {
4764
4808
  .reduce((sum, order) => sum + order.usdValue / order.leverage, 0);
4765
4809
  return totalValue;
4766
4810
  }
4767
- /**
4768
- * Get real-time clearinghouse state from webData2
4769
- */
4770
4811
  getClearinghouseState() {
4771
- var _a;
4772
- return ((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState) || null;
4812
+ return this.clearinghouseState || null;
4773
4813
  }
4774
4814
  /**
4775
4815
  * Check if real-time data is available
4776
4816
  */
4777
4817
  hasRealTimeData() {
4778
- var _a;
4779
- return !!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState);
4818
+ return !!this.clearinghouseState;
4780
4819
  }
4781
4820
  }
4782
4821
 
@@ -4816,13 +4855,13 @@ const useAccountSummary = () => {
4816
4855
  }
4817
4856
  const openOrders = useUserData((state) => state.openOrders);
4818
4857
  const accountSummary = useUserData((state) => state.accountSummary);
4819
- const webData2 = useHyperliquidData((state) => state.webData2);
4858
+ const aggregatedClearingHouseState = useHyperliquidData((state) => state.aggregatedClearingHouseState);
4820
4859
  const isLoading = useMemo(() => {
4821
4860
  // Loading is true initially and becomes false once we get the first data
4822
4861
  return accountSummary === null && context.isConnected;
4823
4862
  }, [accountSummary, context.isConnected]);
4824
4863
  // Create calculator and compute account summary
4825
- const calculator = new AccountSummaryCalculator(webData2);
4864
+ const calculator = new AccountSummaryCalculator(aggregatedClearingHouseState);
4826
4865
  const calculated = calculator.calculateAccountSummary(accountSummary, openOrders, (_a = accountSummary === null || accountSummary === void 0 ? void 0 : accountSummary.agentWallet) === null || _a === void 0 ? void 0 : _a.address, (_b = accountSummary === null || accountSummary === void 0 ? void 0 : accountSummary.agentWallet) === null || _b === void 0 ? void 0 : _b.status);
4827
4866
  return { data: calculated, isLoading };
4828
4867
  };
@@ -4836,28 +4875,29 @@ const useUserSelection = () => {
4836
4875
  * Hook to access webData and native WebSocket state
4837
4876
  */
4838
4877
  const useWebData = () => {
4839
- var _a;
4840
4878
  const context = useContext(PearHyperliquidContext);
4841
4879
  if (!context) {
4842
4880
  throw new Error('useWebData must be used within a PearHyperliquidProvider');
4843
4881
  }
4844
- const webData2 = useHyperliquidData((state) => state.webData2);
4882
+ const finalAssetContexts = useHyperliquidData((state) => state.finalAssetContexts);
4883
+ const perpMetaAssets = useHyperliquidData((state) => state.perpMetaAssets);
4884
+ const aggregatedClearinghouseState = useHyperliquidData((state) => state.aggregatedClearingHouseState);
4885
+ const finalAtOICaps = useHyperliquidData((state) => state.finalAtOICaps);
4845
4886
  let marketDataBySymbol = {};
4846
- if ((webData2 === null || webData2 === void 0 ? void 0 : webData2.assetCtxs) && ((_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe)) {
4847
- const { assetCtxs, meta: { universe } } = webData2;
4887
+ if (finalAssetContexts && perpMetaAssets && finalAssetContexts.length === perpMetaAssets.length) {
4848
4888
  const result = {};
4849
- for (let index = 0; index < universe.length; index++) {
4850
- const name = universe[index].name;
4889
+ for (let index = 0; index < perpMetaAssets.length; index++) {
4890
+ const name = perpMetaAssets[index].name;
4851
4891
  result[name] = {
4852
- asset: assetCtxs[index],
4853
- universe: universe[index],
4892
+ asset: finalAssetContexts[index],
4893
+ universe: perpMetaAssets[index],
4854
4894
  };
4855
4895
  }
4856
4896
  marketDataBySymbol = result;
4857
4897
  }
4858
4898
  return {
4859
- clearinghouseState: webData2 === null || webData2 === void 0 ? void 0 : webData2.clearinghouseState,
4860
- perpsAtOpenInterestCap: webData2 === null || webData2 === void 0 ? void 0 : webData2.perpsAtOpenInterestCap,
4899
+ clearinghouseState: aggregatedClearinghouseState,
4900
+ perpsAtOpenInterestCap: finalAtOICaps,
4861
4901
  marketDataBySymbol,
4862
4902
  isConnected: context.nativeIsConnected,
4863
4903
  error: context.nativeLastError,
@@ -4865,28 +4905,29 @@ const useWebData = () => {
4865
4905
  };
4866
4906
 
4867
4907
  /**
4868
- * Extracts token metadata from WebData2 and AllMids data
4908
+ * Extracts token metadata from aggregated WebData3 contexts and AllMids data
4869
4909
  */
4870
4910
  class TokenMetadataExtractor {
4871
4911
  /**
4872
4912
  * Extracts comprehensive token metadata
4873
4913
  * @param symbol - Token symbol
4874
- * @param webData2 - WebData2 response containing asset context and universe data
4914
+ * @param perpMetaAssets - Aggregated universe assets (flattened across dexes)
4915
+ * @param finalAssetContexts - Aggregated asset contexts (flattened across dexes)
4875
4916
  * @param allMids - AllMids data containing current prices
4876
4917
  * @param activeAssetData - Optional active asset data containing leverage information
4877
4918
  * @returns TokenMetadata or null if token not found
4878
4919
  */
4879
- static extractTokenMetadata(symbol, webData2, allMids, activeAssetData) {
4880
- if (!webData2 || !allMids) {
4920
+ static extractTokenMetadata(symbol, perpMetaAssets, finalAssetContexts, allMids, activeAssetData) {
4921
+ if (!perpMetaAssets || !finalAssetContexts || !allMids) {
4881
4922
  return null;
4882
4923
  }
4883
- // Find token index in universe
4884
- const universeIndex = webData2.meta.universe.findIndex(asset => asset.name === symbol);
4924
+ // Find token index in aggregated universe
4925
+ const universeIndex = perpMetaAssets.findIndex(asset => asset.name === symbol);
4885
4926
  if (universeIndex === -1) {
4886
4927
  return null;
4887
4928
  }
4888
- const universeAsset = webData2.meta.universe[universeIndex];
4889
- const assetCtx = webData2.assetCtxs[universeIndex];
4929
+ const universeAsset = perpMetaAssets[universeIndex];
4930
+ const assetCtx = finalAssetContexts[universeIndex];
4890
4931
  if (!assetCtx) {
4891
4932
  return null;
4892
4933
  }
@@ -4926,28 +4967,29 @@ class TokenMetadataExtractor {
4926
4967
  /**
4927
4968
  * Extracts metadata for multiple tokens
4928
4969
  * @param symbols - Array of token symbols
4929
- * @param webData2 - WebData2 response
4970
+ * @param perpMetaAssets - Aggregated universe assets
4971
+ * @param finalAssetContexts - Aggregated asset contexts
4930
4972
  * @param allMids - AllMids data
4931
4973
  * @param activeAssetData - Optional active asset data containing leverage information
4932
4974
  * @returns Record of symbol to TokenMetadata
4933
4975
  */
4934
- static extractMultipleTokensMetadata(symbols, webData2, allMids, activeAssetData) {
4976
+ static extractMultipleTokensMetadata(symbols, perpMetaAssets, finalAssetContexts, allMids, activeAssetData) {
4935
4977
  const result = {};
4936
4978
  for (const symbol of symbols) {
4937
- result[symbol] = this.extractTokenMetadata(symbol, webData2, allMids, activeAssetData);
4979
+ result[symbol] = this.extractTokenMetadata(symbol, perpMetaAssets, finalAssetContexts, allMids, activeAssetData);
4938
4980
  }
4939
4981
  return result;
4940
4982
  }
4941
4983
  /**
4942
- * Checks if token data is available in WebData2
4984
+ * Checks if token data is available in aggregated universe assets
4943
4985
  * @param symbol - Token symbol
4944
- * @param webData2 - WebData2 response
4986
+ * @param perpMetaAssets - Aggregated universe assets
4945
4987
  * @returns boolean indicating if token exists in universe
4946
4988
  */
4947
- static isTokenAvailable(symbol, webData2) {
4948
- if (!webData2)
4989
+ static isTokenAvailable(symbol, perpMetaAssets) {
4990
+ if (!perpMetaAssets)
4949
4991
  return false;
4950
- return webData2.meta.universe.some(asset => asset.name === symbol);
4992
+ return perpMetaAssets.some(asset => asset.name === symbol);
4951
4993
  }
4952
4994
  }
4953
4995
 
@@ -4966,16 +5008,16 @@ const useTokenSelectionMetadataStore = create((set) => ({
4966
5008
  maxLeverage: 0,
4967
5009
  minMargin: 0,
4968
5010
  leverageMatched: true,
4969
- recompute: ({ webData2, allMids, activeAssetData, marketData, longTokens, shortTokens }) => {
4970
- const isPriceDataReady = !!(webData2 && allMids);
5011
+ recompute: ({ perpMetaAssets, finalAssetContexts, allMids, activeAssetData, marketData, longTokens, shortTokens }) => {
5012
+ const isPriceDataReady = !!(perpMetaAssets && finalAssetContexts && allMids);
4971
5013
  // Compute metadata when ready
4972
5014
  const longSymbols = longTokens.map((t) => t.symbol);
4973
5015
  const shortSymbols = shortTokens.map((t) => t.symbol);
4974
5016
  const longTokensMetadata = isPriceDataReady
4975
- ? TokenMetadataExtractor.extractMultipleTokensMetadata(longSymbols, webData2, allMids, activeAssetData)
5017
+ ? TokenMetadataExtractor.extractMultipleTokensMetadata(longSymbols, perpMetaAssets, finalAssetContexts, allMids, activeAssetData)
4976
5018
  : {};
4977
5019
  const shortTokensMetadata = isPriceDataReady
4978
- ? TokenMetadataExtractor.extractMultipleTokensMetadata(shortSymbols, webData2, allMids, activeAssetData)
5020
+ ? TokenMetadataExtractor.extractMultipleTokensMetadata(shortSymbols, perpMetaAssets, finalAssetContexts, allMids, activeAssetData)
4979
5021
  : {};
4980
5022
  // Determine loading state
4981
5023
  const allTokens = [...longTokens, ...shortTokens];
@@ -5084,15 +5126,14 @@ const useTokenSelectionMetadataStore = create((set) => ({
5084
5126
  })();
5085
5127
  // Max leverage (minimum across all tokens)
5086
5128
  const maxLeverage = (() => {
5087
- var _a;
5088
- if (!((_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe))
5129
+ if (!perpMetaAssets)
5089
5130
  return 0;
5090
5131
  const allTokenSymbols = [...longTokens, ...shortTokens].map((t) => t.symbol);
5091
5132
  if (allTokenSymbols.length === 0)
5092
5133
  return 0;
5093
5134
  let minLev = Infinity;
5094
5135
  allTokenSymbols.forEach((symbol) => {
5095
- const tokenUniverse = webData2.meta.universe.find((u) => u.name === symbol);
5136
+ const tokenUniverse = perpMetaAssets.find((u) => u.name === symbol);
5096
5137
  if (tokenUniverse === null || tokenUniverse === void 0 ? void 0 : tokenUniverse.maxLeverage)
5097
5138
  minLev = Math.min(minLev, tokenUniverse.maxLeverage);
5098
5139
  });
@@ -5144,7 +5185,8 @@ const useTokenSelectionMetadata = () => {
5144
5185
  if (!context) {
5145
5186
  throw new Error('useTokenSelection must be used within PearHyperliquidProvider');
5146
5187
  }
5147
- const webData2 = useHyperliquidData((state) => state.webData2);
5188
+ const perpMetaAssets = useHyperliquidData((state) => state.perpMetaAssets);
5189
+ const finalAssetContexts = useHyperliquidData((state) => state.finalAssetContexts);
5148
5190
  const allMids = useHyperliquidData((state) => state.allMids);
5149
5191
  const activeAssetData = useHyperliquidData((state) => state.activeAssetData);
5150
5192
  const marketData = useMarketData((state) => state.marketData);
@@ -5153,7 +5195,8 @@ const useTokenSelectionMetadata = () => {
5153
5195
  // Recompute derived metadata when inputs change
5154
5196
  useEffect(() => {
5155
5197
  recompute({
5156
- webData2,
5198
+ perpMetaAssets,
5199
+ finalAssetContexts,
5157
5200
  allMids,
5158
5201
  activeAssetData: activeAssetData || null,
5159
5202
  marketData: marketData || null,
@@ -5162,7 +5205,7 @@ const useTokenSelectionMetadata = () => {
5162
5205
  });
5163
5206
  // We want to recompute when token lists or upstream data change
5164
5207
  // eslint-disable-next-line react-hooks/exhaustive-deps
5165
- }, [webData2, allMids, activeAssetData, JSON.stringify(longTokens), JSON.stringify(shortTokens)]);
5208
+ }, [perpMetaAssets, finalAssetContexts, allMids, activeAssetData, JSON.stringify(longTokens), JSON.stringify(shortTokens)]);
5166
5209
  return {
5167
5210
  // Loading states
5168
5211
  isLoading,
@@ -5337,6 +5380,23 @@ const fetchUserFillsFromHyperliquid = async (user, startTime, aggregateByTime =
5337
5380
  throw toApiError(error);
5338
5381
  }
5339
5382
  };
5383
+ /**
5384
+ * Fetch all perp metas from HyperLiquid API
5385
+ * Endpoint: https://api.hyperliquid.xyz/info
5386
+ * Payload: { "type": "allPerpMetas" }
5387
+ */
5388
+ const fetchAllPerpMetas = async () => {
5389
+ const request = { type: 'allPerpMetas' };
5390
+ try {
5391
+ const response = await axios$1.post('https://api.hyperliquid.xyz/info', request, {
5392
+ headers: { 'Content-Type': 'application/json' },
5393
+ });
5394
+ return { data: response.data, status: response.status, headers: response.headers };
5395
+ }
5396
+ catch (error) {
5397
+ throw toApiError(error);
5398
+ }
5399
+ };
5340
5400
 
5341
5401
  const useHistoricalPriceData = () => {
5342
5402
  const context = useContext(PearHyperliquidContext);
@@ -5444,7 +5504,6 @@ const useHistoricalPriceData = () => {
5444
5504
  }
5445
5505
  }, [
5446
5506
  getAllTokens,
5447
- candleInterval,
5448
5507
  storeHasData,
5449
5508
  getHistoricalPriceData,
5450
5509
  setTokenLoading,
@@ -6251,7 +6310,7 @@ const calculatePositionAsset = (asset, currentPrice, totalInitialPositionSize, l
6251
6310
  initialWeight: totalInitialPositionSize > 0 ? entryNotional / totalInitialPositionSize : 0,
6252
6311
  };
6253
6312
  };
6254
- const buildPositionValue = (rawPositions, webData2, allMids) => {
6313
+ const buildPositionValue = (rawPositions, clearinghouseState, allMids) => {
6255
6314
  return rawPositions.map((position) => {
6256
6315
  let mappedPosition = {
6257
6316
  positionId: position.positionId,
@@ -6270,7 +6329,7 @@ const buildPositionValue = (rawPositions, webData2, allMids) => {
6270
6329
  mappedPosition.longAssets = position.longAssets.map(longAsset => {
6271
6330
  var _a, _b, _c;
6272
6331
  const currentPrice = parseFloat(allMids.mids[longAsset.coin]);
6273
- const assetState = (_a = webData2.clearinghouseState.assetPositions.find(ap => ap.position.coin === longAsset.coin)) === null || _a === void 0 ? void 0 : _a.position;
6332
+ const assetState = (_a = clearinghouseState.assetPositions.find(ap => ap.position.coin === longAsset.coin)) === null || _a === void 0 ? void 0 : _a.position;
6274
6333
  const leverage = (_c = (_b = assetState === null || assetState === void 0 ? void 0 : assetState.leverage) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : 0;
6275
6334
  const mappedPositionAssets = calculatePositionAsset(longAsset, currentPrice, totalInitialPositionSize, leverage, true);
6276
6335
  mappedPosition.entryPositionValue += mappedPositionAssets.entryPositionValue;
@@ -6284,7 +6343,7 @@ const buildPositionValue = (rawPositions, webData2, allMids) => {
6284
6343
  mappedPosition.shortAssets = position.shortAssets.map(shortAsset => {
6285
6344
  var _a, _b, _c;
6286
6345
  const currentPrice = parseFloat(allMids.mids[shortAsset.coin]);
6287
- const assetState = (_a = webData2.clearinghouseState.assetPositions.find(ap => ap.position.coin === shortAsset.coin)) === null || _a === void 0 ? void 0 : _a.position;
6346
+ const assetState = (_a = clearinghouseState.assetPositions.find(ap => ap.position.coin === shortAsset.coin)) === null || _a === void 0 ? void 0 : _a.position;
6288
6347
  const leverage = (_c = (_b = assetState === null || assetState === void 0 ? void 0 : assetState.leverage) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : 0;
6289
6348
  const mappedPositionAssets = calculatePositionAsset(shortAsset, currentPrice, totalInitialPositionSize, leverage, false);
6290
6349
  mappedPosition.entryPositionValue += mappedPositionAssets.entryPositionValue;
@@ -6349,16 +6408,16 @@ function usePosition() {
6349
6408
  };
6350
6409
  // Open positions using WS data, with derived values
6351
6410
  const userOpenPositions = useUserData((state) => state.rawOpenPositions);
6352
- const webData2 = useHyperliquidData((state) => state.webData2);
6411
+ const aggregatedClearingHouseState = useHyperliquidData((state) => state.aggregatedClearingHouseState);
6353
6412
  const allMids = useHyperliquidData((state) => state.allMids);
6354
6413
  const isLoading = useMemo(() => {
6355
6414
  return userOpenPositions === null && isConnected;
6356
6415
  }, [userOpenPositions, isConnected]);
6357
6416
  const openPositions = useMemo(() => {
6358
- if (!userOpenPositions || !webData2 || !allMids)
6417
+ if (!userOpenPositions || !aggregatedClearingHouseState || !allMids)
6359
6418
  return null;
6360
- return buildPositionValue(userOpenPositions, webData2, allMids);
6361
- }, [userOpenPositions, webData2, allMids]);
6419
+ return buildPositionValue(userOpenPositions, aggregatedClearingHouseState, allMids);
6420
+ }, [userOpenPositions, aggregatedClearingHouseState, allMids]);
6362
6421
  return { createPosition: createPosition$1, updateRiskParameters: updateRiskParameters$1, closePosition: closePosition$1, closeAllPositions: closeAllPositions$1, adjustPosition: adjustPosition$1, openPositions, isLoading };
6363
6422
  }
6364
6423
 
@@ -6710,13 +6769,22 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
6710
6769
  const { isConnected: nativeIsConnected, lastError: nativeLastError } = useHyperliquidNativeWebSocket({
6711
6770
  address,
6712
6771
  });
6772
+ const perpsMetaAssets = useHyperliquidData((state) => state.perpMetaAssets);
6773
+ const setPerpMetaAssets = useHyperliquidData((state) => state.setPerpMetaAssets);
6713
6774
  // Auth hook
6714
- // Auth state inside provider (replaces useAuth internal state)
6715
6775
  const [authStatus, setAuthStatus] = useState(AuthStatus.Idle);
6716
6776
  const [user, setUser] = useState(null);
6717
6777
  const [authError, setAuthError] = useState(null);
6718
6778
  const [accessToken, setAccessToken] = useState(null);
6719
6779
  const isAuthenticated = useMemo(() => !!accessToken, [accessToken]);
6780
+ useEffect(() => {
6781
+ if (perpsMetaAssets === null) {
6782
+ fetchAllPerpMetas().then(res => {
6783
+ const aggregatedPerpMetas = res.data.flatMap(item => item.universe);
6784
+ setPerpMetaAssets(aggregatedPerpMetas);
6785
+ });
6786
+ }
6787
+ }, [perpsMetaAssets]);
6720
6788
  // Hydrate from existing token
6721
6789
  useEffect(() => {
6722
6790
  const access = localStorage.getItem('accessToken');
@@ -1,4 +1,4 @@
1
- import type { ActiveAssetData, TokenSelection, TokenMetadata, WebData2Response, WsAllMidsData, ActiveAssetsResponse } from "../types";
1
+ import type { ActiveAssetData, TokenSelection, TokenMetadata, WsAllMidsData, ActiveAssetsResponse, UniverseAsset, WebData3AssetCtx } from "../types";
2
2
  export interface TokenSelectionMetadataState {
3
3
  isPriceDataReady: boolean;
4
4
  isLoading: boolean;
@@ -15,7 +15,8 @@ export interface TokenSelectionMetadataState {
15
15
  minMargin: number;
16
16
  leverageMatched: boolean;
17
17
  recompute: (args: {
18
- webData2: WebData2Response | null;
18
+ perpMetaAssets: UniverseAsset[] | null;
19
+ finalAssetContexts: WebData3AssetCtx[] | null;
19
20
  allMids: WsAllMidsData | null;
20
21
  activeAssetData: Record<string, ActiveAssetData> | null;
21
22
  marketData: ActiveAssetsResponse | null;
package/dist/types.d.ts CHANGED
@@ -57,7 +57,7 @@ export declare enum ReadyState {
57
57
  /**
58
58
  * WebSocket channels
59
59
  */
60
- export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'market-data' | 'market-data-all' | 'webData2' | 'allMids' | 'activeAssetData';
60
+ export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'market-data' | 'market-data-all' | 'webData3' | 'allMids' | 'activeAssetData';
61
61
  /**
62
62
  * WebSocket subscription message
63
63
  */
@@ -416,6 +416,7 @@ export interface WebSocketMessage {
416
416
  method: "subscribe" | "unsubscribe";
417
417
  subscription: {
418
418
  type: string;
419
+ dex?: string;
419
420
  coin?: string;
420
421
  interval?: string;
421
422
  user?: string;
@@ -425,13 +426,44 @@ export interface WebSocketMessage {
425
426
  /**
426
427
  * WebSocket response from HyperLiquid native API
427
428
  */
428
- export type HLChannel = 'webData2' | 'allMids' | 'activeAssetData' | 'candle';
429
+ export type HLChannel = 'webData3' | 'allMids' | 'activeAssetData' | 'candle';
429
430
  export interface HLChannelDataMap {
430
- webData2: WebData2Response;
431
+ webData3: WebData3Response;
431
432
  allMids: WsAllMidsData;
432
433
  activeAssetData: ActiveAssetData;
433
434
  candle: CandleData;
434
435
  }
436
+ export interface WebData3UserState {
437
+ agentAddress?: string;
438
+ agentValidUntil?: number;
439
+ cumLedger: string;
440
+ serverTime: number;
441
+ isVault: boolean;
442
+ user: string;
443
+ dexAbstractionEnabled?: boolean;
444
+ }
445
+ export interface WebData3AssetCtx {
446
+ funding: string;
447
+ openInterest: string;
448
+ prevDayPx: string;
449
+ dayNtlVlm: string;
450
+ premium: string | null;
451
+ oraclePx: string;
452
+ markPx: string;
453
+ midPx: string | null;
454
+ impactPxs: string[] | null;
455
+ dayBaseVlm: string;
456
+ }
457
+ export interface WebData3PerpDexState {
458
+ clearinghouseState: ClearinghouseState;
459
+ totalVaultEquity: string;
460
+ assetCtxs: WebData3AssetCtx[];
461
+ perpsAtOpenInterestCap: string[];
462
+ }
463
+ export interface WebData3Response {
464
+ userState: WebData3UserState;
465
+ perpDexStates: WebData3PerpDexState[];
466
+ }
435
467
  export interface HLWebSocketResponse<T extends HLChannel = HLChannel> {
436
468
  channel: T;
437
469
  data: HLChannelDataMap[T];
@@ -465,17 +497,24 @@ export interface UniverseAsset {
465
497
  onlyIsolated?: boolean;
466
498
  isDelisted?: boolean;
467
499
  }
468
- /**
469
- * WebData2 response structure
470
- */
471
- export interface WebData2Response {
472
- assetCtxs: AssetCtx[];
473
- meta: {
474
- universe: UniverseAsset[];
475
- };
476
- clearinghouseState: ClearinghouseState;
477
- perpsAtOpenInterestCap?: string[];
500
+ export interface PerpMetaAsset extends UniverseAsset {
501
+ marginTableId: number;
478
502
  }
503
+ export interface MarginTier {
504
+ lowerBound: string;
505
+ maxLeverage: number;
506
+ }
507
+ export interface MarginTableDef {
508
+ description: string;
509
+ marginTiers: MarginTier[];
510
+ }
511
+ export type MarginTablesEntry = [number, MarginTableDef];
512
+ export interface AllPerpMetasItem {
513
+ universe: PerpMetaAsset[];
514
+ marginTables: MarginTablesEntry[];
515
+ collateralToken: number;
516
+ }
517
+ export type AllPerpMetasResponse = AllPerpMetasItem[];
479
518
  export interface ClearinghouseState {
480
519
  assetPositions: AssetPosition[];
481
520
  crossMaintenanceMarginUsed: string;
@@ -577,9 +616,6 @@ export interface ActiveAssetData {
577
616
  availableToTrade: [string, string];
578
617
  markPx: string;
579
618
  }
580
- /**
581
- * Token metadata from WebData2 and AllMids
582
- */
583
619
  export interface TokenMetadata {
584
620
  currentPrice: number;
585
621
  prevDayPrice: number;
@@ -611,7 +647,7 @@ export interface TokenConflict {
611
647
  conflictMessage: string;
612
648
  }
613
649
  export interface AssetMarketData {
614
- asset: AssetCtx;
650
+ asset: WebData3AssetCtx | AssetCtx;
615
651
  universe: UniverseAsset;
616
652
  }
617
653
  export interface PairAssetDto {
@@ -1,22 +1,19 @@
1
- import type { AccountSummaryResponseDto, WebData2Response, OpenLimitOrderDto } from '../types';
1
+ import type { AccountSummaryResponseDto, ClearinghouseState, OpenLimitOrderDto } from '../types';
2
2
  /**
3
3
  * Account summary calculation utility class
4
4
  */
5
5
  export declare class AccountSummaryCalculator {
6
- private webData2;
7
- constructor(webData2: WebData2Response | null);
6
+ private clearinghouseState;
7
+ constructor(clearinghouseState: ClearinghouseState | null);
8
8
  /**
9
- * Calculate account summary from webData2 and platform orders
9
+ * Calculate account summary from real-time clearinghouse state and platform orders
10
10
  */
11
11
  calculateAccountSummary(platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, agentWalletAddress?: string, agentWalletStatus?: string): AccountSummaryResponseDto | null;
12
12
  /**
13
13
  * Calculate total USD value of open limit orders
14
14
  */
15
15
  private calculateTotalLimitOrderValue;
16
- /**
17
- * Get real-time clearinghouse state from webData2
18
- */
19
- getClearinghouseState(): import("../types").ClearinghouseState | null;
16
+ getClearinghouseState(): ClearinghouseState | null;
20
17
  /**
21
18
  * Check if real-time data is available
22
19
  */
@@ -1,2 +1,2 @@
1
- import { OpenPositionDto, RawPositionDto, WebData2Response, WsAllMidsData } from "../types";
2
- export declare const buildPositionValue: (rawPositions: RawPositionDto[], webData2: WebData2Response, allMids: WsAllMidsData) => OpenPositionDto[];
1
+ import { OpenPositionDto, RawPositionDto, ClearinghouseState, WsAllMidsData } from "../types";
2
+ export declare const buildPositionValue: (rawPositions: RawPositionDto[], clearinghouseState: ClearinghouseState, allMids: WsAllMidsData) => OpenPositionDto[];
@@ -1,31 +1,33 @@
1
- import type { WebData2Response, WsAllMidsData, TokenMetadata, ActiveAssetData } from '../types';
1
+ import type { WsAllMidsData, TokenMetadata, ActiveAssetData, UniverseAsset, WebData3AssetCtx } from '../types';
2
2
  /**
3
- * Extracts token metadata from WebData2 and AllMids data
3
+ * Extracts token metadata from aggregated WebData3 contexts and AllMids data
4
4
  */
5
5
  export declare class TokenMetadataExtractor {
6
6
  /**
7
7
  * Extracts comprehensive token metadata
8
8
  * @param symbol - Token symbol
9
- * @param webData2 - WebData2 response containing asset context and universe data
9
+ * @param perpMetaAssets - Aggregated universe assets (flattened across dexes)
10
+ * @param finalAssetContexts - Aggregated asset contexts (flattened across dexes)
10
11
  * @param allMids - AllMids data containing current prices
11
12
  * @param activeAssetData - Optional active asset data containing leverage information
12
13
  * @returns TokenMetadata or null if token not found
13
14
  */
14
- static extractTokenMetadata(symbol: string, webData2: WebData2Response | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): TokenMetadata | null;
15
+ static extractTokenMetadata(symbol: string, perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): TokenMetadata | null;
15
16
  /**
16
17
  * Extracts metadata for multiple tokens
17
18
  * @param symbols - Array of token symbols
18
- * @param webData2 - WebData2 response
19
+ * @param perpMetaAssets - Aggregated universe assets
20
+ * @param finalAssetContexts - Aggregated asset contexts
19
21
  * @param allMids - AllMids data
20
22
  * @param activeAssetData - Optional active asset data containing leverage information
21
23
  * @returns Record of symbol to TokenMetadata
22
24
  */
23
- static extractMultipleTokensMetadata(symbols: string[], webData2: WebData2Response | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): Record<string, TokenMetadata | null>;
25
+ static extractMultipleTokensMetadata(symbols: string[], perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): Record<string, TokenMetadata | null>;
24
26
  /**
25
- * Checks if token data is available in WebData2
27
+ * Checks if token data is available in aggregated universe assets
26
28
  * @param symbol - Token symbol
27
- * @param webData2 - WebData2 response
29
+ * @param perpMetaAssets - Aggregated universe assets
28
30
  * @returns boolean indicating if token exists in universe
29
31
  */
30
- static isTokenAvailable(symbol: string, webData2: WebData2Response | null): boolean;
32
+ static isTokenAvailable(symbol: string, perpMetaAssets: UniverseAsset[] | null): boolean;
31
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.48",
3
+ "version": "0.0.49-hip3-alpha",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",