@liberfi.io/ui-perpetuals 0.2.18 → 0.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -12,7 +12,7 @@ declare global {
12
12
  };
13
13
  }
14
14
  }
15
- declare const _default: "0.2.18";
15
+ declare const _default: "0.2.20";
16
16
 
17
17
  /**
18
18
  * Trading pair symbol format
@@ -190,7 +190,15 @@ interface Trade {
190
190
  interface Account {
191
191
  /** Total account equity */
192
192
  totalEquity: number;
193
- /** Available balance */
193
+ /**
194
+ * Funds the user can spend on a new isolated position or withdraw
195
+ * from the venue. For Hyperliquid this maps to the `withdrawable`
196
+ * field on `clearinghouseState`, which already accounts for cross
197
+ * margin reservations and the maintenance buffer — using it (rather
198
+ * than `accountValue - totalMarginUsed`) keeps the form's "Available
199
+ * Margin" figure aligned with what the venue actually permits when
200
+ * placing a trade or withdrawing.
201
+ */
194
202
  availableBalance: number;
195
203
  /** Total unrealized PnL */
196
204
  totalUnrealizedPnl: number;
@@ -199,6 +207,73 @@ interface Account {
199
207
  /** Account leverage */
200
208
  accountLeverage?: number;
201
209
  }
210
+ /**
211
+ * A single coin's balance in the user's spot wallet.
212
+ *
213
+ * Mirrors Hyperliquid's `spotClearinghouseState.balances[]` after numeric
214
+ * parsing so consumers don't have to repeat the `parseFloat` ritual.
215
+ */
216
+ interface SpotBalance {
217
+ /** Coin symbol, e.g. "USDC", "USOL". */
218
+ coin: string;
219
+ /** Total balance (free + held), in coin units. */
220
+ total: number;
221
+ /**
222
+ * Raw `total` string as returned by the venue. Preserves the venue's
223
+ * exact precision — JS `number` round-tripping can drop trailing
224
+ * zeros or significant digits that matter for display
225
+ * (e.g. `"0.00000005"` → `5e-8` → `"5e-8"`). Prefer this string when
226
+ * showing the balance to a user.
227
+ */
228
+ totalRaw?: string;
229
+ /** Held portion (locked in open orders), in coin units. */
230
+ hold: number;
231
+ /**
232
+ * Average notional value at acquisition, when the venue tracks it.
233
+ * Used by some UIs to compute realised PnL on spot positions.
234
+ */
235
+ entryNotional?: number;
236
+ }
237
+ /**
238
+ * Aggregated user state across the perpetuals + spot wallet, in the
239
+ * canonical SDK shape.
240
+ *
241
+ * This is the unit emitted by {@link IPerpetualsClient.subscribeAccountState}
242
+ * — venues that expose a single push channel for the user (Hyperliquid's
243
+ * `webData2`, Drift's `userAccount` pub/sub, etc.) parse it into this
244
+ * shape so React Query caches consumed by `usePositionsQuery`,
245
+ * `useOrdersQuery`, and `useAccountStateQuery` stay in sync without
246
+ * additional REST polls.
247
+ *
248
+ * The `raw` field carries the venue's untransformed payload for
249
+ * power-users / debugging; treat it as opaque.
250
+ */
251
+ interface AccountState {
252
+ /** Open positions (filtered to non-zero quantity). */
253
+ positions: Position[];
254
+ /** Open limit / trigger orders. */
255
+ openOrders: Order[];
256
+ /** Spot wallet balances. */
257
+ spotBalances: SpotBalance[];
258
+ /**
259
+ * Total cross-margin account value in USDC (perp + isolated isolated
260
+ * positions combined). Mirrors `clearinghouseState.marginSummary.accountValue`.
261
+ */
262
+ totalEquity: number;
263
+ /**
264
+ * Funds available to open a new isolated position or withdraw —
265
+ * {@link Account.availableBalance}. Sourced from `withdrawable` on
266
+ * Hyperliquid; falls back to `accountValue - totalMarginUsed` when
267
+ * the venue omits an explicit field.
268
+ */
269
+ availableBalance: number;
270
+ /** Sum of unrealised PnL across open positions. */
271
+ totalUnrealizedPnl: number;
272
+ /** Venue-reported server time of the snapshot, if available (ms epoch). */
273
+ serverTime?: number;
274
+ /** Raw payload from the venue (untransformed) for debugging. */
275
+ raw?: any;
276
+ }
202
277
  /**
203
278
  * Position information
204
279
  */
@@ -207,8 +282,16 @@ interface Position {
207
282
  symbol: string;
208
283
  /** Position direction (long or short) */
209
284
  side: OrderSide;
210
- /** Position quantity (positive for long, negative for short) */
285
+ /** Position quantity (always positive; use `side` for direction). */
211
286
  quantity: number;
287
+ /**
288
+ * Raw absolute quantity string as returned by the venue (e.g.
289
+ * Hyperliquid's `position.szi` with the sign stripped). Preserves
290
+ * the venue's exact precision — the parsed `quantity` field may lose
291
+ * trailing zeros or significant digits when round-tripped through
292
+ * JS `number`. Prefer this string for display.
293
+ */
294
+ quantityRaw?: string;
212
295
  /** Entry price */
213
296
  entryPrice: number;
214
297
  /** Current mark price */
@@ -227,6 +310,22 @@ interface Position {
227
310
  notionalValue: number;
228
311
  /** Timestamp (milliseconds) */
229
312
  timestamp?: number;
313
+ /**
314
+ * Active take-profit trigger price (USD) for this position, derived
315
+ * from the venue's open trigger orders. Only the trigger that would
316
+ * actually close this position is reported (i.e. matching the
317
+ * closing-side: SELL for a Long position, BUY for a Short).
318
+ *
319
+ * `undefined` when no matching trigger exists. Picked from the most
320
+ * recent matching `Take Profit Market` reduceOnly trigger.
321
+ */
322
+ takeProfitPrice?: number;
323
+ /**
324
+ * Active stop-loss trigger price (USD) for this position. Same
325
+ * semantics as {@link takeProfitPrice}, but for the most recent
326
+ * matching `Stop Market` reduceOnly trigger.
327
+ */
328
+ stopLossPrice?: number;
230
329
  }
231
330
  /**
232
331
  * Order information
@@ -260,6 +359,30 @@ interface Order {
260
359
  leverage?: number;
261
360
  /** Reduce only flag (optional) */
262
361
  reduceOnly?: boolean;
362
+ /**
363
+ * Whether this order is a trigger order (stop-market, take-profit-market,
364
+ * etc.). Mirrors Hyperliquid's `isTrigger`. When `true`, {@link triggerPx}
365
+ * and {@link triggerType} are populated.
366
+ */
367
+ isTrigger?: boolean;
368
+ /**
369
+ * Activation price (USD) for trigger orders. Reads as `triggerPx` from
370
+ * Hyperliquid's `frontendOpenOrders` response. Undefined for non-trigger
371
+ * orders.
372
+ */
373
+ triggerPx?: number;
374
+ /**
375
+ * Discriminator for trigger orders:
376
+ * - `"tp"` — Take Profit Market / Take Profit Limit
377
+ * - `"sl"` — Stop Market / Stop Limit
378
+ * Undefined when {@link isTrigger} is `false` / unknown.
379
+ */
380
+ triggerType?: "tp" | "sl";
381
+ /**
382
+ * Human-readable trigger condition as supplied by the venue, e.g.
383
+ * "Price above 81470" / "Price below 73761". Mostly useful for tooltips.
384
+ */
385
+ triggerCondition?: string;
263
386
  }
264
387
  /**
265
388
  * User trade history
@@ -313,6 +436,58 @@ interface PlaceOrderParams {
313
436
  /** User address (required for authentication) */
314
437
  userAddress?: string;
315
438
  }
