@kodiak-finance/orderly-hooks 2.8.18 → 2.8.19-rc.0

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.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as swr from 'swr';
2
- import { SWRConfiguration, SWRHook, SWRResponse } from 'swr';
2
+ import { SWRConfiguration, SWRHook, SWRResponse, Middleware } from 'swr';
3
3
  export { swr };
4
4
  export { KeyedMutator, Middleware, SWRConfiguration, SWRHook, SWRResponse, unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
5
5
  import * as swr_mutation from 'swr/mutation';
@@ -9,7 +9,7 @@ import { SWRInfiniteKeyLoader, SWRInfiniteConfiguration } from 'swr/infinite';
9
9
  import * as react from 'react';
10
10
  import react__default, { PropsWithChildren, FC, ReactNode } from 'react';
11
11
  import * as _kodiak_finance_orderly_types from '@kodiak-finance/orderly-types';
12
- import { NetworkId, TrackerEventName, API, Chain as Chain$1, OrderlyOrder, ChainNamespace, WSMessage, OrderType, OrderStatus, OrderSide, AlgoOrderRootType, OrderEntity, PositionType, AlgoOrderEntity, AssetHistoryStatusEnum, AlgoOrderType, RequireKeys } from '@kodiak-finance/orderly-types';
12
+ import { NetworkId, TrackerEventName, API, OrderlyOrder, ChainNamespace, WSMessage, OrderType, OrderStatus, OrderSide, AlgoOrderRootType, OrderEntity, PositionType, AlgoOrderEntity, AssetHistoryStatusEnum, AlgoOrderType, RequireKeys } from '@kodiak-finance/orderly-types';
13
13
  import * as _kodiak_finance_orderly_core from '@kodiak-finance/orderly-core';
14
14
  import { AccountState, Account, EventEmitter, ConfigStore, ConfigKey, SimpleDI, OrderlyKeyStore, WalletAdapter, IContract, DefaultConfigStore } from '@kodiak-finance/orderly-core';
15
15
  export { SubAccount, WalletAdapter } from '@kodiak-finance/orderly-core';
@@ -22,9 +22,12 @@ import { SolanaWalletProvider } from '@kodiak-finance/orderly-default-solana-ada
22
22
  import * as swr_subscription from 'swr/subscription';
23
23
  import * as _kodiak_finance_orderly_utils from '@kodiak-finance/orderly-utils';
24
24
  import { Decimal } from '@kodiak-finance/orderly-utils';
25
- export * from 'use-debounce';
26
25
  import * as immer from 'immer';
27
26
  import * as zustand from 'zustand';
27
+ import { StoreMutatorIdentifier, StateCreator } from 'zustand';
28
+ import * as zustand_middleware from 'zustand/middleware';
29
+ import { PersistOptions } from 'zustand/middleware';
30
+ export * from 'use-debounce';
28
31
 
29
32
  declare global {
30
33
  interface Window {
@@ -49,6 +52,16 @@ declare const noCacheConfig: SWRConfiguration;
49
52
  */
50
53
  declare const useQuery: <T>(query: Parameters<SWRHook>[0], options?: useQueryOptions<T>) => SWRResponse<T>;
51
54
 
55
+ /**
56
+ * SWR middleware that waits for __ORDERLY_timestamp_offset to be initialized
57
+ * before allowing requests to proceed.
58
+ */
59
+ declare const timestampWaitingMiddleware: Middleware;
60
+ /**
61
+ * Reset timestamp state (for testing or re-initialization)
62
+ */
63
+ declare function resetTimestampOffsetState(): void;
64
+
52
65
  /**
53
66
  * useQuery
54
67
  * @description for public api
@@ -356,7 +369,7 @@ declare const useAccount: () => {
356
369
  declare const useAccountInstance: () => Account;
357
370
 
358
371
  declare const usePreLoadData: () => {
359
- error: any;
372
+ error: null;
360
373
  done: boolean;
361
374
  };
362
375
 
@@ -382,6 +395,10 @@ declare const useFeeState: () => {
382
395
  readonly refereeRebate: number | undefined;
383
396
  readonly effectiveTakerFee: string;
384
397
  readonly effectiveMakerFee: string;
398
+ readonly rwaTakerFee: string;
399
+ readonly rwaMakerFee: string;
400
+ readonly rwaEffectiveTakerFee: string;
401
+ readonly rwaEffectiveMakerFee: string;
385
402
  };
386
403
 
387
404
  declare const useTrack: () => {
@@ -454,12 +471,14 @@ declare function useChains<T extends NetworkId | undefined, K extends UseChainsO
454
471
  UseChainsReturnObject
455
472
  ];
456
473
 
457
- type filteredChains$1 = {
458
- mainnet?: Chain$1[];
459
- testnet?: Chain$1[];
474
+ type FilteredChains = {
475
+ mainnet?: {
476
+ id: number;
477
+ }[];
478
+ testnet?: {
479
+ id: number;
480
+ }[];
460
481
  };
461
- type chainFilterFunc = (config: ConfigStore) => filteredChains$1;
462
- type chainFilter = filteredChains$1 | chainFilterFunc;
463
482
  interface OrderlyConfigContextState {
464
483
  fetcher?: (url: string, init: RequestInit) => Promise<any>;
465
484
  configStore: ConfigStore;
@@ -470,11 +489,11 @@ interface OrderlyConfigContextState {
470
489
  * @hidden
471
490
  */
472
491
  onlyTestnet?: boolean;
473
- filteredChains?: filteredChains$1 | null;
492
+ filteredChains?: FilteredChains;
474
493
  customChains?: Chains<undefined, undefined>;
475
494
  chainTransformer?: (params: {
476
495
  chains: API.Chain[];
477
- tokenChains: API.Chain[];
496
+ tokenChains: API.Token[];
478
497
  chainInfos: any[];
479
498
  swapChains: any[];
480
499
  mainnet: boolean;
@@ -511,6 +530,11 @@ interface OrderlyConfigContextState {
511
530
  * @default false
512
531
  */
513
532
  defaultOpen?: boolean;
533
+ /**
534
+ * Whether to display the notification in the order entry.
535
+ * @default true
536
+ */
537
+ displayInOrderEntry?: boolean;
514
538
  };
515
539
  };
516
540
  amplitudeConfig?: {
@@ -537,16 +561,13 @@ declare enum WsNetworkStatus {
537
561
  }
538
562
  declare function useWsStatus(): WsNetworkStatus;
539
563
 
540
- type filteredChains = {
541
- mainnet?: Chain$1[];
542
- testnet?: Chain$1[];
543
- };
544
- type filterChainsFunc = (config: ConfigStore) => filteredChains;
564
+ type ChainFilterFunc = (config: ConfigStore) => FilteredChains;
565
+ type ChainFilter = FilteredChains | ChainFilterFunc;
545
566
  type BaseConfigProviderProps = {
546
567
  keyStore?: OrderlyKeyStore;
547
568
  contracts?: IContract;
548
569
  walletAdapters?: WalletAdapter[];
549
- chainFilter?: filteredChains | filterChainsFunc;
570
+ chainFilter?: ChainFilter;
550
571
  /**
551
572
  * Custom orderbook default tick sizes.
552
573
  */
@@ -684,7 +705,7 @@ declare const useSymbolInfo: (symbol?: string) => ((<Key extends keyof _kodiak_f
684
705
  declare const useAccountInfo: () => swr.SWRResponse<API.AccountInfo, any, any>;
685
706
 
686
707
  declare const useMarketsStream: () => {
687
- data: WSMessage.Ticker[] | null;
708
+ data: WSMessage.Ticker[];
688
709
  };
689
710
 
690
711
  declare enum MarketsType$1 {
@@ -735,7 +756,8 @@ declare enum MarketsType {
735
756
  FAVORITES = 0,
736
757
  RECENT = 1,
737
758
  ALL = 2,
738
- NEW_LISTING = 3
759
+ RWA = 3,
760
+ NEW_LISTING = 4
739
761
  }
740
762
  interface FavoriteTab {
741
763
  name: string;
@@ -778,6 +800,10 @@ type MarketsItem = {
778
800
  openInterest: number;
779
801
  isFavorite: boolean;
780
802
  leverage?: number;
803
+ isRwa: boolean;
804
+ rwaNextOpen?: number;
805
+ rwaNextClose?: number;
806
+ rwaStatus?: "open" | "close";
781
807
  };
782
808
  type MarketsStore = ReturnType<typeof useMarketsStore>;
783
809
  declare const MarketsStorageKey = "orderly_markets";
@@ -913,16 +939,89 @@ declare const useFundingRateHistory: () => {
913
939
  getPositiveRates: (data: ReadonlyArray<API.FundingHistory> | API.FundingHistory[], period: PeriodKey) => Record<string, number>;
914
940
  };
915
941
 
942
+ /**
943
+ * Price mode for PnL calculations in position streams
944
+ * @typedef {("markPrice" | "lastPrice")} PriceMode
945
+ * - markPrice: Uses mark price for unrealized PnL calculations (default)
946
+ * - lastPrice: Uses last traded price (index price) for unrealized PnL calculations
947
+ */
916
948
  type PriceMode = "markPrice" | "lastPrice";
917
- declare const usePositionStream: (
918
949
  /**
919
- * If symbol is passed, only the position of that symbol will be returned.
950
+ * Real-time position stream hook with WebSocket integration
951
+ *
952
+ * Subscribes to position updates via WebSocket and provides real-time position data with automatic
953
+ * calculations for unrealized PnL, ROI, and aggregated portfolio metrics. Integrates TP/SL orders
954
+ * and supports both full portfolio view and single symbol tracking.
955
+ *
956
+ * **Key Features:**
957
+ * - Real-time WebSocket updates for positions
958
+ * - Automatic integration of TP/SL (take-profit/stop-loss) orders
959
+ * - Dual price mode support (mark price vs last price)
960
+ * - Optional pending order inclusion
961
+ * - Calculator service integration for real-time PnL updates
962
+ * - Aggregated portfolio metrics (total collateral, value, ROI)
963
+ *
964
+ * **Price Calculation Modes:**
965
+ * - markPrice (default): Uses mark price for unrealized PnL - recommended for margin calculations
966
+ * - lastPrice: Uses last traded price (index price) - useful for more conservative PnL views
967
+ *
968
+ * **Data Flow:**
969
+ * 1. Subscribes to position store (WebSocket-driven)
970
+ * 2. Fetches related TP/SL orders via useOrderStream
971
+ * 3. Registers calculator for real-time price updates (single symbol only)
972
+ * 4. Merges position data with TP/SL information
973
+ * 5. Applies price mode transformations
974
+ * 6. Filters positions based on includedPendingOrder flag
975
+ *
976
+ * @param {string} [symbol="all"] - Trading symbol to filter positions, or "all" for entire portfolio
977
+ * - "all": Returns all positions across all symbols (calculator not registered)
978
+ * - "BTC-PERP": Returns only BTC-PERP position (calculator registered for real-time updates)
979
+ *
980
+ * @param {Object} [options] - Configuration options extending SWR configuration
981
+ * @param {PriceMode} [options.calcMode] - Price calculation mode: "markPrice" or "lastPrice"
982
+ * - markPrice: Uses mark_price field for unrealized_pnl (default, matches exchange calculations)
983
+ * - lastPrice: Uses unrealized_pnl_index field based on last traded price
984
+ * @param {boolean} [options.includedPendingOrder=false] - Include positions with only pending orders
985
+ * - false: Only returns positions with non-zero position_qty
986
+ * - true: Returns positions with position_qty !== 0 OR pending_long_qty/pending_short_qty !== 0
987
+ *
988
+ * @returns {readonly [PositionData, PositionInfoGetter, LoadingState]} Tuple containing:
989
+ * - [0] PositionData object:
990
+ * - rows: Array of position objects with TP/SL information
991
+ * - aggregated: Aggregated metrics (total unrealized PnL, ROI, etc.)
992
+ * - totalCollateral: Total collateral across all positions
993
+ * - totalValue: Total portfolio value
994
+ * - totalUnrealizedROI: Total unrealized ROI percentage
995
+ * - [1] PositionInfoGetter: Memoized getter function for aggregated data access
996
+ * - [2] LoadingState object:
997
+ * - loading: Loading status (deprecated, use isLoading)
998
+ * - isLoading: Current loading state of position data
999
+ *
1000
+ * @example
1001
+ * // Get all positions with mark price calculation
1002
+ * const [{ rows, aggregated, totalCollateral }] = usePositionStream();
1003
+ *
1004
+ * @example
1005
+ * // Get single symbol position with last price calculation
1006
+ * const [{ rows }] = usePositionStream("BTC-PERP", {
1007
+ * calcMode: "lastPrice"
1008
+ * });
1009
+ *
1010
+ * @example
1011
+ * // Include pending orders in results
1012
+ * const [{ rows }, getter, { isLoading }] = usePositionStream("all", {
1013
+ * includedPendingOrder: true
1014
+ * });
1015
+ *
1016
+ * @example
1017
+ * // Access specific position with TP/SL data
1018
+ * const [{ rows }] = usePositionStream("ETH-PERP");
1019
+ * const position = rows[0];
1020
+ * console.log(position.full_tp_sl.tp_trigger_price); // Full position TP price
1021
+ * console.log(position.partial_tp_sl.order_num); // Number of partial TP/SL orders
920
1022
  */
921
- symbol?: string, options?: SWRConfiguration & {
1023
+ declare const usePositionStream: (symbol?: string, options?: SWRConfiguration & {
922
1024
  calcMode?: PriceMode;
923
- /**
924
- * If true, the pending order will be included in the result.
925
- */
926
1025
  includedPendingOrder?: boolean;
927
1026
  }) => readonly [{
928
1027
  readonly rows: API.PositionTPSLExt[];
@@ -994,8 +1093,9 @@ params: {
994
1093
  readonly refresh: () => void;
995
1094
  readonly loadMore: () => void;
996
1095
  readonly cancelAllOrders: (symbol?: string) => Promise<[any, any, any]>;
1096
+ readonly cancelAllPendingOrders: (symbol?: string) => void;
997
1097
  readonly cancelAllTPSLOrders: (symbol?: string) => Promise<any[]>;
998
- readonly cancelAlgoOrdersByTypes: (types: AlgoOrderRootType[]) => Promise<any[]>;
1098
+ readonly cancelAlgoOrdersByTypes: (types: AlgoOrderRootType[], symbol?: string) => Promise<any[]>;
999
1099
  readonly updateOrder: (orderId: string, order: OrderEntity) => Promise<any>;
1000
1100
  readonly cancelOrder: (orderId: number, symbol?: string) => Promise<any>;
1001
1101
  readonly updateAlgoOrder: (orderId: string, order: OrderEntity) => Promise<any>;
@@ -1226,10 +1326,11 @@ declare const useDeposit: (options: DepositOptions) => {
1226
1326
  depositFeeRevalidating: boolean;
1227
1327
  approve: (amount?: string) => Promise<void | undefined>;
1228
1328
  deposit: () => Promise<any>;
1229
- fetchBalance: (address: string, decimals?: number) => Promise<string>;
1230
- fetchBalances: (tokens: API.TokenInfo[]) => Promise<string[]>;
1329
+ fetchBalance: (address: string, decimals?: number, token?: string) => Promise<string>;
1330
+ fetchBalances: (tokens: API.TokenInfo[]) => Promise<Record<string, string>>;
1231
1331
  /** set input quantity */
1232
1332
  setQuantity: react.Dispatch<react.SetStateAction<string>>;
1333
+ targetChain: API.Chain;
1233
1334
  };
1234
1335
 
1235
1336
  interface ConvertOptions {
@@ -1341,6 +1442,10 @@ type OrderValidationItem = {
1341
1442
  type: "priceErrorMin" | "priceErrorMax";
1342
1443
  message: string;
1343
1444
  value?: never;
1445
+ } | {
1446
+ type: number;
1447
+ message: string;
1448
+ value?: never;
1344
1449
  };
1345
1450
  type OrderValidationResult = {
1346
1451
  [P in keyof OrderlyOrder]?: OrderValidationItem;
@@ -1390,10 +1495,6 @@ declare const useTaskProfitAndStopLossInternal: (position: Partial<API.PositionT
1390
1495
  * Conversely, even if defaultOrder is provided and isEditing is false, a new TPSL order is still created
1391
1496
  */
1392
1497
  isEditing?: boolean;
1393
- tpslEnable?: {
1394
- tp_enable?: boolean;
1395
- sl_enable?: boolean;
1396
- };
1397
1498
  positionType?: PositionType;
1398
1499
  }) => [
1399
1500
  /**
@@ -1416,7 +1517,7 @@ ComputedAlgoOrder, {
1416
1517
  /**
1417
1518
  *
1418
1519
  */
1419
- validate: () => Promise<AlgoOrderEntity<AlgoOrderRootType.POSITIONAL_TP_SL | AlgoOrderRootType.TP_SL>>;
1520
+ validate: (otherErrors?: ValidateError) => Promise<AlgoOrderEntity<AlgoOrderRootType.POSITIONAL_TP_SL | AlgoOrderRootType.TP_SL>>;
1420
1521
  metaState: {
1421
1522
  dirty: { [K in keyof OrderlyOrder]?: boolean; };
1422
1523
  submitted: boolean;
@@ -1437,10 +1538,6 @@ position: Partial<API.PositionTPSLExt> & Pick<API.PositionTPSLExt, "symbol" | "a
1437
1538
  * it is usually used when editing order
1438
1539
  */
1439
1540
  defaultOrder?: API.AlgoOrder;
1440
- tpslEnable?: {
1441
- tp_enable?: boolean;
1442
- sl_enable?: boolean;
1443
- };
1444
1541
  isEditing?: boolean;
1445
1542
  positionType?: PositionType;
1446
1543
  }) => ReturnType<typeof useTaskProfitAndStopLossInternal>;
@@ -1648,12 +1745,114 @@ declare const useStorageLedgerAddress: () => {
1648
1745
  /**
1649
1746
  * return all tokens info
1650
1747
  */
1651
- declare const useTokensInfo: () => API.Chain[];
1748
+ declare const useTokensInfo: () => _kodiak_finance_orderly_types.API.Token[] | undefined;
1652
1749
  /**
1653
1750
  * return token info by specify token
1654
1751
  */
1655
- declare const useTokenInfo: (token: string) => API.Chain | undefined;
1752
+ declare const useTokenInfo: (token: string) => _kodiak_finance_orderly_types.API.Token | undefined;
1753
+
1754
+ /**
1755
+ * Check if currently trading based on next_open/next_close timestamps
1756
+ * @param nextOpen - Next open time timestamp
1757
+ * @param nextClose - Next close time timestamp
1758
+ * @param currentTime - Current time timestamp
1759
+ * @returns boolean - true if currently trading
1760
+ */
1761
+ declare const isCurrentlyTrading: (nextClose: number, status: "open" | "close", currentTime?: number) => boolean;
1762
+ declare const isCurrentlyClosed: (nextOpen: number, status: "open" | "close", currentTime?: number) => boolean;
1763
+ /**
1764
+ * Type alias for the return type of useSymbolsInfo hook
1765
+ */
1766
+ type RwaSymbolsInfo = ReturnType<typeof useRwaSymbolsInfo>;
1767
+ /**
1768
+ * A hook that provides access to symbol information.
1769
+ *
1770
+ * @returns A getter object that provides access to symbol information.
1771
+ * The getter allows accessing symbol data either by symbol name directly,
1772
+ * or through a two-level access pattern (symbol and property).
1773
+ *
1774
+ * @example
1775
+ * ```typescript
1776
+ * const rwaSymbolsInfo = useRwaSymbolsInfo();
1777
+ *
1778
+ * // Get all info for a symbol
1779
+ * const ethInfo = rwaSymbolsInfo["PERP_ETH_USDC"]();
1780
+ * ```
1781
+ */
1782
+ declare const useRwaSymbolsInfo: () => Record<string, <Key extends keyof API.RwaSymbol>(key: Key, defaultValue?: API.RwaSymbol[Key] | undefined) => API.RwaSymbol[Key]> & Record<string, () => API.RwaSymbol> & {
1783
+ isNil: boolean;
1784
+ };
1785
+ declare const useRwaSymbolsInfoStore: () => Record<string, API.RwaSymbol> | undefined;
1786
+ /**
1787
+ * Return type definition for the hook
1788
+ *
1789
+ * - isRwa: true if the symbol is an RWA symbol
1790
+ * - open: true if the symbol is open for trading
1791
+ * - nextOpen: the next open time in milliseconds
1792
+ * - nextClose: the next close time in milliseconds
1793
+ * - closeTimeInterval: the time interval in seconds until the symbol closes (countdown format)
1794
+ * - openTimeInterval: the time interval in seconds until the symbol opens (countdown format)
1795
+ */
1796
+ interface RwaSymbolResult {
1797
+ isRwa: boolean;
1798
+ open?: boolean;
1799
+ nextOpen?: number;
1800
+ nextClose?: number;
1801
+ closeTimeInterval?: number;
1802
+ openTimeInterval?: number;
1803
+ }
1804
+ /**
1805
+ * Hook to initialize and manage the global timer
1806
+ * This hook should be called once at the top level of the application to start and manage the global timer
1807
+ */
1808
+ declare const useInitRwaSymbolsRuntime: () => void;
1809
+ /**
1810
+ * Hook to get current RWA symbol information with real-time updates
1811
+ * Retrieves the state of a specific symbol from the centralized store
1812
+ * @param symbol - The symbol to query
1813
+ * @returns RwaSymbolResult containing RWA status and countdown information
1814
+ */
1815
+ declare const useGetRwaSymbolInfo: (symbol: string) => RwaSymbolResult;
1816
+ /**
1817
+ * Simplified hook to get RWA symbol open status with real-time updates
1818
+ * @param symbol - The symbol to query
1819
+ * @returns Object containing isRwa and open status
1820
+ */
1821
+ declare const useGetRwaSymbolOpenStatus: (symbol: string) => {
1822
+ isRwa: boolean;
1823
+ open?: boolean;
1824
+ };
1825
+ /**
1826
+ * Hook to get RWA symbol close time interval with filtering
1827
+ * @param symbol - The symbol to query
1828
+ * @param thresholdMinutes - Time threshold in minutes, defaults to 30
1829
+ * @returns Close time interval in seconds, or undefined if not within threshold
1830
+ */
1831
+ declare const useGetRwaSymbolCloseTimeInterval: (symbol: string, thresholdMinutes?: number) => {
1832
+ isRwa: boolean;
1833
+ open?: boolean;
1834
+ closeTimeInterval?: number;
1835
+ nextClose?: number;
1836
+ };
1837
+ /**
1838
+ * Hook to get RWA symbol open time interval with filtering
1839
+ * @param symbol - The symbol to query
1840
+ * @param thresholdMinutes - Time threshold in minutes, defaults to 30
1841
+ * @returns Open time interval in seconds, or undefined if not within threshold
1842
+ */
1843
+ declare const useGetRwaSymbolOpenTimeInterval: (symbol: string, thresholdMinutes?: number) => {
1844
+ isRwa: boolean;
1845
+ open?: boolean;
1846
+ openTimeInterval?: number;
1847
+ nextOpen?: number;
1848
+ };
1656
1849
 
1850
+ type AppStatus = {
1851
+ positionsLoading: boolean;
1852
+ ordersLoading: boolean;
1853
+ fundingRatesLoading: boolean;
1854
+ ready: boolean;
1855
+ };
1657
1856
  type Portfolio$1 = {
1658
1857
  holding?: API.Holding[];
1659
1858
  totalCollateral: Decimal;
@@ -1663,7 +1862,144 @@ type Portfolio$1 = {
1663
1862
  unsettledPnL: number;
1664
1863
  totalUnrealizedROI: number;
1665
1864
  };
1865
+ type AppState = {
1866
+ accountInfo?: API.AccountInfo;
1867
+ symbolsInfo?: Record<string, API.SymbolExt>;
1868
+ tokensInfo?: API.Token[];
1869
+ rwaSymbolsInfo?: Record<string, API.RwaSymbol>;
1870
+ fundingRates?: Record<string, API.FundingRate>;
1871
+ portfolio: Portfolio$1;
1872
+ appState: AppStatus;
1873
+ };
1874
+ type AppActions = {
1875
+ cleanAll: () => void;
1876
+ setAccountInfo: (accountInfo: API.AccountInfo) => void;
1877
+ setTokensInfo: (tokensInfo: API.Token[]) => void;
1878
+ setSymbolsInfo: (symbolsInfo: Record<string, API.SymbolExt>) => void;
1879
+ setRwaSymbolsInfo: (rwaSymbolsInfo: Record<string, API.RwaSymbol>) => void;
1880
+ setFundingRates: (fundingRates: Record<string, API.FundingRate>) => void;
1881
+ updateAppStatus: (key: keyof AppStatus, value: boolean) => void;
1882
+ updatePortfolio: (key: keyof Omit<Portfolio$1, "usdc" | "holding">, value: number | Decimal) => void;
1883
+ batchUpdateForPortfolio: (data: Partial<Portfolio$1>) => void;
1884
+ restoreHolding: (holding: API.Holding[]) => void;
1885
+ updateHolding: (msg: Record<string, WSMessage.Holding>) => void;
1886
+ };
1887
+ /**
1888
+ * @warning This store should be used with caution. It contains sensitive account and portfolio data.
1889
+ * Please ensure you have proper authorization and follow security best practices when using this store.
1890
+ *
1891
+ * @example
1892
+ * // Correct usage:
1893
+ * const accountInfo = useAppStore(state => state.accountInfo);
1894
+ *
1895
+ * // Avoid direct store manipulation:
1896
+ * const store = useAppStore.getState(); // Not recommended
1897
+ */
1898
+ declare const useAppStore: zustand.UseBoundStore<Omit<zustand.StoreApi<AppState & {
1899
+ actions: AppActions;
1900
+ }>, "setState"> & {
1901
+ setState(nextStateOrUpdater: (AppState & {
1902
+ actions: AppActions;
1903
+ }) | Partial<AppState & {
1904
+ actions: AppActions;
1905
+ }> | ((state: immer.WritableDraft<AppState & {
1906
+ actions: AppActions;
1907
+ }>) => void), shouldReplace?: boolean | undefined): void;
1908
+ }>;
1666
1909
  declare const usePortfolio: () => Portfolio$1;
1910
+ declare const useFundingRateBySymbol: (symbol: string) => API.FundingRate | undefined;
1911
+
1912
+ /**
1913
+ * Generic store state for data fetching
1914
+ */
1915
+ interface DataStoreState<T> {
1916
+ data: T[] | null;
1917
+ loading: boolean;
1918
+ error: Error | null;
1919
+ name: string;
1920
+ /** Whether the store has been hydrated from IndexedDB */
1921
+ hydrated: boolean;
1922
+ }
1923
+ /**
1924
+ * Generic store actions for data fetching
1925
+ */
1926
+ interface DataStoreActions<T> {
1927
+ fetchData: (baseUrl?: string, options?: {
1928
+ brokerId?: string;
1929
+ }) => Promise<T[]>;
1930
+ }
1931
+
1932
+ declare const useMainnetChainsStore: zustand.UseBoundStore<Omit<zustand.StoreApi<DataStoreState<API.Chain> & DataStoreActions<API.Chain>>, "persist"> & {
1933
+ persist: {
1934
+ setOptions: (options: Partial<zustand_middleware.PersistOptions<DataStoreState<API.Chain> & DataStoreActions<API.Chain>, T>>) => void;
1935
+ clearStorage: () => void;
1936
+ rehydrate: () => Promise<void> | void;
1937
+ hasHydrated: () => boolean;
1938
+ onHydrate: (fn: (state: DataStoreState<API.Chain> & DataStoreActions<API.Chain>) => void) => () => void;
1939
+ onFinishHydration: (fn: (state: DataStoreState<API.Chain> & DataStoreActions<API.Chain>) => void) => () => void;
1940
+ getOptions: () => Partial<zustand_middleware.PersistOptions<DataStoreState<API.Chain> & DataStoreActions<API.Chain>, T>>;
1941
+ };
1942
+ }>;
1943
+
1944
+ declare const useTestnetChainsStore: zustand.UseBoundStore<Omit<zustand.StoreApi<DataStoreState<API.Chain> & DataStoreActions<API.Chain>>, "persist"> & {
1945
+ persist: {
1946
+ setOptions: (options: Partial<zustand_middleware.PersistOptions<DataStoreState<API.Chain> & DataStoreActions<API.Chain>, T>>) => void;
1947
+ clearStorage: () => void;
1948
+ rehydrate: () => Promise<void> | void;
1949
+ hasHydrated: () => boolean;
1950
+ onHydrate: (fn: (state: DataStoreState<API.Chain> & DataStoreActions<API.Chain>) => void) => () => void;
1951
+ onFinishHydration: (fn: (state: DataStoreState<API.Chain> & DataStoreActions<API.Chain>) => void) => () => void;
1952
+ getOptions: () => Partial<zustand_middleware.PersistOptions<DataStoreState<API.Chain> & DataStoreActions<API.Chain>, T>>;
1953
+ };
1954
+ }>;
1955
+
1956
+ declare const useMainTokenStore: zustand.UseBoundStore<Omit<zustand.StoreApi<DataStoreState<API.Token> & DataStoreActions<API.Token>>, "persist"> & {
1957
+ persist: {
1958
+ setOptions: (options: Partial<zustand_middleware.PersistOptions<DataStoreState<API.Token> & DataStoreActions<API.Token>, T>>) => void;
1959
+ clearStorage: () => void;
1960
+ rehydrate: () => Promise<void> | void;
1961
+ hasHydrated: () => boolean;
1962
+ onHydrate: (fn: (state: DataStoreState<API.Token> & DataStoreActions<API.Token>) => void) => () => void;
1963
+ onFinishHydration: (fn: (state: DataStoreState<API.Token> & DataStoreActions<API.Token>) => void) => () => void;
1964
+ getOptions: () => Partial<zustand_middleware.PersistOptions<DataStoreState<API.Token> & DataStoreActions<API.Token>, T>>;
1965
+ };
1966
+ }>;
1967
+
1968
+ declare const useTestTokenStore: zustand.UseBoundStore<Omit<zustand.StoreApi<DataStoreState<API.Token> & DataStoreActions<API.Token>>, "persist"> & {
1969
+ persist: {
1970
+ setOptions: (options: Partial<zustand_middleware.PersistOptions<DataStoreState<API.Token> & DataStoreActions<API.Token>, T>>) => void;
1971
+ clearStorage: () => void;
1972
+ rehydrate: () => Promise<void> | void;
1973
+ hasHydrated: () => boolean;
1974
+ onHydrate: (fn: (state: DataStoreState<API.Token> & DataStoreActions<API.Token>) => void) => () => void;
1975
+ onFinishHydration: (fn: (state: DataStoreState<API.Token> & DataStoreActions<API.Token>) => void) => () => void;
1976
+ getOptions: () => Partial<zustand_middleware.PersistOptions<DataStoreState<API.Token> & DataStoreActions<API.Token>, T>>;
1977
+ };
1978
+ }>;
1979
+
1980
+ type SwapSupport = {
1981
+ data: Record<string, any> | null;
1982
+ loading: boolean;
1983
+ error: Error | null;
1984
+ };
1985
+ type SwapSupportActions = {
1986
+ fetchData: () => Promise<Record<string, any> | null>;
1987
+ };
1988
+ declare const useSwapSupportStore: zustand.UseBoundStore<Omit<zustand.StoreApi<SwapSupport & SwapSupportActions>, "persist"> & {
1989
+ persist: {
1990
+ setOptions: (options: Partial<zustand_middleware.PersistOptions<SwapSupport & SwapSupportActions, {
1991
+ data: Record<string, any> | null;
1992
+ }>>) => void;
1993
+ clearStorage: () => void;
1994
+ rehydrate: () => Promise<void> | void;
1995
+ hasHydrated: () => boolean;
1996
+ onHydrate: (fn: (state: SwapSupport & SwapSupportActions) => void) => () => void;
1997
+ onFinishHydration: (fn: (state: SwapSupport & SwapSupportActions) => void) => () => void;
1998
+ getOptions: () => Partial<zustand_middleware.PersistOptions<SwapSupport & SwapSupportActions, {
1999
+ data: Record<string, any> | null;
2000
+ }>>;
2001
+ };
2002
+ }>;
1667
2003
 
1668
2004
  type UseOrderEntryOptions = {
1669
2005
  commify?: boolean;
@@ -1926,6 +2262,7 @@ declare function priceToPnl(inputs: {
1926
2262
  }, options?: {
1927
2263
  symbol?: Pick<API.SymbolExt, "quote_dp">;
1928
2264
  }): number;
2265
+ /** @deprecated use priceToROI instead */
1929
2266
  declare function calcTPSL_ROI(inputs: {
1930
2267
  pnl: number | string;
1931
2268
  qty: number | string;
@@ -2117,6 +2454,94 @@ declare const useApiKeyManager: (queryParams?: {
2117
2454
  readonly resetOrderlyKeyIPRestriction: (orderlyKey: string, mode: "ALLOW_ALL_IPS" | "DISALLOW_ALL_IPS") => Promise<any>;
2118
2455
  }];
2119
2456
 
2457
+ interface StoreConfig {
2458
+ name: string;
2459
+ keyPath?: string;
2460
+ autoIncrement?: boolean;
2461
+ }
2462
+ interface DatabaseConfig {
2463
+ name: string;
2464
+ version: number;
2465
+ stores: StoreConfig[];
2466
+ }
2467
+ declare class IndexedDBManager {
2468
+ private static instance;
2469
+ private connections;
2470
+ private databaseConfig;
2471
+ /** Promise that resolves when database initialization is complete */
2472
+ private initializationPromise;
2473
+ static getInstance(): IndexedDBManager;
2474
+ initializeDatabase(config: DatabaseConfig): Promise<void>;
2475
+ /**
2476
+ * Performs the actual database initialization
2477
+ * Now keeps the connection open for better performance
2478
+ */
2479
+ private _performInitialization;
2480
+ /**
2481
+ * Handles initialization errors consistently
2482
+ */
2483
+ private _handleInitializationError;
2484
+ getConnection(dbName: string, storeName: string): Promise<IDBDatabase>;
2485
+ /**
2486
+ * Ensures database is initialized, initializes if not already done
2487
+ */
2488
+ private ensureInitialized;
2489
+ /**
2490
+ * Creates a new database connection
2491
+ */
2492
+ private createConnection;
2493
+ /**
2494
+ * Checks if database and all required stores exist
2495
+ */
2496
+ private _checkDatabaseExists;
2497
+ }
2498
+ declare const indexedDBManager: IndexedDBManager;
2499
+ declare const initializeAppDatabase: (config: DatabaseConfig) => Promise<void>;
2500
+
2501
+ /**
2502
+ * Configuration for IndexedDB storage
2503
+ */
2504
+ interface IndexedDBStorageConfig {
2505
+ /** Database name */
2506
+ dbName: string;
2507
+ /** Object store name */
2508
+ storeName: string;
2509
+ }
2510
+ /**
2511
+ * Configuration options for IndexedDB persistence middleware
2512
+ */
2513
+ type IndexedDBPersistOptions<T, U = T> = Omit<PersistOptions<T, U>, "storage"> & {
2514
+ /** IndexedDB configuration */
2515
+ indexedDBConfig: IndexedDBStorageConfig;
2516
+ };
2517
+ /**
2518
+ * Creates a Zustand store with IndexedDB persistence
2519
+ *
2520
+ * @param initializer - The state creator function
2521
+ * @param options - Persistence options including IndexedDB configuration
2522
+ * @returns A state creator with IndexedDB persistence middleware applied
2523
+ *
2524
+ * @example
2525
+ * ```typescript
2526
+ * const useStore = create(
2527
+ * persistIndexedDB(
2528
+ * (set) => ({
2529
+ * items: [],
2530
+ * addItem: (item) => set((state) => ({ items: [...state.items, item] })),
2531
+ * }),
2532
+ * {
2533
+ * name: 'my-store',
2534
+ * indexedDBConfig: {
2535
+ * dbName: 'ORDERLY_STORE',
2536
+ * storeName: 'ITEMS_STORE',
2537
+ * },
2538
+ * }
2539
+ * )
2540
+ * );
2541
+ * ```
2542
+ */
2543
+ declare const persistIndexedDB: <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = [], U = T>(initializer: StateCreator<T, [...Mps, ["zustand/persist", unknown]], Mcs>, options: IndexedDBPersistOptions<T, U>) => StateCreator<T, Mps, [["zustand/persist", U], ...Mcs]>;
2544
+
2120
2545
  type FullOrderState = OrderlyOrder;
2121
2546
  type OrderEntryStateEntity = RequireKeys<FullOrderState, "side" | "order_type" | "symbol">;
2122
2547
  type OrderEntryState = {
@@ -2155,6 +2580,7 @@ declare const useOrderEntryNextInternal: (symbol: string, options?: {
2155
2580
  */
2156
2581
  initialOrder?: Omit<Partial<FullOrderState>, "symbol">;
2157
2582
  symbolInfo?: API.SymbolExt;
2583
+ symbolLeverage?: number;
2158
2584
  }) => {
2159
2585
  readonly formattedOrder: Required<Pick<OrderlyOrder, "symbol" | "side" | "order_type">> & Partial<Omit<OrderlyOrder, "symbol" | "side" | "order_type">>;
2160
2586
  readonly setValue: (key: keyof FullOrderState, value: any, additional?: {
@@ -2215,7 +2641,7 @@ type OrderEntryReturn = {
2215
2641
  * Function to validate the order.
2216
2642
  * @returns {Promise<OrderValidationResult | null>} The validation result.
2217
2643
  */
2218
- validate: () => Promise<OrderValidationResult | null>;
2644
+ validate: (otherErrors?: OrderValidationResult) => Promise<OrderValidationResult | null>;
2219
2645
  };
2220
2646
  freeCollateral: number;
2221
2647
  /**
@@ -2244,7 +2670,8 @@ type OrderEntryReturn = {
2244
2670
  * Indicates if a mutation (order creation) is in progress.
2245
2671
  */
2246
2672
  isMutating: boolean;
2247
- markPrice: number | undefined;
2673
+ markPrice?: number;
2674
+ symbolLeverage?: number;
2248
2675
  };
2249
2676
  /**
2250
2677
  * Custom hook for managing order entry in the Orderly application.
@@ -2424,4 +2851,19 @@ declare const usePositionClose: (options: PositionCloseOptions) => {
2424
2851
  declare const useMarketList: () => API.MarketInfoExt[];
2425
2852
  declare const useMarketMap: () => Record<string, API.MarketInfoExt> | null;
2426
2853
 
2427
- export { type APIKeyItem, type AccountRewardsHistory, type AccountRewardsHistoryRow, type Brokers, type Chain, type Chains, type CheckReferralCodeReturns, type CollateralOutputs, type ComputedAlgoOrder, type ConfigProviderProps, type ConnectedChain, type CurrentEpochEstimate, DefaultLayoutConfig, DistributionId, type DrawOptions, ENVType, type EpochInfoItem, type EpochInfoType, EpochStatus, type ExclusiveConfigProviderProps, ExtendedConfigStore, type Favorite, type FavoriteTab, type FundingRates, MaintenanceStatus, type MarginRatioReturn, type MarketsItem, MarketsStorageKey, type MarketsStore, MarketsType, type NewListing, ORDERLY_ORDERBOOK_DEPTH_KEY, type OrderBookItem, type OrderEntryReturn, type OrderMetadata, type OrderMetadataConfig, type OrderParams, type OrderValidationItem, type OrderValidationResult, type OrderbookData, type OrderbookOptions, type OrderlyConfigContextState, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, type PosterLayoutConfig, type PriceMode, type Recent, RefferalAPI, type RestrictedInfoOptions, type RestrictedInfoReturns, ScopeType, type StatusInfo, StatusProvider, type SymbolsInfo, TWType, type UseChainsOptions, type UseChainsReturnObject, type UseOrderEntryMetaState, WalletConnectorContext, type WalletConnectorContextState, type WalletRewards, type WalletRewardsHistoryReturns, type WalletRewardsItem, type WalletState, WsNetworkStatus, type chainFilter, type chainFilterFunc, checkNotional, cleanStringStyle, fetcher, type filteredChains$1 as filteredChains, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, noCacheConfig, parseJSON, useAccount, useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useAudioPlayer, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChainInfo, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFeeState, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLeverageBySymbol, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxLeverage, useMaxQty, useMaxWithdrawal, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry, useOrderEntry$1 as useOrderEntry_deprecated, useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, type useQueryOptions, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSymbolInfo, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTickerStream, useTokenInfo, useTokensInfo, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, index as utils, _default as version };
2854
+ type TpslPriceParams = {
2855
+ warning_threshold?: number;
2856
+ slPrice?: string;
2857
+ liqPrice: number | null;
2858
+ side?: OrderSide;
2859
+ };
2860
+ declare const useTpslPriceChecker: (params: TpslPriceParams) => OrderValidationResult | null;
2861
+
2862
+ declare const ERROR_MSG_CODES: {
2863
+ SL_PRICE_WARNING: number;
2864
+ SL_PRICE_ERROR: number;
2865
+ };
2866
+
2867
+ declare const useEstLiqPriceBySymbol: (symbol: string) => number | undefined;
2868
+
2869
+ export { type APIKeyItem, type AccountRewardsHistory, type AccountRewardsHistoryRow, type Brokers, type Chain, type ChainFilter, type Chains, type CheckReferralCodeReturns, type CollateralOutputs, type ComputedAlgoOrder, type ConfigProviderProps, type ConnectedChain, type CurrentEpochEstimate, DefaultLayoutConfig, DistributionId, type DrawOptions, ENVType, ERROR_MSG_CODES, type EpochInfoItem, type EpochInfoType, EpochStatus, type ExclusiveConfigProviderProps, ExtendedConfigStore, type Favorite, type FavoriteTab, type FilteredChains, type FundingRates, MaintenanceStatus, type MarginRatioReturn, type MarketsItem, MarketsStorageKey, type MarketsStore, MarketsType, type NewListing, ORDERLY_ORDERBOOK_DEPTH_KEY, type OrderBookItem, type OrderEntryReturn, type OrderMetadata, type OrderMetadataConfig, type OrderParams, type OrderValidationItem, type OrderValidationResult, type OrderbookData, type OrderbookOptions, type OrderlyConfigContextState, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, type PosterLayoutConfig, type PriceMode, type Recent, RefferalAPI, type RestrictedInfoOptions, type RestrictedInfoReturns, type RwaSymbolResult, type RwaSymbolsInfo, ScopeType, type StatusInfo, StatusProvider, type SymbolsInfo, TWType, type UseChainsOptions, type UseChainsReturnObject, type UseOrderEntryMetaState, WalletConnectorContext, type WalletConnectorContextState, type WalletRewards, type WalletRewardsHistoryReturns, type WalletRewardsItem, type WalletState, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, indexedDBManager, initializeAppDatabase, isCurrentlyClosed, isCurrentlyTrading, noCacheConfig, parseJSON, persistIndexedDB, resetTimestampOffsetState, timestampWaitingMiddleware, useAccount, useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAppStore, useAssetsHistory, useAudioPlayer, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChainInfo, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEstLiqPriceBySymbol, useEventEmitter, useFeeState, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateBySymbol, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useGetRwaSymbolCloseTimeInterval, useGetRwaSymbolInfo, useGetRwaSymbolOpenStatus, useGetRwaSymbolOpenTimeInterval, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInitRwaSymbolsRuntime, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLeverageBySymbol, useLocalStorage, useMainTokenStore, useMainnetChainsStore, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxLeverage, useMaxQty, useMaxWithdrawal, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry, useOrderEntry$1 as useOrderEntry_deprecated, useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, type useQueryOptions, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useRwaSymbolsInfo, useRwaSymbolsInfoStore, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSwapSupportStore, useSymbolInfo, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTestTokenStore, useTestnetChainsStore, useTickerStream, useTokenInfo, useTokensInfo, useTpslPriceChecker, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, index as utils, _default as version };