@pear-protocol/hyperliquid-sdk 0.0.63 → 0.0.64

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.
@@ -55,7 +55,6 @@ export interface CreatePositionResponseDto {
55
55
  * Create a position (MARKET/LIMIT/TWAP) using Pear Hyperliquid service
56
56
  * Authorization is derived from headers (Axios defaults or browser localStorage fallback)
57
57
  * @throws MinimumPositionSizeError if any asset has less than $11 USD value
58
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets (15)
59
58
  */
60
59
  export declare function createPosition(baseUrl: string, payload: CreatePositionRequestInput, displayToFull: Map<string, string>): Promise<ApiResponse<CreatePositionResponseDto>>;
61
60
  export interface UpdateRiskParametersRequestInput {
package/dist/index.d.ts CHANGED
@@ -411,12 +411,14 @@ interface WebSocketMessage {
411
411
  /**
412
412
  * WebSocket response from HyperLiquid native API
413
413
  */
414
- type HLChannel = "webData3" | "allMids" | "activeAssetData" | "candle";
414
+ type HLChannel = "webData3" | "allMids" | "activeAssetData" | "candle" | "allDexsClearinghouseState" | "allDexsAssetCtxs";
415
415
  interface HLChannelDataMap {
416
416
  webData3: WebData3Response;
417
417
  allMids: WsAllMidsData;
418
418
  activeAssetData: ActiveAssetData;
419
419
  candle: CandleData;
420
+ allDexsClearinghouseState: AllDexsClearinghouseStateData;
421
+ allDexsAssetCtxs: AllDexsAssetCtxsData;
420
422
  }
421
423
  interface WebData3UserState {
422
424
  agentAddress?: string;
@@ -449,6 +451,13 @@ interface WebData3Response {
449
451
  userState: WebData3UserState;
450
452
  perpDexStates: WebData3PerpDexState[];
451
453
  }
454
+ interface AllDexsClearinghouseStateData {
455
+ user: string;
456
+ clearinghouseStates: [string, ClearinghouseState][];
457
+ }
458
+ interface AllDexsAssetCtxsData {
459
+ ctxs: [string, WebData3AssetCtx[]][];
460
+ }
452
461
  interface HLWebSocketResponse<T extends HLChannel = HLChannel> {
453
462
  channel: T;
454
463
  data: HLChannelDataMap[T];
@@ -720,8 +729,7 @@ interface UserSelectionState {
720
729
  setConflicts: (conflicts: TokenConflict[]) => void;
721
730
  setCandleInterval: (interval: CandleInterval) => void;
722
731
  updateTokenWeight: (isLong: boolean, index: number, newWeight: number) => void;
723
- addToken: (isLong: boolean) => boolean;
724
- canAddToken: (isLong: boolean) => boolean;
732
+ addToken: (isLong: boolean) => void;
725
733
  removeToken: (isLong: boolean, index: number) => void;
726
734
  handleTokenSelect: (selectedToken: string) => void;
727
735
  setTokenSelections: (longTokens: TokenSelection[], shortTokens: TokenSelection[]) => void;
@@ -927,7 +935,6 @@ interface CreatePositionResponseDto {
927
935
  * Create a position (MARKET/LIMIT/TWAP) using Pear Hyperliquid service
928
936
  * Authorization is derived from headers (Axios defaults or browser localStorage fallback)
929
937
  * @throws MinimumPositionSizeError if any asset has less than $11 USD value
930
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets (15)
931
938
  */
932
939
  declare function createPosition(baseUrl: string, payload: CreatePositionRequestInput, displayToFull: Map<string, string>): Promise<ApiResponse<CreatePositionResponseDto>>;
933
940
  interface UpdateRiskParametersRequestInput {
@@ -1256,10 +1263,6 @@ declare function mapCandleIntervalToTradingViewInterval(interval: CandleInterval
1256
1263
  * Minimum USD value required per asset when creating a position
1257
1264
  */
1258
1265
  declare const MINIMUM_ASSET_USD_VALUE = 11;
1259
- /**
1260
- * Maximum number of assets allowed per leg (long or short) in a position
1261
- */
1262
- declare const MAX_ASSETS_PER_LEG = 15;
1263
1266
  /**
1264
1267
  * Validation error for minimum position size
1265
1268
  */
@@ -1269,22 +1272,6 @@ declare class MinimumPositionSizeError extends Error {
1269
1272
  minimumRequired: number;
1270
1273
  constructor(assetName: string, assetValue: number, minimumRequired: number);
1271
1274
  }
1272
- /**
1273
- * Validation error for exceeding maximum assets per leg
1274
- */
1275
- declare class MaxAssetsPerLegError extends Error {
1276
- leg: "long" | "short";
1277
- assetCount: number;
1278
- maxAllowed: number;
1279
- constructor(leg: "long" | "short", assetCount: number, maxAllowed: number);
1280
- }
1281
- /**
1282
- * Validates that each leg doesn't exceed the maximum number of assets
1283
- * @param longAssets Array of long assets
1284
- * @param shortAssets Array of short assets
1285
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets
1286
- */
1287
- declare function validateMaxAssetsPerLeg(longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): void;
1288
1275
  /**
1289
1276
  * Validates that each asset in a position has at least the minimum USD value
1290
1277
  * @param usdValue Total USD value for the position
@@ -1315,5 +1302,5 @@ declare function validatePositionSize(usdValue: number, longAssets?: PairAssetIn
1315
1302
 
1316
1303
  declare const useMarketData: any;
1317
1304
 
1318
- export { AccountSummaryCalculator, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAgentWallet, useAllBaskets, useAuth, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataAllPayload, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
1305
+ export { AccountSummaryCalculator, ConflictDetector, MINIMUM_ASSET_USD_VALUE, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAgentWallet, useAllBaskets, useAuth, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataAllPayload, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMinimumAssetSize, validatePositionSize };
1319
1306
  export type { AccountSummaryResponseDto, ActiveAssetGroupItem, ActiveAssetsResponse, AdjustAdvanceAssetInput, AdjustAdvanceItemInput, AdjustAdvanceResponseDto, 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, ExtraAgent, HLWebSocketResponse, HistoricalRange, LadderConfigInput, MarginSummaryDto, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderStatus, PairAssetDto, PairAssetInput, PerformanceOverlay, PlatformAccountSummaryResponseDto, PortfolioBucketDto, PortfolioInterval, PortfolioIntervalsDto, PortfolioOverallDto, PortfolioResponseDto, PositionAdjustmentType, PositionAssetDetailDto, PositionAssetSummaryDto, PositionResponseStatus, RealtimeBar, RealtimeBarsCallback, ToggleWatchlistResponseDto, TokenConflict, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TpSlThresholdInput, TpSlThresholdType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TwapChunkStatusDto, TwapMonitoringDto, TwapSliceFillResponseItem, UniverseAsset, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseNotificationsResult, UsePerformanceOverlaysReturn, UsePortfolioResult, UseTokenSelectionMetadataReturn, UserProfile, UserSelectionState, WatchlistItemDto, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
package/dist/index.js CHANGED
@@ -365,119 +365,6 @@ const useHyperliquidData = create((set, get) => ({
365
365
  setHip3DisplayToFull: (value) => set({ hip3DisplayToFull: value })
366
366
  }));
367
367
 
368
- /**
369
- * Minimum USD value required per asset when creating a position
370
- */
371
- const MINIMUM_ASSET_USD_VALUE = 11;
372
- /**
373
- * Maximum number of assets allowed per leg (long or short) in a position
374
- */
375
- const MAX_ASSETS_PER_LEG = 15;
376
- /**
377
- * Validation error for minimum position size
378
- */
379
- class MinimumPositionSizeError extends Error {
380
- constructor(assetName, assetValue, minimumRequired) {
381
- super(`Asset "${assetName}" has a USD value of $${assetValue.toFixed(2)}, which is below the minimum required value of $${minimumRequired.toFixed(2)}`);
382
- this.assetName = assetName;
383
- this.assetValue = assetValue;
384
- this.minimumRequired = minimumRequired;
385
- this.name = "MinimumPositionSizeError";
386
- }
387
- }
388
- /**
389
- * Validation error for exceeding maximum assets per leg
390
- */
391
- class MaxAssetsPerLegError extends Error {
392
- constructor(leg, assetCount, maxAllowed) {
393
- super(`Maximum ${maxAllowed} assets allowed per leg. Your ${leg} leg has ${assetCount} assets. Please reduce the number of assets to continue.`);
394
- this.leg = leg;
395
- this.assetCount = assetCount;
396
- this.maxAllowed = maxAllowed;
397
- this.name = "MaxAssetsPerLegError";
398
- }
399
- }
400
- /**
401
- * Validates that each leg doesn't exceed the maximum number of assets
402
- * @param longAssets Array of long assets
403
- * @param shortAssets Array of short assets
404
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets
405
- */
406
- function validateMaxAssetsPerLeg(longAssets, shortAssets) {
407
- const longCount = (longAssets === null || longAssets === void 0 ? void 0 : longAssets.length) || 0;
408
- const shortCount = (shortAssets === null || shortAssets === void 0 ? void 0 : shortAssets.length) || 0;
409
- if (longCount > MAX_ASSETS_PER_LEG) {
410
- throw new MaxAssetsPerLegError("long", longCount, MAX_ASSETS_PER_LEG);
411
- }
412
- if (shortCount > MAX_ASSETS_PER_LEG) {
413
- throw new MaxAssetsPerLegError("short", shortCount, MAX_ASSETS_PER_LEG);
414
- }
415
- }
416
- /**
417
- * Validates that each asset in a position has at least the minimum USD value
418
- * @param usdValue Total USD value for the position
419
- * @param longAssets Array of long assets with weights
420
- * @param shortAssets Array of short assets with weights
421
- * @throws MinimumPositionSizeError if any asset has less than the minimum USD value
422
- */
423
- function validateMinimumAssetSize(usdValue, longAssets, shortAssets) {
424
- var _a;
425
- const allAssets = [...(longAssets || []), ...(shortAssets || [])];
426
- if (allAssets.length === 0) {
427
- return; // No assets to validate
428
- }
429
- // Calculate total weight
430
- const totalWeight = allAssets.reduce((sum, asset) => { var _a; return sum + ((_a = asset.weight) !== null && _a !== void 0 ? _a : 0); }, 0);
431
- // If weights are not provided or sum to 0, assume equal distribution
432
- const hasWeights = totalWeight > 0;
433
- const equalWeight = hasWeights ? 0 : 1 / allAssets.length;
434
- // Validate each asset
435
- for (const asset of allAssets) {
436
- const weight = hasWeights ? (_a = asset.weight) !== null && _a !== void 0 ? _a : 0 : equalWeight;
437
- const assetUsdValue = usdValue * weight;
438
- if (assetUsdValue < MINIMUM_ASSET_USD_VALUE) {
439
- throw new MinimumPositionSizeError(asset.asset, assetUsdValue, MINIMUM_ASSET_USD_VALUE);
440
- }
441
- }
442
- }
443
- /**
444
- * Calculates the minimum USD value required for a position based on the number of assets
445
- * @param longAssets Array of long assets
446
- * @param shortAssets Array of short assets
447
- * @returns The minimum total USD value required
448
- */
449
- function calculateMinimumPositionValue(longAssets, shortAssets) {
450
- const totalAssets = ((longAssets === null || longAssets === void 0 ? void 0 : longAssets.length) || 0) + ((shortAssets === null || shortAssets === void 0 ? void 0 : shortAssets.length) || 0);
451
- if (totalAssets === 0) {
452
- return 0;
453
- }
454
- return MINIMUM_ASSET_USD_VALUE * totalAssets;
455
- }
456
- /**
457
- * Validates and provides a user-friendly error message with suggestions
458
- * @param usdValue Total USD value for the position
459
- * @param longAssets Array of long assets with weights
460
- * @param shortAssets Array of short assets with weights
461
- * @returns Validation result with success flag and optional error message
462
- */
463
- function validatePositionSize(usdValue, longAssets, shortAssets) {
464
- try {
465
- validateMinimumAssetSize(usdValue, longAssets, shortAssets);
466
- return { valid: true };
467
- }
468
- catch (error) {
469
- if (error instanceof MinimumPositionSizeError) {
470
- const minimumRequired = calculateMinimumPositionValue(longAssets, shortAssets);
471
- return {
472
- valid: false,
473
- error: error.message,
474
- minimumRequired,
475
- };
476
- }
477
- throw error;
478
- }
479
- }
480
-
481
368
  const DEFAULT_STATE = {
482
369
  longTokens: [
483
370
  { symbol: "HYPE", weight: 25 },
@@ -526,23 +413,14 @@ const useUserSelection$1 = create((set, get) => ({
526
413
  }
527
414
  });
528
415
  },
529
- canAddToken: (isLong) => {
530
- const currentTokens = isLong ? get().longTokens : get().shortTokens;
531
- return currentTokens.length < MAX_ASSETS_PER_LEG;
532
- },
533
416
  addToken: (isLong) => {
534
417
  const currentTokens = isLong ? get().longTokens : get().shortTokens;
535
- // Check if we've reached the maximum number of assets per leg
536
- if (currentTokens.length >= MAX_ASSETS_PER_LEG) {
537
- return false;
538
- }
539
418
  const newIndex = currentTokens.length;
540
419
  set((prev) => ({
541
420
  ...prev,
542
421
  selectorConfig: { isLong, index: newIndex },
543
422
  openTokenSelector: true,
544
423
  }));
545
- return true;
546
424
  },
547
425
  removeToken: (isLong, index) => {
548
426
  set((prev) => {
@@ -660,11 +538,22 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
660
538
  switch (response.channel) {
661
539
  case 'webData3':
662
540
  const webData3 = response.data;
663
- const finalAssetContexts = webData3.perpDexStates.flatMap((dex) => dex.assetCtxs);
541
+ // finalAssetContexts now sourced from allDexsAssetCtxs channel
664
542
  const finalAtOICaps = webData3.perpDexStates.flatMap((dex) => dex.perpsAtOpenInterestCap);
665
- const aggregatedClearingHouseState = (() => {
666
- const states = webData3.perpDexStates
667
- .map((dex) => dex.clearinghouseState)
543
+ setFinalAtOICaps(finalAtOICaps);
544
+ break;
545
+ case 'allDexsAssetCtxs':
546
+ {
547
+ const data = response.data;
548
+ const finalAssetContexts = (data.ctxs || []).flatMap(([, ctxs]) => ctxs || []);
549
+ setFinalAssetContexts(finalAssetContexts);
550
+ }
551
+ break;
552
+ case 'allDexsClearinghouseState':
553
+ {
554
+ const data = response.data;
555
+ const states = (data.clearinghouseStates || [])
556
+ .map(([, s]) => s)
668
557
  .filter(Boolean);
669
558
  const sum = (values) => values.reduce((acc, v) => acc + (parseFloat(v || '0') || 0), 0);
670
559
  const toStr = (n) => (Number.isFinite(n) ? n.toString() : '0');
@@ -684,7 +573,7 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
684
573
  };
685
574
  const withdrawable = toStr(sum(states.map((s) => s.withdrawable)));
686
575
  const time = Math.max(0, ...states.map((s) => s.time || 0));
687
- return {
576
+ const aggregatedClearingHouseState = {
688
577
  assetPositions,
689
578
  crossMaintenanceMarginUsed,
690
579
  crossMarginSummary,
@@ -692,10 +581,8 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
692
581
  time,
693
582
  withdrawable,
694
583
  };
695
- })();
696
- setFinalAssetContexts(finalAssetContexts);
697
- setFinalAtOICaps(finalAtOICaps);
698
- setAggregatedClearingHouseState(aggregatedClearingHouseState);
584
+ setAggregatedClearingHouseState(aggregatedClearingHouseState);
585
+ }
699
586
  break;
700
587
  case 'allMids':
701
588
  {
@@ -832,8 +719,15 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
832
719
  },
833
720
  };
834
721
  sendJsonMessage(unsubscribeMessage);
722
+ const unsubscribeAllDexsClearinghouseState = {
723
+ method: 'unsubscribe',
724
+ subscription: {
725
+ type: 'allDexsClearinghouseState',
726
+ user: subscribedAddress,
727
+ },
728
+ };
729
+ sendJsonMessage(unsubscribeAllDexsClearinghouseState);
835
730
  }
836
- // Subscribe to webData3 with new address
837
731
  const subscribeWebData3 = {
838
732
  method: 'subscribe',
839
733
  subscription: {
@@ -841,6 +735,14 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
841
735
  user: userAddress,
842
736
  },
843
737
  };
738
+ // Subscribe to allDexsClearinghouseState with the same payload as webData3
739
+ const subscribeAllDexsClearinghouseState = {
740
+ method: 'subscribe',
741
+ subscription: {
742
+ type: 'allDexsClearinghouseState',
743
+ user: userAddress,
744
+ },
745
+ };
844
746
  // Subscribe to allMids
845
747
  const subscribeAllMids = {
846
748
  method: 'subscribe',
@@ -849,8 +751,17 @@ const useHyperliquidNativeWebSocket = ({ address, enabled = true, }) => {
849
751
  dex: 'ALL_DEXS',
850
752
  },
851
753
  };
754
+ // Subscribe to allDexsAssetCtxs (no payload params, global feed)
755
+ const subscribeAllDexsAssetCtxs = {
756
+ method: 'subscribe',
757
+ subscription: {
758
+ type: 'allDexsAssetCtxs',
759
+ },
760
+ };
852
761
  sendJsonMessage(subscribeWebData3);
762
+ sendJsonMessage(subscribeAllDexsClearinghouseState);
853
763
  sendJsonMessage(subscribeAllMids);
764
+ sendJsonMessage(subscribeAllDexsAssetCtxs);
854
765
  setSubscribedAddress(userAddress);
855
766
  // Clear previous data when address changes
856
767
  if (subscribedAddress && subscribedAddress !== userAddress) {
@@ -6376,15 +6287,93 @@ function useAutoSyncFills(options) {
6376
6287
  };
6377
6288
  }
6378
6289
 
6290
+ /**
6291
+ * Minimum USD value required per asset when creating a position
6292
+ */
6293
+ const MINIMUM_ASSET_USD_VALUE = 11;
6294
+ /**
6295
+ * Validation error for minimum position size
6296
+ */
6297
+ class MinimumPositionSizeError extends Error {
6298
+ constructor(assetName, assetValue, minimumRequired) {
6299
+ super(`Asset "${assetName}" has a USD value of $${assetValue.toFixed(2)}, which is below the minimum required value of $${minimumRequired.toFixed(2)}`);
6300
+ this.assetName = assetName;
6301
+ this.assetValue = assetValue;
6302
+ this.minimumRequired = minimumRequired;
6303
+ this.name = "MinimumPositionSizeError";
6304
+ }
6305
+ }
6306
+ /**
6307
+ * Validates that each asset in a position has at least the minimum USD value
6308
+ * @param usdValue Total USD value for the position
6309
+ * @param longAssets Array of long assets with weights
6310
+ * @param shortAssets Array of short assets with weights
6311
+ * @throws MinimumPositionSizeError if any asset has less than the minimum USD value
6312
+ */
6313
+ function validateMinimumAssetSize(usdValue, longAssets, shortAssets) {
6314
+ var _a;
6315
+ const allAssets = [...(longAssets || []), ...(shortAssets || [])];
6316
+ if (allAssets.length === 0) {
6317
+ return; // No assets to validate
6318
+ }
6319
+ // Calculate total weight
6320
+ const totalWeight = allAssets.reduce((sum, asset) => { var _a; return sum + ((_a = asset.weight) !== null && _a !== void 0 ? _a : 0); }, 0);
6321
+ // If weights are not provided or sum to 0, assume equal distribution
6322
+ const hasWeights = totalWeight > 0;
6323
+ const equalWeight = hasWeights ? 0 : 1 / allAssets.length;
6324
+ // Validate each asset
6325
+ for (const asset of allAssets) {
6326
+ const weight = hasWeights ? (_a = asset.weight) !== null && _a !== void 0 ? _a : 0 : equalWeight;
6327
+ const assetUsdValue = usdValue * weight;
6328
+ if (assetUsdValue < MINIMUM_ASSET_USD_VALUE) {
6329
+ throw new MinimumPositionSizeError(asset.asset, assetUsdValue, MINIMUM_ASSET_USD_VALUE);
6330
+ }
6331
+ }
6332
+ }
6333
+ /**
6334
+ * Calculates the minimum USD value required for a position based on the number of assets
6335
+ * @param longAssets Array of long assets
6336
+ * @param shortAssets Array of short assets
6337
+ * @returns The minimum total USD value required
6338
+ */
6339
+ function calculateMinimumPositionValue(longAssets, shortAssets) {
6340
+ const totalAssets = ((longAssets === null || longAssets === void 0 ? void 0 : longAssets.length) || 0) + ((shortAssets === null || shortAssets === void 0 ? void 0 : shortAssets.length) || 0);
6341
+ if (totalAssets === 0) {
6342
+ return 0;
6343
+ }
6344
+ return MINIMUM_ASSET_USD_VALUE * totalAssets;
6345
+ }
6346
+ /**
6347
+ * Validates and provides a user-friendly error message with suggestions
6348
+ * @param usdValue Total USD value for the position
6349
+ * @param longAssets Array of long assets with weights
6350
+ * @param shortAssets Array of short assets with weights
6351
+ * @returns Validation result with success flag and optional error message
6352
+ */
6353
+ function validatePositionSize(usdValue, longAssets, shortAssets) {
6354
+ try {
6355
+ validateMinimumAssetSize(usdValue, longAssets, shortAssets);
6356
+ return { valid: true };
6357
+ }
6358
+ catch (error) {
6359
+ if (error instanceof MinimumPositionSizeError) {
6360
+ const minimumRequired = calculateMinimumPositionValue(longAssets, shortAssets);
6361
+ return {
6362
+ valid: false,
6363
+ error: error.message,
6364
+ minimumRequired,
6365
+ };
6366
+ }
6367
+ throw error;
6368
+ }
6369
+ }
6370
+
6379
6371
  /**
6380
6372
  * Create a position (MARKET/LIMIT/TWAP) using Pear Hyperliquid service
6381
6373
  * Authorization is derived from headers (Axios defaults or browser localStorage fallback)
6382
6374
  * @throws MinimumPositionSizeError if any asset has less than $11 USD value
6383
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets (15)
6384
6375
  */
6385
6376
  async function createPosition(baseUrl, payload, displayToFull) {
6386
- // Validate maximum assets per leg before creating position
6387
- validateMaxAssetsPerLeg(payload.longAssets, payload.shortAssets);
6388
6377
  // Validate minimum asset size before creating position
6389
6378
  validateMinimumAssetSize(payload.usdValue, payload.longAssets, payload.shortAssets);
6390
6379
  const url = joinUrl(baseUrl, "/positions");
@@ -7354,4 +7343,4 @@ function mapCandleIntervalToTradingViewInterval(interval) {
7354
7343
  }
7355
7344
  }
7356
7345
 
7357
- export { AccountSummaryCalculator, ConflictDetector, MAX_ASSETS_PER_LEG, MINIMUM_ASSET_USD_VALUE, MaxAssetsPerLegError, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAgentWallet, useAllBaskets, useAuth, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataAllPayload, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMaxAssetsPerLeg, validateMinimumAssetSize, validatePositionSize };
7346
+ export { AccountSummaryCalculator, ConflictDetector, MINIMUM_ASSET_USD_VALUE, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustAdvancePosition, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAgentWallet, useAllBaskets, useAuth, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataAllPayload, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMinimumAssetSize, validatePositionSize };
@@ -16,8 +16,7 @@ interface UserSelectionState {
16
16
  setConflicts: (conflicts: TokenConflict[]) => void;
17
17
  setCandleInterval: (interval: CandleInterval) => void;
18
18
  updateTokenWeight: (isLong: boolean, index: number, newWeight: number) => void;
19
- addToken: (isLong: boolean) => boolean;
20
- canAddToken: (isLong: boolean) => boolean;
19
+ addToken: (isLong: boolean) => void;
21
20
  removeToken: (isLong: boolean, index: number) => void;
22
21
  handleTokenSelect: (selectedToken: string) => void;
23
22
  setTokenSelections: (longTokens: TokenSelection[], shortTokens: TokenSelection[]) => void;
package/dist/types.d.ts CHANGED
@@ -441,12 +441,14 @@ export interface WebSocketMessage {
441
441
  /**
442
442
  * WebSocket response from HyperLiquid native API
443
443
  */
444
- export type HLChannel = "webData3" | "allMids" | "activeAssetData" | "candle";
444
+ export type HLChannel = "webData3" | "allMids" | "activeAssetData" | "candle" | "allDexsClearinghouseState" | "allDexsAssetCtxs";
445
445
  export interface HLChannelDataMap {
446
446
  webData3: WebData3Response;
447
447
  allMids: WsAllMidsData;
448
448
  activeAssetData: ActiveAssetData;
449
449
  candle: CandleData;
450
+ allDexsClearinghouseState: AllDexsClearinghouseStateData;
451
+ allDexsAssetCtxs: AllDexsAssetCtxsData;
450
452
  }
451
453
  export interface WebData3UserState {
452
454
  agentAddress?: string;
@@ -479,6 +481,13 @@ export interface WebData3Response {
479
481
  userState: WebData3UserState;
480
482
  perpDexStates: WebData3PerpDexState[];
481
483
  }
484
+ export interface AllDexsClearinghouseStateData {
485
+ user: string;
486
+ clearinghouseStates: [string, ClearinghouseState][];
487
+ }
488
+ export interface AllDexsAssetCtxsData {
489
+ ctxs: [string, WebData3AssetCtx[]][];
490
+ }
482
491
  export interface HLWebSocketResponse<T extends HLChannel = HLChannel> {
483
492
  channel: T;
484
493
  data: HLChannelDataMap[T];
@@ -3,10 +3,6 @@ import type { PairAssetInput } from "../clients/positions";
3
3
  * Minimum USD value required per asset when creating a position
4
4
  */
5
5
  export declare const MINIMUM_ASSET_USD_VALUE = 11;
6
- /**
7
- * Maximum number of assets allowed per leg (long or short) in a position
8
- */
9
- export declare const MAX_ASSETS_PER_LEG = 15;
10
6
  /**
11
7
  * Validation error for minimum position size
12
8
  */
@@ -16,22 +12,6 @@ export declare class MinimumPositionSizeError extends Error {
16
12
  minimumRequired: number;
17
13
  constructor(assetName: string, assetValue: number, minimumRequired: number);
18
14
  }
19
- /**
20
- * Validation error for exceeding maximum assets per leg
21
- */
22
- export declare class MaxAssetsPerLegError extends Error {
23
- leg: "long" | "short";
24
- assetCount: number;
25
- maxAllowed: number;
26
- constructor(leg: "long" | "short", assetCount: number, maxAllowed: number);
27
- }
28
- /**
29
- * Validates that each leg doesn't exceed the maximum number of assets
30
- * @param longAssets Array of long assets
31
- * @param shortAssets Array of short assets
32
- * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets
33
- */
34
- export declare function validateMaxAssetsPerLeg(longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): void;
35
15
  /**
36
16
  * Validates that each asset in a position has at least the minimum USD value
37
17
  * @param usdValue Total USD value for the position
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.63",
3
+ "version": "0.0.64",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",