439
+ /**
440
+ * Enriched place-order callback payload.
441
+ *
442
+ * Carried by the {@link PlaceOrderFormScriptProps.onPlaceOrder} hook
443
+ * exit when the host app wants to bypass the SDK's internal
444
+ * {@link IPerpetualsClient.placeOrder} mutation and submit the order
445
+ * itself (typical for Hyperliquid direct-relay setups where the host
446
+ * holds the wallet keys).
447
+ *
448
+ * The form script pre-computes everything that requires venue-specific
449
+ * context (live mark price, `szDecimals`) so the host hook can stay a
450
+ * pure venue adapter:
451
+ *
452
+ * - `size` is in coin units, derived as `amount × leverage / refPrice`,
453
+ * so the hook only needs to apply the venue's rounding rules.
454
+ * - `refPrice` is the live mark price snapshot used for the size
455
+ * calculation; the hook reuses it as the basis for any slippage
456
+ * guard (e.g. Hyperliquid's `FrontendMarket` orders need a worst-
457
+ * case price within ~8% of the mark).
458
+ * - `szDecimals` mirrors the venue's per-asset display precision so
459
+ * the hook can format the size string without re-querying meta.
460
+ */
461
+ interface PlaceOrderRequest {
462
+ /** Trading pair symbol, e.g. "BTC-USDC". */
463
+ symbol: string;
464
+ /** Order direction: long (buy) or short (sell). */
465
+ side: OrderSide;
466
+ /** Order type: market or limit. */
467
+ orderType: OrderType;
468
+ /** Order amount in USDC margin (matches the form input). */
469
+ amount: number;
470
+ /** Limit order price (only set for limit orders). */
471
+ price?: number;
472
+ /** Leverage multiplier (defaults to 1x). */
473
+ leverage: number;
474
+ /** Reduce-only flag (for closing positions). */
475
+ reduceOnly?: boolean;
476
+ /** Take profit trigger price. */
477
+ takeProfitPrice?: number;
478
+ /** Stop loss trigger price. */
479
+ stopLossPrice?: number;
480
+ /** Optional client order ID for caller-side tracking. */
481
+ clientOrderId?: string;
482
+ /** User wallet address (always populated when the form gates on auth). */
483
+ userAddress: string;
484
+ /** Coin-unit position size, pre-computed as `amount × leverage / refPrice`. */
485
+ size: number;
486
+ /** Live mark price snapshot used for `size` (and any slippage math). */
487
+ refPrice: number;
488
+ /** Venue-published display precision for the asset's size field. */
489
+ szDecimals: number;
490
+ }
316
491
  /**
317
492
  * Cancel order parameters
318
493
  */
@@ -335,6 +510,67 @@ interface GetPositionsParams {
335
510
  /** Optional: filter by specific trading pair */
336
511
  symbol?: string;
337
512
  }
513
+ /**
514
+ * Per-asset leverage configuration for a user, independent of whether
515
+ * an open position exists.
516
+ *
517
+ * Hyperliquid stores leverage settings at the `(user, coin)` granularity
518
+ * server-side. After the user calls `updateLeverage`, the value
519
+ * persists even when no position is open, so the form can recall the
520
+ * latest configured leverage on every page load instead of falling back
521
+ * to a hardcoded default.
522
+ */
523
+ interface ActiveAssetLeverage {
524
+ /** Configured leverage multiplier (e.g. 20 for 20x). */
525
+ value: number;
526
+ /** Whether the position uses isolated or cross-margin. */
527
+ type: "isolated" | "cross";
528
+ }
529
+ /**
530
+ * Parameters for {@link IPerpetualsClient.getActiveAssetLeverage}.
531
+ */
532
+ interface GetActiveAssetLeverageParams {
533
+ /** User wallet address. */
534
+ userAddress: string;
535
+ /** Trading pair symbol (e.g. "BTC-USDC"). */
536
+ symbol: string;
537
+ }
538
+ /**
539
+ * Static, per-asset metadata that the venue publishes about a perp
540
+ * symbol. Independent of the user (no wallet involved) and rarely
541
+ * changes — listing additions / leverage caps update infrequently.
542
+ *
543
+ * Used by the Place Order form to:
544
+ * - format the token quantity badge with the correct number of decimal
545
+ * places (BTC → 5, ETH → 4, SOL → 2, DOGE → 0). Hyperliquid hands
546
+ * this out as `szDecimals` on `meta.universe[i]`; we surface it under
547
+ * the same name so SDK consumers don't need to translate.
548
+ * - read the venue's max leverage cap (40x for BTC, 25x for ETH, ...)
549
+ * when scaling the leverage modal.
550
+ *
551
+ * Implementations that don't expose this data may return `null`; the
552
+ * caller is expected to fall back to its own heuristics.
553
+ */
554
+ interface AssetMeta {
555
+ /**
556
+ * Number of decimal places the venue uses to express the **size**
557
+ * (token quantity, not USD notional) of this asset. A value of `5`
558
+ * means the smallest tradeable unit is `1e-5` of the token.
559
+ *
560
+ * Mirrors Hyperliquid's `szDecimals` exactly. Other venues may store
561
+ * the same information as `stepSize = 10 ^ -szDecimals`.
562
+ */
563
+ szDecimals: number;
564
+ /** Maximum leverage the venue allows for this asset (e.g. 40 for BTC). */
565
+ maxLeverage?: number;
566
+ }
567
+ /**
568
+ * Parameters for {@link IPerpetualsClient.getAssetMeta}.
569
+ */
570
+ interface GetAssetMetaParams {
571
+ /** Trading pair symbol (e.g. "BTC-USDC"). */
572
+ symbol: string;
573
+ }
338
574
  /**
339
575
  * Get open orders parameters
340
576
  */
@@ -377,6 +613,12 @@ interface PlaceOrderResult {
377
613
  status: OrderStatus;
378
614
  /** Order creation timestamp (milliseconds) */
379
615
  timestamp: number;
616
+ /**
617
+ * Average fill price, only populated when the order filled
618
+ * synchronously (market orders typically). Undefined for resting
619
+ * limit orders.
620
+ */
621
+ avgPrice?: number;
380
622
  /** Raw response data (for debugging, optional) */
381
623
  raw?: any;
382
624
  }
@@ -405,7 +647,7 @@ interface GetPositionsResult {
405
647
  positions: Position[];
406
648
  /** Total account equity (optional) */
407
649
  totalEquity?: number;
408
- /** Available balance (optional) */
650
+ /** See {@link Account.availableBalance} — the venue's "withdrawable" figure. */
409
651
  availableBalance?: number;
410
652
  /** Total unrealized PnL (optional) */
411
653
  totalUnrealizedPnl?: number;
@@ -538,6 +780,32 @@ interface IPerpetualsClient {
538
780
  * @throws {Error} Network error or API error
539
781
  */
540
782
  getTrades(params?: GetTradesParams): Promise<GetTradesResult>;
783
+ /**
784
+ * Read the user's per-asset leverage configuration even when no
785
+ * position is open. Used by the Place Order form to seed the leverage
786
+ * slider from the venue's source of truth instead of a local default.
787
+ *
788
+ * Implementations that don't expose this data may return `null`; the
789
+ * caller is expected to fall back to its own default (e.g. 20x).
790
+ *
791
+ * @param params User address + trading pair symbol.
792
+ * @returns The configured leverage, or `null` when unavailable.
793
+ * @throws {Error} Network error or API error
794
+ */
795
+ getActiveAssetLeverage(params: GetActiveAssetLeverageParams): Promise<ActiveAssetLeverage | null>;
796
+ /**
797
+ * Read the venue's static metadata for a perp symbol — `szDecimals`
798
+ * (token-size precision) and `maxLeverage`. Used by the Place Order
799
+ * form to format the converted token quantity with the right number
800
+ * of decimal places per asset. Hyperliquid implements this against
801
+ * the `meta` info endpoint; venues without an equivalent may return
802
+ * `null`.
803
+ *
804
+ * @param params Trading pair symbol.
805
+ * @returns The asset's metadata, or `null` when unavailable.
806
+ * @throws {Error} Network error or API error
807
+ */
808
+ getAssetMeta(params: GetAssetMetaParams): Promise<AssetMeta | null>;
541
809
  /**
542
810
  * Connect to WebSocket server
543
811
  * @throws {Error} Connection failed
@@ -576,6 +844,26 @@ interface IPerpetualsClient {
576
844
  * @returns Subscription ID (for unsubscribing)
577
845
  */
578
846
  subscribeUserData(type: "orders" | "positions" | "fills", userAddress: string, callback: (data: any) => void): string;
847
+ /**
848
+ * Subscribe to the user's full account state via a single push
849
+ * channel (Hyperliquid `webData2`, Drift `userAccount`, etc.).
850
+ *
851
+ * Replaces a fan of REST polls — `clearinghouseState`,
852
+ * `spotClearinghouseState`, `openOrders` — with one subscription that
853
+ * the venue pushes incrementally on each fill / margin movement.
854
+ *
855
+ * Optional because not every venue exposes a unified user channel;
856
+ * implementations that don't may omit it. Consumers that depend on
857
+ * it (e.g. `useAccountStateSubscription`) must guard with
858
+ * `typeof client.subscribeAccountState === "function"`.
859
+ *
860
+ * @param userAddress Wallet address whose state to track.
861
+ * @param callback Receives the canonical {@link AccountState} on every
862
+ * push. The SDK transforms the venue's raw payload before invoking
863
+ * the callback so consumers only see SDK types.
864
+ * @returns Subscription ID for {@link unsubscribe}.
865
+ */
866
+ subscribeAccountState?(userAddress: string, callback: (state: AccountState) => void): string;
579
867
  /**
580
868
  * Unsubscribe
581
869
  * @param subscriptionId Subscription ID
@@ -650,6 +938,23 @@ declare class HyperliquidPerpetualsClient implements IPerpetualsClient {
650
938
  * on {@link LiberFiPerpetualsClient}.
651
939
  */
652
940
  private wsRefCount;
941
+ /**
942
+ * Process-local memoisation of the venue's asset universe (the
943
+ * `meta` info endpoint). Hyperliquid's universe rarely changes (new
944
+ * listings, leverage cap adjustments) so the SDK caches the parsed
945
+ * map for {@link ASSET_META_TTL_MS} per client instance to spare
946
+ * downstream consumers a network round-trip on every render.
947
+ *
948
+ * The TanStack Query layer adds another tier of caching above this
949
+ * (per `staleTime`), but caching here too keeps the contract correct
950
+ * for non-React callers that talk to the client directly.
951
+ */
952
+ private assetMetaCache;
953
+ /**
954
+ * In-flight `getAssetMeta` request, deduped so concurrent callers
955
+ * collapse onto a single network request when the cache misses.
956
+ */
957
+ private assetMetaPending;
653
958
  /**
654
959
  * 构造 Hyperliquid 客户端
655
960
  *
@@ -771,6 +1076,35 @@ declare class HyperliquidPerpetualsClient implements IPerpetualsClient {
771
1076
  * @throws {Error} 缺少必需参数
772
1077
  */
773
1078
  getPositions(params?: GetPositionsParams): Promise<GetPositionsResult>;
1079
+ /**
1080
+ * Read the user's per-asset leverage configuration via the
1081
+ * `activeAssetData` info endpoint. This works whether or not an open
1082
+ * position exists for the asset, so the UI can render the latest
1083
+ * configured leverage on a fresh page load.
1084
+ *
1085
+ * @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-active-asset-data
1086
+ */
1087
+ getActiveAssetLeverage(params: GetActiveAssetLeverageParams): Promise<ActiveAssetLeverage | null>;
1088
+ /**
1089
+ * Fetch the venue's static metadata for `params.symbol` (currently
1090
+ * `szDecimals` and `maxLeverage`). Backed by Hyperliquid's `meta`
1091
+ * info endpoint, with an in-memory cache keyed on this client
1092
+ * instance and TTL'd at {@link ASSET_META_TTL_MS}.
1093
+ *
1094
+ * Returns `null` when the symbol isn't part of the universe so
1095
+ * downstream consumers can branch on absence without try/catching
1096
+ * lookups for unsupported coins.
1097
+ *
1098
+ * @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata
1099
+ */
1100
+ getAssetMeta(params: GetAssetMetaParams): Promise<AssetMeta | null>;
1101
+ /**
1102
+ * Internal: ensure {@link assetMetaCache} is populated and fresh,
1103
+ * then return the resolved coin → {@link AssetMeta} map. Concurrent
1104
+ * cache misses share a single in-flight request via
1105
+ * {@link assetMetaPending}.
1106
+ */
1107
+ private fetchAssetUniverse;
774
1108
  /**
775
1109
  * 获取用户挂单信息
776
1110
  *
@@ -844,6 +1178,29 @@ declare class HyperliquidPerpetualsClient implements IPerpetualsClient {
844
1178
  * @returns Subscription ID (for unsubscribing)
845
1179
  */
846
1180
  subscribeUserData(type: "orders" | "positions" | "fills", userAddress: string, callback: (data: any) => void): string;
1181
+ /**
1182
+ * Subscribe to the user's full account state via Hyperliquid's
1183
+ * `webData2` channel. Each push carries a complete snapshot of:
1184
+ *
1185
+ * - `clearinghouseState` — perp positions, margin summaries, and the
1186
+ * `withdrawable` figure used as "Available Margin".
1187
+ * - `spotState` — spot wallet balances (USDC, USOL, etc.).
1188
+ * - `openOrders` — the user's resting limit orders.
1189
+ *
1190
+ * Replaces three separate REST polls (`clearinghouseState`,
1191
+ * `spotClearinghouseState`, `openOrders`) with a single push channel.
1192
+ * Hooks like `useAccountStateSubscription` use this to seed React
1193
+ * Query caches in real time so consumers see fills / margin moves
1194
+ * the moment Hyperliquid pushes them.
1195
+ *
1196
+ * @param userAddress Wallet address whose state to track.
1197
+ * @param callback Receives the canonical {@link AccountState} on
1198
+ * every push (raw payload available on `state.raw`).
1199
+ * @returns Subscription ID for {@link unsubscribe}.
1200
+ *
1201
+ * @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions#webdata2
1202
+ */
1203
+ subscribeAccountState(userAddress: string, callback: (state: AccountState) => void): string;
847
1204
  /**
848
1205
  * Unsubscribe from a data stream
849
1206
  *
@@ -1197,6 +1554,27 @@ declare class LiberFiPerpetualsClient implements IPerpetualsClient {
1197
1554
  getPositions(params?: GetPositionsParams): Promise<GetPositionsResult>;
1198
1555
  getOpenOrders(params?: GetOpenOrdersParams): Promise<GetOpenOrdersResult>;
1199
1556
  getTrades(params?: GetTradesParams): Promise<GetTradesResult>;
1557
+ /**
1558
+ * The LiberFi backend does not yet expose an `activeAssetData`
1559
+ * equivalent. Returning `null` lets the form fall back to its own
1560
+ * default leverage without raising — the perpetuals-server can grow
1561
+ * this endpoint later and we'll plug it in here.
1562
+ */
1563
+ getActiveAssetLeverage(_params: GetActiveAssetLeverageParams): Promise<ActiveAssetLeverage | null>;
1564
+ /**
1565
+ * The LiberFi backend doesn't currently surface per-asset
1566
+ * `szDecimals` / `maxLeverage` over a dedicated endpoint. We could
1567
+ * derive `szDecimals` from {@link getSupportedCoins}'s `stepSize`
1568
+ * once perpetuals-server starts populating it (`szDecimals =
1569
+ * -log10(stepSize)`), but until then the form falls back to its
1570
+ * adaptive heuristic when this returns `null`.
1571
+ *
1572
+ * TODO(perpetuals-server): expose `GET /v1/markets/:symbol/meta`
1573
+ * (or extend the existing `/v1/coins` payload with `szDecimals` +
1574
+ * `maxLeverage`) so this can resolve without a side trip to the
1575
+ * upstream venue.
1576
+ */
1577
+ getAssetMeta(_params: GetAssetMetaParams): Promise<AssetMeta | null>;
1200
1578
  placeOrder(params: PlaceOrderParams): Promise<PlaceOrderResult>;
1201
1579
  cancelOrder(params: CancelOrderParams): Promise<CancelOrderResult>;
1202
1580
  connectWebSocket(): Promise<void>;
@@ -1634,6 +2012,72 @@ declare function tradesQueryKey(params: Omit<UseTradesQueryParams, "enabled">):
1634
2012
  declare function fetchTrades(client: IPerpetualsClient, params: GetTradesParams): Promise<GetTradesResult>;
1635
2013
  declare function useTradesQuery(params: UseTradesQueryParams, options?: Omit<UseQueryOptions<GetTradesResult, Error, GetTradesResult, string[]>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<GetTradesResult, Error>;
1636
2014
 
2015
+ interface UseActiveAssetLeverageQueryParams {
2016
+ /** User wallet address. Query stays disabled until this is set. */
2017
+ userAddress?: string;
2018
+ /** Trading pair symbol (e.g. "BTC-USDC"). */
2019
+ symbol: string;
2020
+ /** Optional override; useful for tests. */
2021
+ enabled?: boolean;
2022
+ }
2023
+ /**
2024
+ * React Query key for the user's per-asset leverage configuration.
2025
+ *
2026
+ * Accepts an undefined `userAddress` (e.g. before the wallet connects)
2027
+ * because consumers often want a stable key shape to feed
2028
+ * `invalidateQueries` after the address resolves. The fallback empty
2029
+ * string just makes the key deterministic; the query itself stays
2030
+ * disabled until both fields are populated.
2031
+ */
2032
+ declare function activeAssetLeverageQueryKey(params: {
2033
+ userAddress?: GetActiveAssetLeverageParams["userAddress"];
2034
+ symbol?: GetActiveAssetLeverageParams["symbol"];
2035
+ }): string[];
2036
+ declare function fetchActiveAssetLeverage(client: IPerpetualsClient, params: GetActiveAssetLeverageParams): Promise<ActiveAssetLeverage | null>;
2037
+ /**
2038
+ * Read the user's configured leverage for `symbol` from the venue,
2039
+ * independent of whether an open position exists. Backed by Hyperliquid's
2040
+ * `activeAssetData` info endpoint when the active provider is
2041
+ * Hyperliquid; the LiberFi adapter currently returns `null` (the form
2042
+ * will fall back to its default).
2043
+ *
2044
+ * The returned data updates every 30s while the form is mounted, and
2045
+ * the consumer is expected to invalidate the query after a successful
2046
+ * `updateLeverage` so the UI reflects the new value immediately.
2047
+ */
2048
+ declare function useActiveAssetLeverageQuery(params: UseActiveAssetLeverageQueryParams, options?: Omit<UseQueryOptions<ActiveAssetLeverage | null, Error, ActiveAssetLeverage | null, string[]>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<ActiveAssetLeverage | null, Error>;
2049
+
2050
+ interface UseAssetMetaQueryParams {
2051
+ /** Trading pair symbol (e.g. "BTC-USDC"). */
2052
+ symbol?: string;
2053
+ /** Optional override; useful for tests. */
2054
+ enabled?: boolean;
2055
+ }
2056
+ /**
2057
+ * React Query key for the per-asset metadata query.
2058
+ *
2059
+ * Tolerates an undefined `symbol` so consumers can build a stable key
2060
+ * shape before the symbol resolves; the query itself stays disabled
2061
+ * until both `enabled` and `symbol` are truthy.
2062
+ */
2063
+ declare function assetMetaQueryKey(params: {
2064
+ symbol?: GetAssetMetaParams["symbol"];
2065
+ }): string[];
2066
+ declare function fetchAssetMeta(client: IPerpetualsClient, params: GetAssetMetaParams): Promise<AssetMeta | null>;
2067
+ /**
2068
+ * Read the venue's static metadata (`szDecimals`, `maxLeverage`) for
2069
+ * `symbol`. Backed by Hyperliquid's `meta` info endpoint when the
2070
+ * active provider is Hyperliquid; the LiberFi adapter currently
2071
+ * returns `null` (the form falls back to an adaptive precision rule).
2072
+ *
2073
+ * The data is process-stable for minutes at a time (Hyperliquid only
2074
+ * updates the universe on listing additions / leverage cap changes),
2075
+ * so we set a generous `staleTime` of 60 seconds. Consumers don't
2076
+ * need to invalidate this on user actions — the data is keyed on
2077
+ * symbol alone.
2078
+ */
2079
+ declare function useAssetMetaQuery(params: UseAssetMetaQueryParams, options?: Omit<UseQueryOptions<AssetMeta | null, Error, AssetMeta | null, string[]>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<AssetMeta | null, Error>;
2080
+
1637
2081
  type UseCreateOrderMutationParams = PlaceOrderParams;
1638
2082
  declare function createOrder(client: IPerpetualsClient, params: UseCreateOrderMutationParams): Promise<PlaceOrderResult>;
1639
2083
  declare function useCreateOrderMutation(options?: Omit<UseMutationOptions<PlaceOrderResult, Error, UseCreateOrderMutationParams>, "mutationFn">): _tanstack_react_query.UseMutationResult<PlaceOrderResult, Error, PlaceOrderParams, unknown>;
@@ -1698,6 +2142,96 @@ interface UseUserDataSubscriptionResult<T> {
1698
2142
  }
1699
2143
  declare function useUserDataSubscription<T = UserDataType extends "orders" ? Order : UserDataType extends "positions" ? Position : TradeHistory>(params: UseUserDataSubscriptionParams): UseUserDataSubscriptionResult<T>;
1700
2144
 
2145
+ interface UseAccountStateSubscriptionParams {
2146
+ /**
2147
+ * Wallet address whose state should be tracked. When undefined or
2148
+ * empty the subscription is disabled, so it's safe to mount this
2149
+ * hook before authentication completes.
2150
+ */
2151
+ userAddress?: string;
2152
+ /** Disable the subscription entirely (e.g. for SSR / paused tabs). */
2153
+ enabled?: boolean;
2154
+ }
2155
+ interface UseAccountStateSubscriptionResult {
2156
+ /** Latest account state pushed by the venue. */
2157
+ data: AccountState | null;
2158
+ /** WebSocket connection status (true after the first successful connect). */
2159
+ isConnected: boolean;
2160
+ /** Last connection / subscription error, or null on success. */
2161
+ error: Error | null;
2162
+ }
2163
+ /**
2164
+ * Subscribe to the venue's unified user-state push channel
2165
+ * (Hyperliquid's `webData2`) and fan the snapshots out across the
2166
+ * SDK's React Query caches.
2167
+ *
2168
+ * Why this hook exists:
2169
+ *
2170
+ * The naive way to keep `usePositionsQuery`, `useOrdersQuery`, and a
2171
+ * spot-balance reader live is to crank their `refetchInterval` down to
2172
+ * a few seconds, hammering Hyperliquid's `clearinghouseState` /
2173
+ * `spotClearinghouseState` / `openOrders` endpoints. That trades
2174
+ * bandwidth for latency and still misses fills between polls. Axiom
2175
+ * uses a single `webData2` subscription instead, and so should we.
2176
+ *
2177
+ * On every push this hook writes the parsed snapshot to:
2178
+ * - {@link accountStateQueryKey} — the canonical cache slot read by
2179
+ * {@link useAccountStateQuery} (consumed by wallet buttons,
2180
+ * deposit modals, etc.).
2181
+ * - {@link positionsQueryKey} — keeps `usePositionsQuery` in sync so
2182
+ * the place-order form's Available Margin / Current Position
2183
+ * reflects the venue without a second REST round-trip.
2184
+ * - {@link ordersQueryKey} — keeps `useOrdersQuery` in sync for the
2185
+ * open-orders table.
2186
+ *
2187
+ * Mount this hook **once** at the top of the perpetuals shell (a
2188
+ * shared layout, an app-wide provider, …). Children read through
2189
+ * existing hooks; nothing else needs to know that the data arrives
2190
+ * via WebSocket.
2191
+ *
2192
+ * Falls back gracefully when the venue does not support a unified
2193
+ * channel: if `client.subscribeAccountState` is missing the hook is a
2194
+ * no-op, and the existing REST polling continues to drive the caches.
2195
+ */
2196
+ declare function useAccountStateSubscription(params: UseAccountStateSubscriptionParams): UseAccountStateSubscriptionResult;
2197
+
2198
+ interface UseAccountStateQueryParams {
2199
+ /** User wallet address. The query is disabled when missing. */
2200
+ userAddress?: string;
2201
+ enabled?: boolean;
2202
+ }
2203
+ /**
2204
+ * Stable React Query key for the user's full account state. Shared
2205
+ * between {@link useAccountStateQuery} (read) and
2206
+ * `useAccountStateSubscription` (write) so a webData2 push and a
2207
+ * consumer reader land on the same cache slot.
2208
+ */
2209
+ declare function accountStateQueryKey(params: Pick<UseAccountStateQueryParams, "userAddress">): string[];
2210
+ /**
2211
+ * Read the user's full account state (positions, open orders, spot
2212
+ * balances, available margin) from the React Query cache.
2213
+ *
2214
+ * This hook does NOT itself fetch data over HTTP — the cache is fed
2215
+ * exclusively by `useAccountStateSubscription`, which subscribes to
2216
+ * Hyperliquid's `webData2` push channel and writes every snapshot
2217
+ * into the same cache slot. Mount the subscription somewhere high in
2218
+ * the tree (e.g. an app-shell layout) and this hook becomes a cheap
2219
+ * subscriber that re-renders whenever a fresh push lands.
2220
+ *
2221
+ * Returning `null` means no push has been received yet — wait for the
2222
+ * subscription to flush its initial snapshot rather than firing a
2223
+ * REST fallback, since `webData2` always primes the stream on
2224
+ * connect.
2225
+ *
2226
+ * @example
2227
+ * function WalletButton() {
2228
+ * const { address } = useWallet();
2229
+ * const { data: account } = useAccountStateQuery({ userAddress: address });
2230
+ * return <span>{account?.availableBalance.toFixed(2)} USDC</span>;
2231
+ * }
2232
+ */
2233
+ declare function useAccountStateQuery(params: UseAccountStateQueryParams, options?: Omit<UseQueryOptions<AccountState | null, Error, AccountState | null, string[]>, "queryKey" | "queryFn">): _tanstack_react_query.UseQueryResult<AccountState | null, Error>;
2234
+
1701
2235
  /**
1702
2236
  * Hook to access the deposit client from `PerpetualsProvider`.
1703
2237
  *
@@ -2223,13 +2757,42 @@ type PlaceOrderFormWidgetProps = {
2223
2757
  * control.
2224
2758
  */
2225
2759
  onAddFunds?: () => void;
2760
+ /**
2761
+ * Optional callback fired when the user confirms a new leverage value
2762
+ * in the leverage modal. The host app should sign + relay the
2763
+ * `updateLeverage` action to Hyperliquid and surface a toast. While
2764
+ * the returned promise is pending the modal's button shows a spinner;
2765
+ * if it rejects, the modal stays open so the user can retry.
2766
+ */
2767
+ onUpdateLeverage?: (leverage: number) => Promise<void>;
2768
+ /**
2769
+ * Optional callback that takes over order submission. When provided,
2770
+ * the widget bypasses its internal `client.placeOrder` mutation and
2771
+ * forwards the enriched {@link PlaceOrderRequest} (live mark price +
2772
+ * coin-unit size + per-asset `szDecimals`) so the host can sign and
2773
+ * relay the action against the venue directly. While the returned
2774
+ * promise is pending, the submit button shows a spinner; on
2775
+ * rejection, `onError` fires.
2776
+ *
2777
+ * Mirrors the `onUpdateLeverage` pattern. When omitted, the SDK
2778
+ * falls back to `IPerpetualsClient.placeOrder` (used by the LiberFi
2779
+ * adapter, which holds the signing keys server-side).
2780
+ */
2781
+ onPlaceOrder?: (request: PlaceOrderRequest) => Promise<PlaceOrderResult>;
2226
2782
  className?: string;
2227
2783
  };
2228
- declare function PlaceOrderFormWidget({ symbol, userAddress, maxLeverage, onSuccess, onError, onAddFunds, className, }: PlaceOrderFormWidgetProps): react_jsx_runtime.JSX.Element;
2784
+ declare function PlaceOrderFormWidget({ symbol, userAddress, maxLeverage, onSuccess, onError, onAddFunds, onUpdateLeverage, onPlaceOrder, className, }: PlaceOrderFormWidgetProps): react_jsx_runtime.JSX.Element;
2229
2785
 
2230
2786
  type PlaceOrderFormData = {
2231
2787
  price?: number;
2232
- amount: number;
2788
+ /**
2789
+ * USDC margin the user is committing to this trade. Optional so the
2790
+ * form can render an empty input on first mount (placeholder
2791
+ * `0.0 USDC`) instead of pre-filling `0`. The notional position size
2792
+ * a venue cares about is derived as `amount * leverage`; the token
2793
+ * quantity is `(amount * leverage) / currentPrice`.
2794
+ */
2795
+ amount?: number;
2233
2796
  leverage: number;
2234
2797
  takeProfitPrice?: number;
2235
2798
  takeProfitPercent?: number;
@@ -2242,6 +2805,32 @@ type UsePlaceOrderFormScriptParams = {
2242
2805
  maxLeverage?: number;
2243
2806
  onSuccess?: () => void;
2244
2807
  onError?: (error: Error) => void;
2808
+ /**
2809
+ * Optional callback fired when the user confirms a new leverage value
2810
+ * in the leverage modal. The host app is expected to sign + relay the
2811
+ * `updateLeverage` action to Hyperliquid (and surface a toast). The
2812
+ * widget tracks the returned promise to drive the modal's button
2813
+ * loading state — when the promise rejects, the modal stays open so
2814
+ * the user can retry.
2815
+ *
2816
+ * When omitted, the modal falls back to a local-only update: the
2817
+ * leverage slider commits to the form state without contacting the
2818
+ * exchange.
2819
+ */
2820
+ onUpdateLeverage?: (leverage: number) => Promise<void>;
2821
+ /**
2822
+ * Optional callback that takes over order submission. When provided,
2823
+ * the form bypasses the SDK's internal `client.placeOrder` mutation
2824
+ * and forwards the enriched {@link PlaceOrderRequest} (live mark
2825
+ * price + coin-unit size + per-asset `szDecimals`) so the host can
2826
+ * sign + relay the action against the venue directly.
2827
+ *
2828
+ * Mirrors the {@link onUpdateLeverage} pattern; when omitted, the
2829
+ * widget falls back to {@link useCreateOrderMutation} → the
2830
+ * configured `IPerpetualsClient.placeOrder` (used by the LiberFi
2831
+ * adapter, which holds the signing keys server-side).
2832
+ */
2833
+ onPlaceOrder?: (request: PlaceOrderRequest) => Promise<PlaceOrderResult>;
2245
2834
  };
2246
2835
  type UsePlaceOrderFormScriptResult = {
2247
2836
  form: ReturnType<typeof useForm<PlaceOrderFormData>>;
@@ -2257,16 +2846,64 @@ type UsePlaceOrderFormScriptResult = {
2257
2846
  liquidationPrice?: number;
2258
2847
  availableMargin: number;
2259
2848
  accountValue: number;
2260
- currentPosition?: number;
2849
+ /**
2850
+ * Position the user currently holds in the symbol shown by the form.
2851
+ * Shaped to match the Axiom layout — `Long 0.00045 BTC (1.19 USDC)` —
2852
+ * by exposing the venue-precision size, base symbol, and isolated
2853
+ * margin used. `undefined` when there is no position for the symbol.
2854
+ */
2855
+ currentPosition?: {
2856
+ side: OrderSide;
2857
+ /** Absolute quantity from the venue (preserves precision when available). */
2858
+ quantity: number;
2859
+ /** Raw absolute quantity string from the venue, e.g. `"0.00045"`. */
2860
+ quantityRaw?: string;
2861
+ /** Isolated margin used by this position, in USDC. */
2862
+ margin: number;
2863
+ /** Base asset symbol, e.g. `"BTC"` for `"BTC-USDC"`. */
2864
+ base: string;
2865
+ };
2261
2866
  maxLeverage: number;
2262
2867
  /**
2263
- * Leverage currently configured on Hyperliquid for the active symbol's
2264
- * position. `undefined` when the user has no open position for the
2265
- * symbol (and therefore no per-asset leverage to read).
2868
+ * Leverage currently configured on the venue for `symbol`, sourced
2869
+ * from the `activeAssetData` info endpoint. Defined whether or not
2870
+ * an open position exists; `undefined` only while the query is
2871
+ * loading or when the venue does not expose this data (e.g. the
2872
+ * LiberFi adapter today).
2266
2873
  */
2267
2874
  currentLeverage?: number;
2875
+ /**
2876
+ * `true` once the venue has returned a leverage value for `symbol`.
2877
+ * The UI uses this to render a skeleton in place of the form's
2878
+ * default until the real configuration arrives, avoiding a
2879
+ * `20 → real value` flash on refresh.
2880
+ */
2881
+ isLeverageReady: boolean;
2882
+ /**
2883
+ * `true` when the user has at least one resting order on the venue
2884
+ * for `symbol`. Surfaced to the leverage modal so it can warn
2885
+ * "open order(s) will be affected by leverage change" — Hyperliquid
2886
+ * recomputes margin on resting orders whenever the per-asset
2887
+ * leverage changes, so the user should know before confirming.
2888
+ *
2889
+ * Sourced from the same `webData2` snapshot that drives positions
2890
+ * and balances, so it stays in sync with the rest of the form
2891
+ * without an extra REST round-trip.
2892
+ */
2893
+ hasOpenOrdersForSymbol: boolean;
2894
+ /**
2895
+ * Number of decimal places the venue uses to express the size
2896
+ * (token quantity) for `symbol`. Sourced from the `meta` info
2897
+ * endpoint; `undefined` while the query is in flight or when the
2898
+ * venue does not expose it (e.g. the LiberFi adapter today). The UI
2899
+ * uses this to format the converted token quantity badge with
2900
+ * per-asset precision (BTC → 5, SOL → 2, DOGE → 0).
2901
+ */
2902
+ szDecimals?: number;
2903
+ /** Forwarded callback (see {@link UsePlaceOrderFormScriptParams.onUpdateLeverage}). */
2904
+ onUpdateLeverage?: (leverage: number) => Promise<void>;
2268
2905
  };
2269
- declare function usePlaceOrderFormScript({ symbol, userAddress, maxLeverage: maxLeverageProp, onSuccess, onError, }: UsePlaceOrderFormScriptParams): UsePlaceOrderFormScriptResult;
2906
+ declare function usePlaceOrderFormScript({ symbol, userAddress, maxLeverage: maxLeverageProp, onSuccess, onError, onUpdateLeverage, onPlaceOrder, }: UsePlaceOrderFormScriptParams): UsePlaceOrderFormScriptResult;
2270
2907
 
2271
2908
  type PlaceOrderFormUIProps = {
2272
2909
  methods: UseFormReturn<PlaceOrderFormData>;
@@ -2283,8 +2920,45 @@ type PlaceOrderFormUIProps = {
2283
2920
  liquidationPrice?: number;
2284
2921
  availableMargin: number;
2285
2922
  accountValue: number;
2286
- currentPosition?: number;
2923
+ /**
2924
+ * Position the user currently holds in the symbol shown by the form.
2925
+ * Shaped to match the Axiom layout — `Long 0.00045 BTC (1.19 USDC)`.
2926
+ * `undefined` when there is no open position for `symbol`, in which
2927
+ * case the row falls back to `--`.
2928
+ */
2929
+ currentPosition?: {
2930
+ side: "long" | "short";
2931
+ quantity: number;
2932
+ quantityRaw?: string;
2933
+ margin: number;
2934
+ base: string;
2935
+ };
2287
2936
  maxLeverage: number;
2937
+ /**
2938
+ * Whether the leverage value can be displayed. When `false` the
2939
+ * leverage button shows a skeleton instead of the form's default,
2940
+ * to avoid flashing `20x` before the venue's per-asset configuration
2941
+ * is loaded. Defaults to `true` for backwards compatibility.
2942
+ */
2943
+ isLeverageReady?: boolean;
2944
+ /**
2945
+ * Whether the user has at least one resting order on `symbol`.
2946
+ * Drives the leverage modal's "Open order(s) will be affected"
2947
+ * advisory — Hyperliquid recomputes resting-order margin when the
2948
+ * per-asset leverage changes, so the user should see this before
2949
+ * confirming. Purely informational; does NOT block the update.
2950
+ */
2951
+ hasOpenOrdersForSymbol?: boolean;
2952
+ /**
2953
+ * Number of decimal places the venue uses for the size of `symbol`
2954
+ * (e.g. BTC → 5, ETH → 4, SOL → 2, DOGE → 0). Sourced from
2955
+ * Hyperliquid's `meta` info endpoint via `useAssetMetaQuery`. The
2956
+ * UI uses this to format the converted token quantity badge with
2957
+ * per-asset precision. When omitted the form falls back to an
2958
+ * adaptive heuristic that keeps the badge readable across coins
2959
+ * with very different price magnitudes.
2960
+ */
2961
+ szDecimals?: number;
2288
2962
  /**
2289
2963
  * Optional callback fired when the user clicks the "Add More Funds"
2290
2964
  * button (typically wired by the host app to open a deposit dialog).
@@ -2292,8 +2966,17 @@ type PlaceOrderFormUIProps = {
2292
2966
  * don't support a deposit flow don't render a dead control.
2293
2967
  */
2294
2968
  onAddFunds?: () => void;
2969
+ /**
2970
+ * Optional callback fired when the user confirms a new leverage in
2971
+ * the leverage modal. The widget tracks the returned promise to
2972
+ * drive the modal's button loading state — when it rejects the
2973
+ * modal stays open so the caller can retry. When omitted, the
2974
+ * leverage value is committed to the form locally without contacting
2975
+ * the exchange.
2976
+ */
2977
+ onUpdateLeverage?: (leverage: number) => Promise<void>;
2295
2978
  };
2296
- declare function PlaceOrderFormUI({ methods, side, orderType, onSideChange, onOrderTypeChange, onSubmit, isSubmitting, symbol, currentPrice, estimatedFee, liquidationPrice, availableMargin, accountValue, currentPosition, maxLeverage: _maxLeverage, onAddFunds, }: PlaceOrderFormUIProps): react_jsx_runtime.JSX.Element;
2979
+ declare function PlaceOrderFormUI({ methods, side, orderType, onSideChange, onOrderTypeChange, onSubmit, isSubmitting, symbol, currentPrice, estimatedFee, liquidationPrice, availableMargin, accountValue, currentPosition, maxLeverage, isLeverageReady, hasOpenOrdersForSymbol, szDecimals, onAddFunds, onUpdateLeverage, }: PlaceOrderFormUIProps): react_jsx_runtime.JSX.Element;
2297
2980
 
2298
2981
  type PositionsWidgetProps = {
2299
2982
  userAddress?: string;
@@ -2302,17 +2985,47 @@ type PositionsWidgetProps = {
2302
2985
  onCloseError?: (error: Error) => void;
2303
2986
  className?: string;
2304
2987
  };
2988
+ /**
2989
+ * Positions table widget. Owns no business logic — wires the
2990
+ * `usePositionsScript` data layer (sort + close-mutation) to the
2991
+ * presentational `PositionsUI`. The host page just provides the
2992
+ * connected wallet address and (optionally) a symbol filter; the
2993
+ * widget handles everything else (sort state, realtime updates,
2994
+ * close-position toasts in the consumer's mutation lifecycle).
2995
+ */
2305
2996
  declare function PositionsWidget({ userAddress, symbol, onCloseSuccess, onCloseError, className, }: PositionsWidgetProps): react_jsx_runtime.JSX.Element;
2306
2997
 
2998
+ /**
2999
+ * Stable identifier for a sortable column. Mirrors Axiom's set: 7 of the
3000
+ * 9 columns are sortable; `tpsl` and `close` are interaction-only.
3001
+ *
3002
+ * Kept as a discriminated string union (rather than an enum) so it
3003
+ * survives a tsup build to a stable runtime string — consumers that
3004
+ * persist the active sort key to local-storage / URL params are
3005
+ * insulated from enum-numbering churn.
3006
+ */
3007
+ type PositionSortKey = "asset" | "position" | "value" | "entry" | "mark" | "liq" | "marginPnl";
3008
+ type SortDirection = "asc" | "desc";
2307
3009
  type PositionsUIProps = {
3010
+ /** Already-sorted positions. The script layer owns sort state. */
2308
3011
  positions: Position[];
3012
+ /** Currently active sort column, or `null` when no sort applied. */
3013
+ sortKey: PositionSortKey | null;
3014
+ sortDir: SortDirection;
3015
+ onSort: (key: PositionSortKey) => void;
2309
3016
  onClosePosition: (position: Position) => void;
2310
3017
  isClosing: boolean;
3018
+ /** Optional className for the outer container. */
3019
+ className?: string;
2311
3020
  };
2312
- declare function PositionsUI({ positions, onClosePosition, isClosing, }: PositionsUIProps): react_jsx_runtime.JSX.Element;
3021
+ declare function PositionsUI({ positions, sortKey, sortDir, onSort, onClosePosition, isClosing, className, }: PositionsUIProps): react_jsx_runtime.JSX.Element;
2313
3022
  /** Loading skeleton for positions panel */
2314
3023
  declare function PositionsSkeleton(): react_jsx_runtime.JSX.Element;
2315
- /** Empty state when there are no open positions */
3024
+ /**
3025
+ * Standalone empty-state component. The main `PositionsUI` renders its
3026
+ * own empty layout (header + centred message) so this export exists for
3027
+ * consumers that wire their own empty state outside the widget.
3028
+ */
2316
3029
  declare function PositionsEmpty(): react_jsx_runtime.JSX.Element;
2317
3030
 
2318
3031
  type UsePositionsScriptParams = {
@@ -2322,12 +3035,30 @@ type UsePositionsScriptParams = {
2322
3035
  onCloseError?: (error: Error) => void;
2323
3036
  };
2324
3037
  type UsePositionsScriptResult = {
3038
+ /** Positions already sorted by the active `sortKey` / `sortDir`. */
2325
3039
  positions: Position[];
2326
3040
  isLoading: boolean;
2327
3041
  error: Error | null;
3042
+ /** Active sort column (`null` only when the consumer overrides it). */
3043
+ sortKey: PositionSortKey | null;
3044
+ sortDir: SortDirection;
3045
+ /** Toggle the sort column / direction. Mirrors Axiom's 2-state cycle:
3046
+ * first click on a new column → asc, subsequent clicks toggle asc ↔
3047
+ * desc. There is no "no-sort" state. */
3048
+ onSort: (key: PositionSortKey) => void;
2328
3049
  handleClosePosition: (position: Position) => Promise<void>;
2329
3050
  isClosing: boolean;
2330
3051
  };
3052
+ /**
3053
+ * Container hook for the positions table. Responsibilities:
3054
+ * - read positions via `usePositionsQuery` (which the consumer's
3055
+ * `useAccountStateSubscription` keeps live via webData2 cache
3056
+ * write-through, so we do **not** subscribe to `userEvents` here —
3057
+ * doing so would clobber the TP/SL + mark-price enrichment that
3058
+ * the client adds on the webData2 path).
3059
+ * - own sort state (default `marginPnl ↓`, mirroring Axiom).
3060
+ * - expose a `handleClosePosition` shim over `useCreateOrderMutation`.
3061
+ */
2331
3062
  declare function usePositionsScript({ userAddress, symbol, onCloseSuccess, onCloseError, }: UsePositionsScriptParams): UsePositionsScriptResult;
2332
3063
 
2333
3064
  type OpenOrdersWidgetProps = {
@@ -2643,4 +3374,4 @@ interface HyperliquidInitWidgetProps extends Pick<UseHyperliquidSetupOptions, "a
2643
3374
  }
2644
3375
  declare function HyperliquidInitWidget({ adapter, userAddress, steps, autoLoad, onComplete, onError, onDismiss, className, }: HyperliquidInitWidgetProps): react_jsx_runtime.JSX.Element;
2645
3376
 
2646
- export { type Account, type ApproveBuilderFeeParams, type CancelOrderParams, type CancelOrderResult, type Coin, CoinInfoNotFoundUI, CoinInfoSkeletonsUI, CoinInfoUI, type CoinInfoUIProps, CoinInfoWidget, type CoinInfoWidgetProps, DEFAULT_ORDER_BOOK_PRECISION_OPTIONS, type DepositBreakdown, DepositConfirmUI, type DepositConfirmUIProps, type DepositErrorInfo, type DepositEvent, DepositFlowWidget, type DepositFlowWidgetProps, DepositFormUI, type DepositFormUIProps, type DepositPhase, type DepositQuoteRequest, type DepositQuoteResponse, type DepositSource, type DepositState, type DepositStatus, type DepositStatusResponse, type DepositStatusTransition, DepositStatusUI, type DepositStatusUIProps, type DepositSubmitRequest, type DepositSubmitResponse, type ExecuteDepositInput, type GetOpenOrdersParams, type GetOpenOrdersResult, type GetPositionsParams, type GetPositionsResult, type GetTradesParams, type GetTradesResult, HL_USDC_DECIMALS, type HyperliquidAccountState, HyperliquidApiError, type HyperliquidClientConfig, type HyperliquidEnvironment, HyperliquidInitUI, type HyperliquidInitUIProps, HyperliquidInitWidget, type HyperliquidInitWidgetProps, HyperliquidPerpetualsClient, type HyperliquidSetupActionResult, type IHyperliquidSetupAdapter, type IPerpDepositClient, type IPerpetualsClient, type Kline, type KlineInterval, type KlineQueryOptions, LiberFiApiError, type LiberFiHttpMethod, type RequestOptions as LiberFiHttpRequestOptions, LiberFiHttpTransport, type LiberFiHttpTransportConfig, LiberFiPerpDepositClient, type LiberFiPerpDepositClientConfig, LiberFiPerpetualsClient, type LiberFiPerpetualsClientConfig, type MarketData, type MarketDataType, OpenOrdersEmpty, OpenOrdersSkeleton, OpenOrdersUI, type OpenOrdersUIProps, OpenOrdersWidget, type OpenOrdersWidgetProps, type Order, type OrderBook, type OrderBookAggregationOptions, type OrderBookLevel, OrderBookUI, type OrderBookUIProps, OrderBookWidget, type OrderBookWidgetProps, type OrderSide, type OrderStatus, type OrderType, PerpetualsContext, type PerpetualsContextValue, PerpetualsProvider, type PerpetualsProviderProps, type PlaceOrderFormData, PlaceOrderFormUI, type PlaceOrderFormUIProps, PlaceOrderFormWidget, type PlaceOrderFormWidgetProps, type PlaceOrderParams, type PlaceOrderResult, type Position, PositionsEmpty, PositionsSkeleton, PositionsUI, type PositionsUIProps, PositionsWidget, type PositionsWidgetProps, type PriceLevel, SearchCoinsUI, type SearchCoinsUIProps, SearchCoinsWidget, type SearchCoinsWidgetProps, type SetReferrerParams, type SetupAction, type SetupPhase, type SetupState, type SetupStep, type SetupStepId, type SignAndBroadcastSolanaTx, type SignTypedDataFn, type StepRecord, type StepStatus, type Symbol, TERMINAL_DEPOSIT_STATUSES, type TimeRange, type Trade, type TradeHistory, TradeHistoryEmpty, TradeHistorySkeleton, TradeHistoryUI, type TradeHistoryUIProps, TradeHistoryWidget, type TradeHistoryWidgetProps, type TradeSide, TradesUI, type TradesUIProps, TradesWidget, type TradesWidgetProps, type TradingProvider, type UpdateLeverageParams, type UseCancelOrderMutationParams, type UseCandlesSubscriptionParams, type UseCandlesSubscriptionResult, type UseCoinInfoReturnType, type UseCreateOrderMutationParams, type UseHyperliquidSetupOptions, type UseHyperliquidSetupResult, type UseKlinesQueryParams, type UseMarketDataSubscriptionParams, type UseMarketDataSubscriptionResult, type UseMarketQueryParams, type UseMarketsQueryParams, type UseOpenOrdersScriptParams, type UseOpenOrdersScriptResult, type UseOrderBookQueryParams, type UseOrderBookScriptParams, type UseOrderBookScriptResult, type UseOrdersQueryParams, type UsePerpDepositExecuteResult, type UsePerpDepositQuoteOptions, type UsePerpDepositStatusOptions, type UsePlaceOrderFormScriptParams, type UsePlaceOrderFormScriptResult, type UsePositionsQueryParams, type UsePositionsScriptParams, type UsePositionsScriptResult, type UseRecentTradesQueryParams, type UseSearchCoinsScriptParams, type UseSearchCoinsScriptResult, type UseTradeHistoryScriptParams, type UseTradeHistoryScriptResult, type UseTradesQueryParams, type UseTradesScriptParams, type UseTradesScriptResult, type UseUserDataSubscriptionParams, type UseUserDataSubscriptionResult, type UserDataType, aggregationFromStep, cancelOrder, classifyStep, coinsQueryKey, createOrder, currentBreakdown as currentDepositBreakdown, currentStatus as currentDepositStatus, fetchCoins, fetchKlines, fetchMarket, fetchMarkets, fetchOrderBook, fetchOrders, fetchPerpDepositQuote, fetchPerpDepositStatus, fetchPositions, fetchRecentTrades, fetchTrades, hlUsdcRawToUsdc, initialDepositState, initialSetupState, isPolling as isDepositPolling, isTerminal as isDepositTerminal, isTerminalLifecycle as isTerminalDepositLifecycle, klinesQueryKey, lamportsToSol, marketQueryKey, marketsQueryKey, microUsdcToUsdc, nextRunnableStep, orderBookQueryKey, ordersQueryKey, perpDepositQuoteQueryKey, perpDepositStatusQueryKey, positionsQueryKey, recentTradesQueryKey, reduceDepositState, reduceSetupState, secondsUntil, shortAddress, solToLamports, tradesQueryKey, useCancelOrderMutation, useCandlesSubscription, useCoinInfo, useCoinsQuery, useCreateOrderMutation, useHyperliquidSetup, useKlinesQuery, useMarketDataSubscription, useMarketQuery, useMarketsQuery, useOpenOrdersScript, useOrderBookQuery, useOrderBookScript, useOrdersQuery, usePerpDepositClient, usePerpDepositClientMaybe, usePerpDepositExecute, usePerpDepositQuote, usePerpDepositStatus, usePerpetualsClient, usePlaceOrderFormScript, usePositionsQuery, usePositionsScript, useRecentTradesQuery, useSearchCoinsScript, useTradeHistoryScript, useTradesQuery, useTradesScript, useUserDataSubscription, _default as version };
3377
+ export { type Account, type AccountState, type ActiveAssetLeverage, type ApproveBuilderFeeParams, type AssetMeta, type CancelOrderParams, type CancelOrderResult, type Coin, CoinInfoNotFoundUI, CoinInfoSkeletonsUI, CoinInfoUI, type CoinInfoUIProps, CoinInfoWidget, type CoinInfoWidgetProps, DEFAULT_ORDER_BOOK_PRECISION_OPTIONS, type DepositBreakdown, DepositConfirmUI, type DepositConfirmUIProps, type DepositErrorInfo, type DepositEvent, DepositFlowWidget, type DepositFlowWidgetProps, DepositFormUI, type DepositFormUIProps, type DepositPhase, type DepositQuoteRequest, type DepositQuoteResponse, type DepositSource, type DepositState, type DepositStatus, type DepositStatusResponse, type DepositStatusTransition, DepositStatusUI, type DepositStatusUIProps, type DepositSubmitRequest, type DepositSubmitResponse, type ExecuteDepositInput, type GetActiveAssetLeverageParams, type GetAssetMetaParams, type GetOpenOrdersParams, type GetOpenOrdersResult, type GetPositionsParams, type GetPositionsResult, type GetTradesParams, type GetTradesResult, HL_USDC_DECIMALS, type HyperliquidAccountState, HyperliquidApiError, type HyperliquidClientConfig, type HyperliquidEnvironment, HyperliquidInitUI, type HyperliquidInitUIProps, HyperliquidInitWidget, type HyperliquidInitWidgetProps, HyperliquidPerpetualsClient, type HyperliquidSetupActionResult, type IHyperliquidSetupAdapter, type IPerpDepositClient, type IPerpetualsClient, type Kline, type KlineInterval, type KlineQueryOptions, LiberFiApiError, type LiberFiHttpMethod, type RequestOptions as LiberFiHttpRequestOptions, LiberFiHttpTransport, type LiberFiHttpTransportConfig, LiberFiPerpDepositClient, type LiberFiPerpDepositClientConfig, LiberFiPerpetualsClient, type LiberFiPerpetualsClientConfig, type MarketData, type MarketDataType, OpenOrdersEmpty, OpenOrdersSkeleton, OpenOrdersUI, type OpenOrdersUIProps, OpenOrdersWidget, type OpenOrdersWidgetProps, type Order, type OrderBook, type OrderBookAggregationOptions, type OrderBookLevel, OrderBookUI, type OrderBookUIProps, OrderBookWidget, type OrderBookWidgetProps, type OrderSide, type OrderStatus, type OrderType, PerpetualsContext, type PerpetualsContextValue, PerpetualsProvider, type PerpetualsProviderProps, type PlaceOrderFormData, PlaceOrderFormUI, type PlaceOrderFormUIProps, PlaceOrderFormWidget, type PlaceOrderFormWidgetProps, type PlaceOrderParams, type PlaceOrderRequest, type PlaceOrderResult, type Position, type PositionSortKey, PositionsEmpty, PositionsSkeleton, PositionsUI, type PositionsUIProps, PositionsWidget, type PositionsWidgetProps, type PriceLevel, SearchCoinsUI, type SearchCoinsUIProps, SearchCoinsWidget, type SearchCoinsWidgetProps, type SetReferrerParams, type SetupAction, type SetupPhase, type SetupState, type SetupStep, type SetupStepId, type SignAndBroadcastSolanaTx, type SignTypedDataFn, type SortDirection, type SpotBalance, type StepRecord, type StepStatus, type Symbol, TERMINAL_DEPOSIT_STATUSES, type TimeRange, type Trade, type TradeHistory, TradeHistoryEmpty, TradeHistorySkeleton, TradeHistoryUI, type TradeHistoryUIProps, TradeHistoryWidget, type TradeHistoryWidgetProps, type TradeSide, TradesUI, type TradesUIProps, TradesWidget, type TradesWidgetProps, type TradingProvider, type UpdateLeverageParams, type UseAccountStateQueryParams, type UseAccountStateSubscriptionParams, type UseAccountStateSubscriptionResult, type UseActiveAssetLeverageQueryParams, type UseAssetMetaQueryParams, type UseCancelOrderMutationParams, type UseCandlesSubscriptionParams, type UseCandlesSubscriptionResult, type UseCoinInfoReturnType, type UseCreateOrderMutationParams, type UseHyperliquidSetupOptions, type UseHyperliquidSetupResult, type UseKlinesQueryParams, type UseMarketDataSubscriptionParams, type UseMarketDataSubscriptionResult, type UseMarketQueryParams, type UseMarketsQueryParams, type UseOpenOrdersScriptParams, type UseOpenOrdersScriptResult, type UseOrderBookQueryParams, type UseOrderBookScriptParams, type UseOrderBookScriptResult, type UseOrdersQueryParams, type UsePerpDepositExecuteResult, type UsePerpDepositQuoteOptions, type UsePerpDepositStatusOptions, type UsePlaceOrderFormScriptParams, type UsePlaceOrderFormScriptResult, type UsePositionsQueryParams, type UsePositionsScriptParams, type UsePositionsScriptResult, type UseRecentTradesQueryParams, type UseSearchCoinsScriptParams, type UseSearchCoinsScriptResult, type UseTradeHistoryScriptParams, type UseTradeHistoryScriptResult, type UseTradesQueryParams, type UseTradesScriptParams, type UseTradesScriptResult, type UseUserDataSubscriptionParams, type UseUserDataSubscriptionResult, type UserDataType, accountStateQueryKey, activeAssetLeverageQueryKey, aggregationFromStep, assetMetaQueryKey, cancelOrder, classifyStep, coinsQueryKey, createOrder, currentBreakdown as currentDepositBreakdown, currentStatus as currentDepositStatus, fetchActiveAssetLeverage, fetchAssetMeta, fetchCoins, fetchKlines, fetchMarket, fetchMarkets, fetchOrderBook, fetchOrders, fetchPerpDepositQuote, fetchPerpDepositStatus, fetchPositions, fetchRecentTrades, fetchTrades, hlUsdcRawToUsdc, initialDepositState, initialSetupState, isPolling as isDepositPolling, isTerminal as isDepositTerminal, isTerminalLifecycle as isTerminalDepositLifecycle, klinesQueryKey, lamportsToSol, marketQueryKey, marketsQueryKey, microUsdcToUsdc, nextRunnableStep, orderBookQueryKey, ordersQueryKey, perpDepositQuoteQueryKey, perpDepositStatusQueryKey, positionsQueryKey, recentTradesQueryKey, reduceDepositState, reduceSetupState, secondsUntil, shortAddress, solToLamports, tradesQueryKey, useAccountStateQuery, useAccountStateSubscription, useActiveAssetLeverageQuery, useAssetMetaQuery, useCancelOrderMutation, useCandlesSubscription, useCoinInfo, useCoinsQuery, useCreateOrderMutation, useHyperliquidSetup, useKlinesQuery, useMarketDataSubscription, useMarketQuery, useMarketsQuery, useOpenOrdersScript, useOrderBookQuery, useOrderBookScript, useOrdersQuery, usePerpDepositClient, usePerpDepositClientMaybe, usePerpDepositExecute, usePerpDepositQuote, usePerpDepositStatus, usePerpetualsClient, usePlaceOrderFormScript, usePositionsQuery, usePositionsScript, useRecentTradesQuery, useSearchCoinsScript, useTradeHistoryScript, useTradesQuery, useTradesScript, useUserDataSubscription, _default as version };