@orderly.network/hooks 2.8.1 → 2.8.2

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.mjs CHANGED
@@ -3,10 +3,10 @@ import useSWR__default, { mutate } from 'swr';
3
3
  import * as useSWR from 'swr';
4
4
  export { useSWR as swr };
5
5
  export { unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
6
- import { TesntTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, EMPTY_LIST, EMPTY_OBJECT, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, ARBITRUM_TESTNET_CHAINID, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, ETHEREUM_MAINNET_CHAINID, DEPOSIT_FEE_RATE, LedgerWalletKey, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
6
+ import { TesnetTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, EMPTY_LIST, EMPTY_OBJECT, ARBITRUM_TESTNET_CHAINID, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, ETHEREUM_MAINNET_CHAINID, DEPOSIT_FEE_RATE, LedgerWalletKey, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
7
7
  import React2, { createContext, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
8
- import useSWRMutation from 'swr/mutation';
9
8
  import { zero, windowGuard, getTimestamp, getGlobalObject, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, getBBOType, camelCaseToUnderscoreCase, commify, todpIfNeed, getTPSLDirection } from '@orderly.network/utils';
9
+ import useSWRMutation from 'swr/mutation';
10
10
  import useConstant from 'use-constant';
11
11
  export { default as useConstant } from 'use-constant';
12
12
  import { SimpleDI, Account, EventEmitter, DefaultConfigStore, EVENT_NAMES, LocalStorageStore } from '@orderly.network/core';
@@ -14,14 +14,16 @@ import { debounce } from 'lodash';
14
14
  import useSWRInfinite, { unstable_serialize } from 'swr/infinite';
15
15
  import { pathOr, min, max, omit, prop, pick, compose, head, mergeDeepRight, isNil, propOr, path, lensIndex, over } from 'ramda';
16
16
  import { account, order, positions } from '@orderly.network/perp';
17
+ import { create } from 'zustand';
18
+ import { immer } from 'zustand/middleware/immer';
19
+ import pathOr$1 from 'ramda/es/pathOr';
20
+ import { persist, createJSONStorage } from 'zustand/middleware';
17
21
  import useSWRSubscription from 'swr/subscription';
18
22
  import * as amplitude from '@amplitude/analytics-browser';
19
23
  import { jsx } from 'react/jsx-runtime';
20
24
  import { DefaultEVMWalletAdapter } from '@orderly.network/default-evm-adapter';
21
25
  import { DefaultSolanaWalletAdapter } from '@orderly.network/default-solana-adapter';
22
26
  import { EthersProvider } from '@orderly.network/web3-provider-ethers';
23
- import { create } from 'zustand';
24
- import { immer } from 'zustand/middleware/immer';
25
27
  import { useDebouncedCallback } from 'use-debounce';
26
28
  export * from 'use-debounce';
27
29
  import { produce } from 'immer';
@@ -36,9 +38,9 @@ var __export = (target, all) => {
36
38
  // src/version.ts
37
39
  if (typeof window !== "undefined") {
38
40
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
39
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.8.1";
41
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.8.2";
40
42
  }
41
- var version_default = "2.8.1";
43
+ var version_default = "2.8.2";
42
44
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
43
45
  var noCacheConfig = {
44
46
  dedupingInterval: 0,
@@ -85,6 +87,69 @@ var useQuery = (query, options) => {
85
87
  swrOptions
86
88
  );
87
89
  };
90
+ var timestampOffsetPromise = null;
91
+ var timestampOffsetReady = false;
92
+ var timestampWaitingMiddleware = (useSWRNext) => {
93
+ return (key, fetcher4, config) => {
94
+ if (!fetcher4) {
95
+ return useSWRNext(key, fetcher4, config);
96
+ }
97
+ const wrappedFetcher = async (...args) => {
98
+ await getTimestampOffsetPromise();
99
+ return fetcher4(...args);
100
+ };
101
+ return useSWRNext(key, wrappedFetcher, config);
102
+ };
103
+ };
104
+ function getTimestampOffsetPromise() {
105
+ if (timestampOffsetReady) {
106
+ return Promise.resolve();
107
+ }
108
+ if (timestampOffsetPromise) {
109
+ return timestampOffsetPromise;
110
+ }
111
+ timestampOffsetPromise = waitForTimestampOffset();
112
+ timestampOffsetPromise.then(() => {
113
+ timestampOffsetReady = true;
114
+ }).catch(() => {
115
+ timestampOffsetPromise = null;
116
+ });
117
+ return timestampOffsetPromise;
118
+ }
119
+ async function waitForTimestampOffset(maxWaitTime = 3e4) {
120
+ let globalObj;
121
+ try {
122
+ globalObj = getGlobalObject();
123
+ } catch {
124
+ throw new Error("Failed to access global object");
125
+ }
126
+ const checkTimestampOffset = () => {
127
+ return typeof globalObj.__ORDERLY_timestamp_offset === "number";
128
+ };
129
+ if (checkTimestampOffset()) {
130
+ return;
131
+ }
132
+ return new Promise((resolve, reject) => {
133
+ let attempts = 0;
134
+ const maxAttempts = maxWaitTime / 100;
135
+ const pollInterval = setInterval(() => {
136
+ attempts++;
137
+ if (checkTimestampOffset()) {
138
+ clearInterval(pollInterval);
139
+ resolve();
140
+ } else if (attempts >= maxAttempts) {
141
+ clearInterval(pollInterval);
142
+ reject(
143
+ new Error("Timeout waiting for timestamp offset initialization")
144
+ );
145
+ }
146
+ }, 100);
147
+ });
148
+ }
149
+ function resetTimestampOffsetState() {
150
+ timestampOffsetPromise = null;
151
+ timestampOffsetReady = false;
152
+ }
88
153
  var useLazyQuery = (query, options) => {
89
154
  const apiBaseUrl = useConfig("apiBaseUrl");
90
155
  const { formatter, init: init2, ...swrOptions } = options || {};
@@ -2036,90 +2101,710 @@ var useReferralInfo = () => {
2036
2101
  getFirstRefCode
2037
2102
  };
2038
2103
  };
2039
- var usePreLoadData = () => {
2040
- const [timestampOffsetInitialized, setTimestampOffsetInitialized] = useState(false);
2041
- const { error: tokenError, data: tokenData } = useQuery(
2042
- "https://api.orderly.org/v1/public/token",
2043
- {
2044
- revalidateOnFocus: false
2045
- }
2046
- );
2047
- const apiBaseUrl = useConfig("apiBaseUrl");
2048
- const { data: systemInfo } = useSWR__default(
2049
- "/v1/public/system_info",
2050
- async (url, init2) => {
2051
- const data = await fetch(
2052
- url.startsWith("http") ? url : `${apiBaseUrl}${url}`,
2053
- init2
2054
- );
2055
- return await data.json();
2104
+ var useAppStore = create()(
2105
+ immer((set) => ({
2106
+ // accountInfo: null,
2107
+ portfolio: {
2108
+ totalCollateral: zero,
2109
+ totalValue: null,
2110
+ freeCollateral: zero,
2111
+ availableBalance: 0,
2112
+ unsettledPnL: 0,
2113
+ totalUnrealizedROI: 0
2056
2114
  },
2057
- {
2058
- errorRetryCount: 3,
2059
- errorRetryInterval: 500
2060
- }
2061
- );
2062
- useEffect(() => {
2063
- if (timestampOffsetInitialized)
2064
- return;
2065
- if (typeof systemInfo !== "undefined") {
2066
- const sd = systemInfo.timestamp;
2067
- const ld = Date.now();
2068
- const diff = sd - ld;
2069
- if (isNaN(diff)) {
2070
- return;
2115
+ appState: {
2116
+ positionsLoading: false,
2117
+ ordersLoading: false,
2118
+ fundingRatesLoading: false,
2119
+ ready: false
2120
+ },
2121
+ actions: {
2122
+ setTokensInfo: (tokensInfo) => {
2123
+ set((state) => {
2124
+ state.tokensInfo = tokensInfo;
2125
+ }, false);
2126
+ },
2127
+ cleanAll: () => {
2128
+ set((state) => {
2129
+ state.accountInfo = void 0;
2130
+ state.portfolio = {
2131
+ totalCollateral: zero,
2132
+ totalValue: null,
2133
+ freeCollateral: zero,
2134
+ availableBalance: 0,
2135
+ unsettledPnL: 0,
2136
+ totalUnrealizedROI: 0
2137
+ };
2138
+ }, false);
2139
+ },
2140
+ setAccountInfo: (accountInfo) => {
2141
+ set(
2142
+ (state) => {
2143
+ state.accountInfo = accountInfo;
2144
+ },
2145
+ false
2146
+ // "setAccountInfo"
2147
+ );
2148
+ },
2149
+ setSymbolsInfo: (symbolsInfo) => {
2150
+ set(
2151
+ (state) => {
2152
+ state.symbolsInfo = symbolsInfo;
2153
+ },
2154
+ false
2155
+ // "setSymbolsInfo"
2156
+ );
2157
+ },
2158
+ setRwaSymbolsInfo: (rwaSymbolsInfo) => {
2159
+ set(
2160
+ (state) => {
2161
+ state.rwaSymbolsInfo = rwaSymbolsInfo;
2162
+ },
2163
+ false
2164
+ // "setRwaSymbolsInfo"
2165
+ );
2166
+ },
2167
+ setFundingRates: (fundingRates) => {
2168
+ set(
2169
+ (state) => {
2170
+ state.fundingRates = fundingRates;
2171
+ },
2172
+ false
2173
+ // "setFundingRates"
2174
+ );
2175
+ },
2176
+ updateAppStatus: (key, value) => {
2177
+ set(
2178
+ (state) => {
2179
+ state.appState[key] = value;
2180
+ },
2181
+ false
2182
+ // "updateAppStatus"
2183
+ );
2184
+ },
2185
+ updatePortfolio: (key, value) => {
2186
+ set(
2187
+ (state) => {
2188
+ state.portfolio[key] = value;
2189
+ },
2190
+ false
2191
+ // "updatePortfolio"
2192
+ );
2193
+ },
2194
+ batchUpdateForPortfolio: (data) => {
2195
+ set(
2196
+ (state) => {
2197
+ state.portfolio = { ...state.portfolio, ...data };
2198
+ },
2199
+ false
2200
+ // "batchUpdateForPortfolio"
2201
+ );
2202
+ },
2203
+ restoreHolding: (holding) => {
2204
+ set(
2205
+ (state) => {
2206
+ state.portfolio.holding = holding;
2207
+ },
2208
+ false
2209
+ // "updateHolding"
2210
+ );
2211
+ },
2212
+ updateHolding(msg) {
2213
+ set(
2214
+ (state) => {
2215
+ if (state.portfolio.holding && state.portfolio.holding.length) {
2216
+ for (const key in msg) {
2217
+ const holding = state.portfolio.holding.find(
2218
+ (item) => item.token === key
2219
+ );
2220
+ if (holding) {
2221
+ holding.holding = msg[key].holding;
2222
+ holding.frozen = msg[key].frozen;
2223
+ }
2224
+ }
2225
+ }
2226
+ },
2227
+ false
2228
+ // "updateHolding"
2229
+ );
2071
2230
  }
2072
- getGlobalObject().__ORDERLY_timestamp_offset = diff;
2073
- setTimestampOffsetInitialized(true);
2074
2231
  }
2075
- }, [systemInfo, timestampOffsetInitialized]);
2076
- const isDone = useMemo(() => {
2077
- return !!tokenData && timestampOffsetInitialized;
2078
- }, [timestampOffsetInitialized, tokenData]);
2079
- return {
2080
- error: tokenError,
2081
- done: isDone
2082
- };
2232
+ }))
2233
+ );
2234
+ var useAccountInfo = () => useAppStore((state) => state.accountInfo);
2235
+ var usePortfolio = () => useAppStore((state) => state.portfolio);
2236
+ var useFundingRateBySymbol = (symbol) => useAppStore((state) => state.fundingRates?.[symbol]);
2237
+
2238
+ // src/middleware/indexedDBManager.ts
2239
+ var ORDERLY_SYMBOLS = {
2240
+ name: "ORDERLY_SYMBOLS",
2241
+ keyPath: "symbol",
2242
+ autoIncrement: false
2083
2243
  };
2084
- function useSessionStorage(key, initialValue) {
2085
- const readValue = useCallback(() => {
2086
- if (typeof window === "undefined") {
2087
- return initialValue;
2244
+ var ORDERLY_MAIN_CHAIN_INFO = {
2245
+ name: "ORDERLY_MAIN_CHAIN_INFO",
2246
+ keyPath: "chain_id",
2247
+ autoIncrement: false
2248
+ };
2249
+ var ORDERLY_TEST_CHAIN_INFO = {
2250
+ name: "ORDERLY_TEST_CHAIN_INFO",
2251
+ keyPath: "chain_id",
2252
+ autoIncrement: false
2253
+ };
2254
+ var ORDERLY_MAIN_TOKEN = {
2255
+ name: "ORDERLY_MAIN_TOKEN",
2256
+ keyPath: "token",
2257
+ autoIncrement: false
2258
+ };
2259
+ var ORDERLY_TEST_TOKEN = {
2260
+ name: "ORDERLY_TEST_TOKEN",
2261
+ keyPath: "token",
2262
+ autoIncrement: false
2263
+ };
2264
+ var DEFAULT_DATABASE_CONFIG = {
2265
+ name: "ORDERLY_STORE",
2266
+ version: 4,
2267
+ stores: [
2268
+ ORDERLY_MAIN_CHAIN_INFO,
2269
+ ORDERLY_TEST_CHAIN_INFO,
2270
+ ORDERLY_MAIN_TOKEN,
2271
+ ORDERLY_SYMBOLS,
2272
+ ORDERLY_TEST_TOKEN
2273
+ ]
2274
+ };
2275
+ var IndexedDBManager = class _IndexedDBManager {
2276
+ constructor() {
2277
+ this.connections = /* @__PURE__ */ new Map();
2278
+ this.databaseConfig = null;
2279
+ /** Promise that resolves when database initialization is complete */
2280
+ this.initializationPromise = null;
2281
+ }
2282
+ static getInstance() {
2283
+ if (!_IndexedDBManager.instance) {
2284
+ _IndexedDBManager.instance = new _IndexedDBManager();
2088
2285
  }
2089
- try {
2090
- const item = window.sessionStorage.getItem(key);
2091
- return item ? parseJSON(item) : initialValue;
2092
- } catch (error) {
2093
- return initialValue;
2286
+ return _IndexedDBManager.instance;
2287
+ }
2288
+ async initializeDatabase(config) {
2289
+ if (this.initializationPromise) {
2290
+ return this.initializationPromise;
2094
2291
  }
2095
- }, [initialValue, key]);
2096
- const [storedValue, setStoredValue] = useState(readValue);
2097
- const setValue = (value) => {
2098
- try {
2099
- const newValue = value instanceof Function ? value(storedValue) : value;
2100
- window.sessionStorage.setItem(key, JSON.stringify(newValue));
2101
- setStoredValue(newValue);
2102
- } catch (error) {
2292
+ this.initializationPromise = this._performInitialization(config);
2293
+ return this.initializationPromise;
2294
+ }
2295
+ /**
2296
+ * Performs the actual database initialization
2297
+ * Now keeps the connection open for better performance
2298
+ */
2299
+ async _performInitialization(config) {
2300
+ this.databaseConfig = config;
2301
+ return new Promise((resolve, reject) => {
2302
+ const request = indexedDB.open(config.name, config.version);
2303
+ request.onupgradeneeded = (event) => {
2304
+ const db = event.target.result;
2305
+ config.stores.forEach((storeConfig) => {
2306
+ if (!db.objectStoreNames.contains(storeConfig.name)) {
2307
+ db.createObjectStore(storeConfig.name, {
2308
+ keyPath: storeConfig.keyPath,
2309
+ autoIncrement: storeConfig.autoIncrement ?? true
2310
+ });
2311
+ }
2312
+ });
2313
+ };
2314
+ request.onsuccess = () => {
2315
+ const db = request.result;
2316
+ this.connections.set(config.name, db);
2317
+ db.addEventListener("close", () => {
2318
+ this.connections.delete(config.name);
2319
+ });
2320
+ resolve();
2321
+ };
2322
+ request.onerror = () => {
2323
+ this._handleInitializationError(config.name, request.error);
2324
+ reject(request.error);
2325
+ };
2326
+ request.onblocked = () => {
2327
+ const error = new Error(
2328
+ `Database '${config.name}' is blocked by another connection`
2329
+ );
2330
+ this._handleInitializationError(config.name, error);
2331
+ reject(error);
2332
+ };
2333
+ });
2334
+ }
2335
+ /**
2336
+ * Handles initialization errors consistently
2337
+ */
2338
+ _handleInitializationError(dbName, error) {
2339
+ this.initializationPromise = null;
2340
+ }
2341
+ async getConnection(dbName, storeName) {
2342
+ await this.ensureInitialized();
2343
+ if (this.connections.has(dbName)) {
2344
+ const existingConnection = this.connections.get(dbName);
2345
+ try {
2346
+ if (existingConnection.objectStoreNames.contains(storeName)) {
2347
+ return existingConnection;
2348
+ }
2349
+ } catch {
2350
+ this.connections.delete(dbName);
2351
+ }
2103
2352
  }
2104
- };
2105
- useEffect(() => {
2106
- setStoredValue(readValue());
2107
- }, []);
2108
- useEffect(() => {
2109
- if (typeof window == "undefined") {
2110
- return;
2353
+ const db = await this.createConnection(dbName);
2354
+ this.connections.set(dbName, db);
2355
+ db.addEventListener("close", () => {
2356
+ this.connections.delete(dbName);
2357
+ });
2358
+ return db;
2359
+ }
2360
+ /**
2361
+ * Ensures database is initialized, initializes if not already done
2362
+ */
2363
+ async ensureInitialized() {
2364
+ if (this.initializationPromise) {
2365
+ return this.initializationPromise;
2111
2366
  }
2112
- window.addEventListener?.("storage", handleStorageChange);
2113
- return () => {
2114
- window.removeEventListener?.("storage", handleStorageChange);
2115
- };
2116
- });
2117
- const handleStorageChange = useCallback(
2118
- (event) => {
2119
- if (event?.key && event.key !== key) {
2120
- return;
2121
- }
2122
- setStoredValue(readValue());
2367
+ if (!this.databaseConfig) {
2368
+ return this.initializeDatabase(DEFAULT_DATABASE_CONFIG);
2369
+ }
2370
+ const isActuallyInitialized = await this._checkDatabaseExists();
2371
+ if (!isActuallyInitialized) {
2372
+ this.initializationPromise = null;
2373
+ return this.initializeDatabase(this.databaseConfig);
2374
+ }
2375
+ this.initializationPromise = Promise.resolve();
2376
+ return this.initializationPromise;
2377
+ }
2378
+ /**
2379
+ * Creates a new database connection
2380
+ */
2381
+ async createConnection(dbName) {
2382
+ const config = this.databaseConfig;
2383
+ if (!config) {
2384
+ throw new Error(
2385
+ "Database not initialized. Call initializeDatabase() first."
2386
+ );
2387
+ }
2388
+ return new Promise((resolve, reject) => {
2389
+ const request = indexedDB.open(dbName, config.version);
2390
+ request.onsuccess = () => {
2391
+ resolve(request.result);
2392
+ };
2393
+ request.onerror = () => {
2394
+ reject(request.error);
2395
+ };
2396
+ });
2397
+ }
2398
+ /**
2399
+ * Checks if database and all required stores exist
2400
+ */
2401
+ async _checkDatabaseExists() {
2402
+ if (!this.databaseConfig) {
2403
+ return false;
2404
+ }
2405
+ try {
2406
+ return new Promise((resolve) => {
2407
+ const config = this.databaseConfig;
2408
+ const request = indexedDB.open(config.name, config.version);
2409
+ request.onsuccess = () => {
2410
+ const db = request.result;
2411
+ const config2 = this.databaseConfig;
2412
+ const allStoresExist = config2.stores.every(
2413
+ (store) => db.objectStoreNames.contains(store.name)
2414
+ );
2415
+ db.close();
2416
+ resolve(allStoresExist);
2417
+ };
2418
+ request.onerror = () => resolve(false);
2419
+ });
2420
+ } catch {
2421
+ return false;
2422
+ }
2423
+ }
2424
+ };
2425
+ var indexedDBManager = IndexedDBManager.getInstance();
2426
+ var initializeAppDatabase = async (config) => {
2427
+ try {
2428
+ await indexedDBManager.initializeDatabase(config);
2429
+ } catch (error) {
2430
+ throw error;
2431
+ }
2432
+ };
2433
+ var createIndexedDBStorage = (config) => {
2434
+ const { dbName, storeName } = config;
2435
+ const getDB = async () => {
2436
+ return indexedDBManager.getConnection(dbName, storeName);
2437
+ };
2438
+ const executeTransaction = async (operation, mode = "readwrite") => {
2439
+ const dbInstance = await getDB();
2440
+ const transaction = dbInstance.transaction(storeName, mode);
2441
+ const store = transaction.objectStore(storeName);
2442
+ return new Promise((resolve, reject) => {
2443
+ const result = operation(store);
2444
+ transaction.oncomplete = () => resolve(result);
2445
+ transaction.onerror = () => {
2446
+ reject(transaction.error);
2447
+ };
2448
+ transaction.onabort = () => {
2449
+ reject(new Error("Transaction was aborted"));
2450
+ };
2451
+ });
2452
+ };
2453
+ const getItem = async () => {
2454
+ try {
2455
+ const allValues = await executeTransaction((store) => {
2456
+ return new Promise((resolve, reject) => {
2457
+ const request = store.getAll();
2458
+ request.onsuccess = () => {
2459
+ const result = request.result;
2460
+ resolve(result.length > 0 ? result : []);
2461
+ };
2462
+ request.onerror = () => reject(request.error);
2463
+ });
2464
+ }, "readonly");
2465
+ return allValues.length > 0 ? allValues : null;
2466
+ } catch (error) {
2467
+ return null;
2468
+ }
2469
+ };
2470
+ const setItem = async (value) => {
2471
+ try {
2472
+ await executeTransaction((store) => {
2473
+ store.clear();
2474
+ value.forEach((item) => store.put(item));
2475
+ return void 0;
2476
+ }, "readwrite");
2477
+ } catch (error) {
2478
+ throw error;
2479
+ }
2480
+ };
2481
+ const removeItem = async () => {
2482
+ try {
2483
+ await executeTransaction((store) => {
2484
+ store.clear();
2485
+ return void 0;
2486
+ }, "readwrite");
2487
+ } catch (error) {
2488
+ throw error;
2489
+ }
2490
+ };
2491
+ return {
2492
+ getItem,
2493
+ setItem,
2494
+ removeItem
2495
+ };
2496
+ };
2497
+ var adaptToStateStorage = (indexedDBStorage) => ({
2498
+ getItem: async () => {
2499
+ try {
2500
+ const result = await indexedDBStorage.getItem();
2501
+ return result && Array.isArray(result) && result.length > 0 ? JSON.stringify({
2502
+ state: result,
2503
+ version: 0
2504
+ }) : null;
2505
+ } catch (error) {
2506
+ return null;
2507
+ }
2508
+ },
2509
+ setItem: async (_name, value) => {
2510
+ try {
2511
+ const parsed = JSON.parse(value);
2512
+ const stateData = pathOr$1([], ["state"], parsed);
2513
+ if (Array.isArray(stateData) && stateData.length > 0) {
2514
+ await indexedDBStorage.setItem(stateData);
2515
+ }
2516
+ } catch (error) {
2517
+ }
2518
+ },
2519
+ removeItem: async () => {
2520
+ try {
2521
+ await indexedDBStorage.removeItem();
2522
+ } catch (error) {
2523
+ }
2524
+ }
2525
+ });
2526
+ var persistIndexedDB = (initializer, options) => {
2527
+ const { indexedDBConfig, ...rest } = options;
2528
+ const indexedDBStorage = createIndexedDBStorage(indexedDBConfig);
2529
+ const jsonStorage = createJSONStorage(
2530
+ () => adaptToStateStorage(indexedDBStorage)
2531
+ );
2532
+ return persist(initializer, {
2533
+ ...rest,
2534
+ storage: jsonStorage
2535
+ });
2536
+ };
2537
+
2538
+ // src/provider/store/createDataStore.ts
2539
+ var createDataStore = (config) => {
2540
+ const {
2541
+ name,
2542
+ dbName,
2543
+ storeName,
2544
+ keyPath,
2545
+ endpoint,
2546
+ baseUrl,
2547
+ formatter = (data) => pathOr$1([], ["rows"], data),
2548
+ initData
2549
+ // brokerId,
2550
+ } = config;
2551
+ return create(
2552
+ persistIndexedDB(
2553
+ (set) => ({
2554
+ name: storeName,
2555
+ data: typeof initData === "undefined" ? [] : initData,
2556
+ loading: false,
2557
+ error: null,
2558
+ fetchData: async (dynamicBaseUrl, options) => {
2559
+ try {
2560
+ set({ loading: true });
2561
+ const brokerIdQuery = typeof options?.brokerId === "string" && options?.brokerId !== "orderly" ? `?broker_id=${options?.brokerId}` : "";
2562
+ const url = `${dynamicBaseUrl || baseUrl || ""}${endpoint}${brokerIdQuery}`;
2563
+ const data = await fetcher(url, {}, { formatter });
2564
+ const dataWithBrokerId = data.map((item) => ({
2565
+ ...item,
2566
+ broker_id: options?.brokerId
2567
+ }));
2568
+ set({
2569
+ data: dataWithBrokerId,
2570
+ loading: false,
2571
+ error: null
2572
+ });
2573
+ return dataWithBrokerId;
2574
+ } catch (error) {
2575
+ set({ error, loading: false });
2576
+ return null;
2577
+ }
2578
+ }
2579
+ }),
2580
+ {
2581
+ name,
2582
+ indexedDBConfig: {
2583
+ dbName,
2584
+ storeName
2585
+ },
2586
+ //@ts-ignore
2587
+ partialize: (state) => state.data,
2588
+ merge: (persisted, current) => {
2589
+ return {
2590
+ ...current,
2591
+ data: persisted
2592
+ };
2593
+ }
2594
+ }
2595
+ )
2596
+ );
2597
+ };
2598
+
2599
+ // src/provider/store/chainInfoMainStore.ts
2600
+ var useMainnetChainsStore = createDataStore({
2601
+ name: "orderly-main-chain-info",
2602
+ dbName: "ORDERLY_STORE",
2603
+ storeName: ORDERLY_MAIN_CHAIN_INFO.name,
2604
+ keyPath: ORDERLY_MAIN_CHAIN_INFO.keyPath,
2605
+ endpoint: "/v1/public/chain_info",
2606
+ baseUrl: "https://api.orderly.org",
2607
+ initData: null
2608
+ });
2609
+ var testnetChainFallback = [ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo];
2610
+ var useTestnetChainsStore = createDataStore({
2611
+ name: "orderly-test-chain-info",
2612
+ dbName: "ORDERLY_STORE",
2613
+ storeName: ORDERLY_TEST_CHAIN_INFO.name,
2614
+ keyPath: ORDERLY_TEST_CHAIN_INFO.keyPath,
2615
+ endpoint: "/v1/public/chain_info",
2616
+ baseUrl: "https://testnet-api.orderly.org",
2617
+ initData: testnetChainFallback
2618
+ });
2619
+
2620
+ // src/provider/store/mainTokenStore.ts
2621
+ var useMainTokenStore = createDataStore({
2622
+ name: "orderly-main-token",
2623
+ dbName: "ORDERLY_STORE",
2624
+ storeName: ORDERLY_MAIN_TOKEN.name,
2625
+ keyPath: ORDERLY_MAIN_TOKEN.keyPath,
2626
+ endpoint: "/v1/public/token",
2627
+ baseUrl: "https://api.orderly.org"
2628
+ });
2629
+ var useSwapSupportStore = create()(
2630
+ persist(
2631
+ (set) => ({
2632
+ data: null,
2633
+ loading: false,
2634
+ error: null,
2635
+ fetchData: async () => {
2636
+ try {
2637
+ set({ loading: true, error: null });
2638
+ const res = await fetch("https://fi-api.woo.org/swap_support");
2639
+ const data = await res.json();
2640
+ if (data.status === "ok") {
2641
+ set({ data: data.data, loading: false, error: null });
2642
+ return data.data;
2643
+ }
2644
+ set((state) => ({
2645
+ data: state.data ?? {},
2646
+ error: new Error(data.message),
2647
+ loading: false
2648
+ }));
2649
+ return null;
2650
+ } catch (error) {
2651
+ set((state) => ({
2652
+ data: state.data ?? {},
2653
+ error,
2654
+ loading: false
2655
+ }));
2656
+ return null;
2657
+ }
2658
+ }
2659
+ }),
2660
+ {
2661
+ name: "orderly-swap-support",
2662
+ // Key for localStorage persistence
2663
+ partialize: (state) => ({ data: state.data })
2664
+ // Only persist data field
2665
+ }
2666
+ )
2667
+ );
2668
+
2669
+ // src/provider/store/symbolStore.ts
2670
+ var useSymbolStore = createDataStore({
2671
+ name: "orderly-main-symbols",
2672
+ dbName: "ORDERLY_STORE",
2673
+ storeName: ORDERLY_SYMBOLS.name,
2674
+ keyPath: ORDERLY_SYMBOLS.keyPath,
2675
+ endpoint: "/v1/public/info"
2676
+ });
2677
+ var testnetTokenFallback = TesnetTokenFallback([
2678
+ ArbitrumSepoliaTokenInfo,
2679
+ SolanaDevnetTokenInfo
2680
+ ]);
2681
+ var useTestTokenStore = createDataStore({
2682
+ name: "orderly-main-token",
2683
+ dbName: "ORDERLY_STORE",
2684
+ storeName: ORDERLY_TEST_TOKEN.name,
2685
+ keyPath: ORDERLY_TEST_TOKEN.keyPath,
2686
+ endpoint: "/v1/public/token",
2687
+ initData: testnetTokenFallback
2688
+ });
2689
+
2690
+ // src/usePreloadData.ts
2691
+ var usePreLoadData = () => {
2692
+ const [timestampOffsetInitialized, setTimestampOffsetInitialized] = useState(false);
2693
+ const { configStore, enableSwapDeposit } = useContext(OrderlyContext);
2694
+ const env = configStore.get("env");
2695
+ const apiBaseUrl = configStore.get("apiBaseUrl");
2696
+ const urlPrefix = env === "prod" ? "https://testnet-api.orderly.org" : configStore.get("apiBaseUrl");
2697
+ const fetchMainTokens = useMainTokenStore((state) => state.fetchData);
2698
+ const fetchTestTokens = useTestTokenStore((state) => state.fetchData);
2699
+ const fetchMainChains = useMainnetChainsStore((state) => state.fetchData);
2700
+ const fetchTestChains = useTestnetChainsStore((state) => state.fetchData);
2701
+ const fetchSymbols = useSymbolStore((state) => state.fetchData);
2702
+ const fetchSwapSupport = useSwapSupportStore((state) => state.fetchData);
2703
+ const setTokensInfo = useAppStore((state) => state.actions.setTokensInfo);
2704
+ const mainTokenInfo = useMainTokenStore((state) => state.data);
2705
+ const testTokenInfo = useTestTokenStore((state) => state.data);
2706
+ const swapSupportInfo = useSwapSupportStore((state) => state.data);
2707
+ useEffect(() => {
2708
+ fetchMainTokens();
2709
+ fetchSymbols(apiBaseUrl).then((symbols) => {
2710
+ });
2711
+ fetchMainChains(void 0, {
2712
+ brokerId: configStore.get("brokerId")
2713
+ });
2714
+ }, []);
2715
+ useEffect(() => {
2716
+ if (!urlPrefix)
2717
+ return;
2718
+ fetchTestTokens(urlPrefix);
2719
+ fetchTestChains(urlPrefix, {
2720
+ brokerId: configStore.get("brokerId")
2721
+ });
2722
+ }, [urlPrefix]);
2723
+ useEffect(() => {
2724
+ if (!mainTokenInfo || !testTokenInfo)
2725
+ return;
2726
+ setTokensInfo(env === "prod" ? mainTokenInfo : testTokenInfo);
2727
+ }, [mainTokenInfo, testTokenInfo]);
2728
+ useEffect(() => {
2729
+ if (swapSupportInfo || !enableSwapDeposit)
2730
+ return;
2731
+ fetchSwapSupport();
2732
+ }, [swapSupportInfo, enableSwapDeposit]);
2733
+ const { data: systemInfo } = useSWR__default(
2734
+ "/v1/public/system_info",
2735
+ async (url, init2) => {
2736
+ const data = await fetch(
2737
+ url.startsWith("http") ? url : `${apiBaseUrl}${url}`,
2738
+ init2
2739
+ );
2740
+ return await data.json();
2741
+ },
2742
+ {
2743
+ errorRetryCount: 3,
2744
+ errorRetryInterval: 500
2745
+ }
2746
+ );
2747
+ useEffect(() => {
2748
+ if (timestampOffsetInitialized)
2749
+ return;
2750
+ if (typeof systemInfo !== "undefined") {
2751
+ const serverTimestamp = systemInfo.timestamp;
2752
+ const localTimestamp = Date.now();
2753
+ const timestampOffset = serverTimestamp - localTimestamp;
2754
+ if (isNaN(timestampOffset)) {
2755
+ return;
2756
+ }
2757
+ getGlobalObject().__ORDERLY_timestamp_offset = timestampOffset;
2758
+ setTimestampOffsetInitialized(true);
2759
+ }
2760
+ }, [systemInfo, timestampOffsetInitialized]);
2761
+ const isDone = useMemo(() => {
2762
+ return timestampOffsetInitialized;
2763
+ }, [timestampOffsetInitialized]);
2764
+ return {
2765
+ error: null,
2766
+ done: isDone
2767
+ };
2768
+ };
2769
+ function useSessionStorage(key, initialValue) {
2770
+ const readValue = useCallback(() => {
2771
+ if (typeof window === "undefined") {
2772
+ return initialValue;
2773
+ }
2774
+ try {
2775
+ const item = window.sessionStorage.getItem(key);
2776
+ return item ? parseJSON(item) : initialValue;
2777
+ } catch (error) {
2778
+ return initialValue;
2779
+ }
2780
+ }, [initialValue, key]);
2781
+ const [storedValue, setStoredValue] = useState(readValue);
2782
+ const setValue = (value) => {
2783
+ try {
2784
+ const newValue = value instanceof Function ? value(storedValue) : value;
2785
+ window.sessionStorage.setItem(key, JSON.stringify(newValue));
2786
+ setStoredValue(newValue);
2787
+ } catch (error) {
2788
+ }
2789
+ };
2790
+ useEffect(() => {
2791
+ setStoredValue(readValue());
2792
+ }, []);
2793
+ useEffect(() => {
2794
+ if (typeof window == "undefined") {
2795
+ return;
2796
+ }
2797
+ window.addEventListener?.("storage", handleStorageChange);
2798
+ return () => {
2799
+ window.removeEventListener?.("storage", handleStorageChange);
2800
+ };
2801
+ });
2802
+ const handleStorageChange = useCallback(
2803
+ (event) => {
2804
+ if (event?.key && event.key !== key) {
2805
+ return;
2806
+ }
2807
+ setStoredValue(readValue());
2123
2808
  },
2124
2809
  [key, readValue]
2125
2810
  );
@@ -2142,7 +2827,7 @@ var useNetworkInfo = (networkId) => {
2142
2827
  };
2143
2828
 
2144
2829
  // src/orderly/useAccountInfo.ts
2145
- var useAccountInfo = () => {
2830
+ var useAccountInfo2 = () => {
2146
2831
  return usePrivateQuery("/v1/client/info", {
2147
2832
  revalidateOnFocus: false
2148
2833
  });
@@ -2160,7 +2845,7 @@ var computeEffectiveFromBps = (userBps, orderlyBps, rebate) => {
2160
2845
  return effective;
2161
2846
  };
2162
2847
  var useFeeState = () => {
2163
- const { data: accountInfo, isLoading: isAccountLoading } = useAccountInfo();
2848
+ const { data: accountInfo, isLoading: isAccountLoading } = useAccountInfo2();
2164
2849
  const { data: referralData, isLoading: isReferralLoading } = usePrivateQuery("/v1/referral/info", {
2165
2850
  revalidateOnFocus: true,
2166
2851
  errorRetryCount: 3,
@@ -2512,215 +3197,87 @@ var useMarketsStream = () => {
2512
3197
  });
2513
3198
  const topic = "tickers";
2514
3199
  const { data: tickers } = useSWRSubscription("tickers", (_, { next }) => {
2515
- const unsubscribe = ws.subscribe(
2516
- // { event: "subscribe", topic: "markprices" },
2517
- topic,
2518
- {
2519
- onMessage: (message) => {
2520
- next(null, message);
2521
- }
2522
- // onUnsubscribe: () => {
2523
- // return "markprices";
2524
- // },
2525
- // onError: (error: any) => {
2526
- //
2527
- // },
2528
- }
2529
- );
2530
- return () => {
2531
- unsubscribe?.();
2532
- };
2533
- });
2534
- const value = useMemo(() => {
2535
- if (!futures)
2536
- return null;
2537
- if (!tickers)
2538
- return futures;
2539
- return futures.map((item) => {
2540
- const ticker = tickers.find(
2541
- (t) => t.symbol === item.symbol
2542
- );
2543
- if (ticker) {
2544
- const data = {
2545
- ...item,
2546
- ["24h_close"]: ticker.close,
2547
- ["24h_open"]: ticker.open,
2548
- /**
2549
- * @deprecated
2550
- * spelling mistake, use 24h_volume to instead, will be remove next version
2551
- */
2552
- ["24h_volumn"]: ticker.volume,
2553
- ["24h_volume"]: ticker.volume,
2554
- ["24h_amount"]: ticker.amount,
2555
- change: 0
2556
- };
2557
- if (ticker.close !== void 0 && ticker.open !== void 0) {
2558
- data["change"] = new Decimal(ticker.close).minus(ticker.open).div(ticker.open).toNumber();
2559
- }
2560
- return data;
2561
- }
2562
- return item;
2563
- });
2564
- }, [futures, tickers]);
2565
- return { data: value };
2566
- };
2567
- function createGetter(data, depth = 2) {
2568
- const getValue = (value, defaultValue) => {
2569
- if (defaultValue === void 0) {
2570
- return value;
2571
- }
2572
- return value ?? defaultValue;
2573
- };
2574
- return new Proxy(data || {}, {
2575
- get(target, property, receiver) {
2576
- if (property === "isNil") {
2577
- return isNil(data);
2578
- }
2579
- if (depth === 1) {
2580
- return (defaultValue) => {
2581
- if (!target)
2582
- return defaultValue;
2583
- return getValue(target[property], defaultValue);
2584
- };
2585
- }
2586
- return (key, defaultValue) => {
2587
- if (key) {
2588
- return getValue(target[property]?.[key], defaultValue);
2589
- } else {
2590
- return getValue(target[property], defaultValue);
2591
- }
2592
- };
2593
- }
2594
- });
2595
- }
2596
- var useAppStore = create()(
2597
- immer((set) => ({
2598
- // accountInfo: null,
2599
- portfolio: {
2600
- totalCollateral: zero,
2601
- totalValue: null,
2602
- freeCollateral: zero,
2603
- availableBalance: 0,
2604
- unsettledPnL: 0,
2605
- totalUnrealizedROI: 0
2606
- },
2607
- appState: {
2608
- positionsLoading: false,
2609
- ordersLoading: false,
2610
- fundingRatesLoading: false,
2611
- ready: false
2612
- },
2613
- actions: {
2614
- cleanAll: () => {
2615
- set((state) => {
2616
- state.accountInfo = void 0;
2617
- state.portfolio = {
2618
- totalCollateral: zero,
2619
- totalValue: null,
2620
- freeCollateral: zero,
2621
- availableBalance: 0,
2622
- unsettledPnL: 0,
2623
- totalUnrealizedROI: 0
2624
- };
2625
- }, false);
2626
- },
2627
- setAccountInfo: (accountInfo) => {
2628
- set(
2629
- (state) => {
2630
- state.accountInfo = accountInfo;
2631
- },
2632
- false
2633
- // "setAccountInfo"
2634
- );
2635
- },
2636
- setSymbolsInfo: (symbolsInfo) => {
2637
- set(
2638
- (state) => {
2639
- state.symbolsInfo = symbolsInfo;
2640
- },
2641
- false
2642
- // "setSymbolsInfo"
2643
- );
2644
- },
2645
- setRwaSymbolsInfo: (rwaSymbolsInfo) => {
2646
- set(
2647
- (state) => {
2648
- state.rwaSymbolsInfo = rwaSymbolsInfo;
2649
- },
2650
- false
2651
- // "setRwaSymbolsInfo"
2652
- );
2653
- },
2654
- setFundingRates: (fundingRates) => {
2655
- set(
2656
- (state) => {
2657
- state.fundingRates = fundingRates;
2658
- },
2659
- false
2660
- // "setFundingRates"
2661
- );
2662
- },
2663
- updateAppStatus: (key, value) => {
2664
- set(
2665
- (state) => {
2666
- state.appState[key] = value;
2667
- },
2668
- false
2669
- // "updateAppStatus"
2670
- );
2671
- },
2672
- updatePortfolio: (key, value) => {
2673
- set(
2674
- (state) => {
2675
- state.portfolio[key] = value;
2676
- },
2677
- false
2678
- // "updatePortfolio"
2679
- );
2680
- },
2681
- batchUpdateForPortfolio: (data) => {
2682
- set(
2683
- (state) => {
2684
- state.portfolio = { ...state.portfolio, ...data };
2685
- },
2686
- false
2687
- // "batchUpdateForPortfolio"
2688
- );
2689
- },
2690
- restoreHolding: (holding) => {
2691
- set(
2692
- (state) => {
2693
- state.portfolio.holding = holding;
2694
- },
2695
- false
2696
- // "updateHolding"
2697
- );
2698
- },
2699
- updateHolding(msg) {
2700
- set(
2701
- (state) => {
2702
- if (state.portfolio.holding && state.portfolio.holding.length) {
2703
- for (const key in msg) {
2704
- const holding = state.portfolio.holding.find(
2705
- (item) => item.token === key
2706
- );
2707
- if (holding) {
2708
- holding.holding = msg[key].holding;
2709
- holding.frozen = msg[key].frozen;
2710
- }
2711
- }
2712
- }
2713
- },
2714
- false
2715
- // "updateHolding"
2716
- );
3200
+ const unsubscribe = ws.subscribe(
3201
+ // { event: "subscribe", topic: "markprices" },
3202
+ topic,
3203
+ {
3204
+ onMessage: (message) => {
3205
+ next(null, message);
3206
+ }
3207
+ // onUnsubscribe: () => {
3208
+ // return "markprices";
3209
+ // },
3210
+ // onError: (error: any) => {
3211
+ //
3212
+ // },
3213
+ }
3214
+ );
3215
+ return () => {
3216
+ unsubscribe?.();
3217
+ };
3218
+ });
3219
+ const value = useMemo(() => {
3220
+ if (!futures)
3221
+ return null;
3222
+ if (!tickers)
3223
+ return futures;
3224
+ return futures.map((item) => {
3225
+ const ticker = tickers.find(
3226
+ (t) => t.symbol === item.symbol
3227
+ );
3228
+ if (ticker) {
3229
+ const data = {
3230
+ ...item,
3231
+ ["24h_close"]: ticker.close,
3232
+ ["24h_open"]: ticker.open,
3233
+ /**
3234
+ * @deprecated
3235
+ * spelling mistake, use 24h_volume to instead, will be remove next version
3236
+ */
3237
+ ["24h_volumn"]: ticker.volume,
3238
+ ["24h_volume"]: ticker.volume,
3239
+ ["24h_amount"]: ticker.amount,
3240
+ change: 0
3241
+ };
3242
+ if (ticker.close !== void 0 && ticker.open !== void 0) {
3243
+ data["change"] = new Decimal(ticker.close).minus(ticker.open).div(ticker.open).toNumber();
3244
+ }
3245
+ return data;
2717
3246
  }
3247
+ return item;
3248
+ });
3249
+ }, [futures, tickers]);
3250
+ return { data: value };
3251
+ };
3252
+ function createGetter(data, depth = 2) {
3253
+ const getValue = (value, defaultValue) => {
3254
+ if (defaultValue === void 0) {
3255
+ return value;
2718
3256
  }
2719
- }))
2720
- );
2721
- var useAccountInfo2 = () => useAppStore((state) => state.accountInfo);
2722
- var usePortfolio = () => useAppStore((state) => state.portfolio);
2723
- var useFundingRateBySymbol = (symbol) => useAppStore((state) => state.fundingRates?.[symbol]);
3257
+ return value ?? defaultValue;
3258
+ };
3259
+ return new Proxy(data || {}, {
3260
+ get(target, property, receiver) {
3261
+ if (property === "isNil") {
3262
+ return isNil(data);
3263
+ }
3264
+ if (depth === 1) {
3265
+ return (defaultValue) => {
3266
+ if (!target)
3267
+ return defaultValue;
3268
+ return getValue(target[property], defaultValue);
3269
+ };
3270
+ }
3271
+ return (key, defaultValue) => {
3272
+ if (key) {
3273
+ return getValue(target[property]?.[key], defaultValue);
3274
+ } else {
3275
+ return getValue(target[property], defaultValue);
3276
+ }
3277
+ };
3278
+ }
3279
+ });
3280
+ }
2724
3281
 
2725
3282
  // src/orderly/useRwaSymbolsInfo.ts
2726
3283
  var isCurrentlyTrading = (nextClose, status, currentTime = Date.now()) => {
@@ -3402,9 +3959,15 @@ var orderbook_service_default = orderBookService;
3402
3959
  var useMarkPrice = (symbol) => {
3403
3960
  const ws = useWS();
3404
3961
  const [price, setPrice] = useState(0);
3962
+ const symbolRef = useRef(symbol);
3963
+ symbolRef.current = symbol;
3405
3964
  useEffect(() => {
3406
3965
  const unsubscribe = ws.subscribe(`${symbol}@markprice`, {
3407
3966
  onMessage: (message) => {
3967
+ if (message.symbol !== symbolRef.current) {
3968
+ unsubscribe?.();
3969
+ return;
3970
+ }
3408
3971
  setPrice(message.price);
3409
3972
  }
3410
3973
  });
@@ -3414,33 +3977,6 @@ var useMarkPrice = (symbol) => {
3414
3977
  }, [symbol]);
3415
3978
  return { data: price };
3416
3979
  };
3417
- var useIndexPrice = (symbol) => {
3418
- symbol = symbol.replace("PERP", "SPOT");
3419
- const ws = useWS();
3420
- return useSWRSubscription(`${symbol}@indexprice`, (key, { next }) => {
3421
- const unsubscribe = ws.subscribe(`${symbol}@indexprice`, {
3422
- onMessage: (message) => {
3423
- next(null, message.price);
3424
- }
3425
- });
3426
- return () => {
3427
- unsubscribe?.();
3428
- };
3429
- });
3430
- };
3431
- var useOpenInterest = (symbol) => {
3432
- const ws = useWS();
3433
- return useSWRSubscription(`${symbol}@openinterest`, (key, { next }) => {
3434
- const unsubscribe = ws.subscribe(`${symbol}@openinterest`, {
3435
- onMessage: (message) => {
3436
- next(null, message.openInterest);
3437
- }
3438
- });
3439
- return () => {
3440
- unsubscribe?.();
3441
- };
3442
- });
3443
- };
3444
3980
  var useFutures = () => {
3445
3981
  const { data, isLoading, error } = useQuery(
3446
3982
  `/v1/public/futures`,
@@ -3472,6 +4008,45 @@ var useFutures = () => {
3472
4008
  error
3473
4009
  };
3474
4010
  };
4011
+ var useIndexPrice = (symbol) => {
4012
+ symbol = symbol.replace("PERP", "SPOT");
4013
+ const symbolRef = useRef(symbol);
4014
+ symbolRef.current = symbol;
4015
+ const ws = useWS();
4016
+ return useSWRSubscription(`${symbol}@indexprice`, (key, { next }) => {
4017
+ const unsubscribe = ws.subscribe(`${symbol}@indexprice`, {
4018
+ onMessage: (message) => {
4019
+ if (message.symbol !== symbolRef.current) {
4020
+ unsubscribe?.();
4021
+ return;
4022
+ }
4023
+ next(null, message.price);
4024
+ }
4025
+ });
4026
+ return () => {
4027
+ unsubscribe?.();
4028
+ };
4029
+ });
4030
+ };
4031
+ var useOpenInterest = (symbol) => {
4032
+ const ws = useWS();
4033
+ const symbolRef = useRef(symbol);
4034
+ symbolRef.current = symbol;
4035
+ return useSWRSubscription(`${symbol}@openinterest`, (key, { next }) => {
4036
+ const unsubscribe = ws.subscribe(`${symbol}@openinterest`, {
4037
+ onMessage: (message) => {
4038
+ if (message.symbol !== symbolRef.current) {
4039
+ unsubscribe?.();
4040
+ return;
4041
+ }
4042
+ next(null, message.openInterest);
4043
+ }
4044
+ });
4045
+ return () => {
4046
+ unsubscribe?.();
4047
+ };
4048
+ });
4049
+ };
3475
4050
 
3476
4051
  // src/orderly/useTickerStream.ts
3477
4052
  var useTickerStream = (symbol) => {
@@ -3485,6 +4060,8 @@ var useTickerStream = (symbol) => {
3485
4060
  }
3486
4061
  );
3487
4062
  const [ticker, setTicker] = useState();
4063
+ const symbolRef = useRef(symbol);
4064
+ symbolRef.current = symbol;
3488
4065
  const ws = useWS();
3489
4066
  useEffect(() => {
3490
4067
  const unsubscribe = ws.subscribe(
@@ -3492,16 +4069,12 @@ var useTickerStream = (symbol) => {
3492
4069
  `${symbol}@ticker`,
3493
4070
  {
3494
4071
  onMessage: (message) => {
3495
- if (message.symbol !== symbol)
4072
+ if (message.symbol !== symbolRef.current) {
4073
+ unsubscribe?.();
3496
4074
  return;
4075
+ }
3497
4076
  setTicker(message);
3498
4077
  }
3499
- // onUnsubscribe: () => {
3500
- // return "markprices";
3501
- // },
3502
- // onError: (error: any) => {
3503
- //
3504
- // },
3505
4078
  }
3506
4079
  );
3507
4080
  return () => {
@@ -4200,31 +4773,11 @@ var useLeverage = () => {
4200
4773
  var useOdosQuote = () => {
4201
4774
  return useMutation(`https://api.odos.xyz/sor/quote/v2`);
4202
4775
  };
4203
- var useTokensInfoStore = create(
4204
- (set) => ({
4205
- tokensInfo: [],
4206
- setTokensInfo(data) {
4207
- set({ tokensInfo: data });
4208
- }
4209
- })
4210
- );
4211
- var useTokensInfo = () => {
4212
- const tokensInfo = useTokensInfoStore((state) => state.tokensInfo);
4213
- return tokensInfo;
4214
- };
4215
- var useTokenInfo = (token) => {
4216
- const tokensInfo = useTokensInfo();
4217
- return useMemo(() => {
4218
- return tokensInfo?.find((item) => item.token === token);
4219
- }, [tokensInfo, token]);
4220
- };
4221
-
4222
- // src/orderly/useComputedLTV.ts
4223
4776
  var { LTV, collateralRatio } = account;
4224
4777
  var useComputedLTV = (options = {}) => {
4225
4778
  const { input, token } = options;
4226
4779
  const isUSDC = token?.toUpperCase() === "USDC";
4227
- const tokensInfo = useTokensInfo();
4780
+ const tokensInfo = useAppStore((state) => state.tokensInfo);
4228
4781
  const { usdc, data: holdingList = [] } = useHoldingStream();
4229
4782
  const { getIndexPrice } = useIndexPricesStream();
4230
4783
  const { unsettledPnL } = useCollateral();
@@ -4476,7 +5029,7 @@ var CalculatorContext = class _CalculatorContext {
4476
5029
  this.accountInfo = useAppStore.getState().accountInfo;
4477
5030
  this.symbolsInfo = useAppStore.getState().symbolsInfo;
4478
5031
  this.fundingRates = useAppStore.getState().fundingRates;
4479
- this.tokensInfo = useTokensInfoStore.getState().tokensInfo;
5032
+ this.tokensInfo = useAppStore.getState().tokensInfo || [];
4480
5033
  }
4481
5034
  get(fn) {
4482
5035
  return fn(this.output);
@@ -5275,7 +5828,6 @@ var usePositionStream = (symbol = "all", options) => {
5275
5828
  ...rust,
5276
5829
  unrealized_pnl: unrealized_pnl_index ?? 0,
5277
5830
  unsettled_pnl_ROI: unrealized_pnl_ROI_index ?? 0
5278
- // mark_price: item.last_price,
5279
5831
  };
5280
5832
  });
5281
5833
  }
@@ -5287,9 +5839,6 @@ var usePositionStream = (symbol = "all", options) => {
5287
5839
  const partial_tp_sl = partialPossitionOrder ? findTPSLFromOrder(partialPossitionOrder) : void 0;
5288
5840
  return {
5289
5841
  ...item,
5290
- // tp_trigger_price: tp_sl_pricer?.tp_trigger_price,
5291
- // sl_trigger_price: tp_sl_pricer?.sl_trigger_price,
5292
- // algo_order: related_order,
5293
5842
  full_tp_sl: {
5294
5843
  tp_trigger_price: full_tp_sl?.tp_trigger_price,
5295
5844
  sl_trigger_price: full_tp_sl?.sl_trigger_price,
@@ -5300,7 +5849,6 @@ var usePositionStream = (symbol = "all", options) => {
5300
5849
  tp_trigger_price: partial_tp_sl?.tp_trigger_price,
5301
5850
  sl_trigger_price: partial_tp_sl?.sl_trigger_price,
5302
5851
  algo_order: partialPossitionOrder
5303
- // algo_order: partialPositionOrders,
5304
5852
  }
5305
5853
  };
5306
5854
  });
@@ -5313,11 +5861,14 @@ var usePositionStream = (symbol = "all", options) => {
5313
5861
  return [
5314
5862
  {
5315
5863
  rows,
5316
- // rows: formattedPositions[0],
5864
+ // Processed position rows with TP/SL data
5317
5865
  aggregated: formattedPositions?.[1] ?? EMPTY_OBJECT,
5318
5866
  totalCollateral,
5867
+ // Portfolio-wide collateral
5319
5868
  totalValue,
5869
+ // Total portfolio value
5320
5870
  totalUnrealizedROI
5871
+ // Total unrealized ROI across all positions
5321
5872
  },
5322
5873
  positionInfoGetter,
5323
5874
  {
@@ -5647,6 +6198,8 @@ var useMarketTradeStream = (symbol, options = {}) => {
5647
6198
  }
5648
6199
  const [trades, setTrades] = useState([]);
5649
6200
  const [isLoading, setIsLoading] = useState(false);
6201
+ const symbolRef = useRef(symbol);
6202
+ symbolRef.current = symbol;
5650
6203
  const { limit = 50 } = options;
5651
6204
  const ws = useWS();
5652
6205
  useEffect(() => {
@@ -5671,7 +6224,7 @@ var useMarketTradeStream = (symbol, options = {}) => {
5671
6224
  );
5672
6225
  }, [symbol]);
5673
6226
  useEffect(() => {
5674
- const unsubscript = ws.subscribe(
6227
+ const unsubscribe = ws.subscribe(
5675
6228
  {
5676
6229
  id: `${symbol}@trade`,
5677
6230
  event: "subscribe",
@@ -5680,6 +6233,10 @@ var useMarketTradeStream = (symbol, options = {}) => {
5680
6233
  },
5681
6234
  {
5682
6235
  onMessage: (data) => {
6236
+ if (data.symbol !== symbolRef.current) {
6237
+ unsubscribe?.();
6238
+ return;
6239
+ }
5683
6240
  setTrades((prev) => {
5684
6241
  const arr = [{ ...data, ts: getTimestamp() }, ...prev];
5685
6242
  if (arr.length > limit) {
@@ -5691,7 +6248,7 @@ var useMarketTradeStream = (symbol, options = {}) => {
5691
6248
  }
5692
6249
  );
5693
6250
  return () => {
5694
- unsubscript?.();
6251
+ unsubscribe?.();
5695
6252
  };
5696
6253
  }, [symbol]);
5697
6254
  return { data: trades, isLoading };
@@ -5755,7 +6312,7 @@ var useLeverageBySymbol = (symbol) => {
5755
6312
  // src/orderly/useMaxQty.ts
5756
6313
  var useMaxQty = (symbol, side, reduceOnly = false) => {
5757
6314
  const positions3 = usePositions();
5758
- const accountInfo = useAccountInfo2();
6315
+ const accountInfo = useAccountInfo();
5759
6316
  const symbolInfo = useSymbolsInfo();
5760
6317
  const { totalCollateral } = useCollateral();
5761
6318
  const { data: markPrices } = useMarkPricesStream();
@@ -5874,11 +6431,6 @@ var TestNetWhiteList = [
5874
6431
  ABSTRACT_TESTNET_CHAINID,
5875
6432
  BSC_TESTNET_CHAINID
5876
6433
  ];
5877
- var testnetTokenFallback = TesntTokenFallback([
5878
- ArbitrumSepoliaTokenInfo,
5879
- SolanaDevnetTokenInfo
5880
- ]);
5881
- var testnetChainFallback = [ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo];
5882
6434
  function useChains(networkId, options = {}) {
5883
6435
  const { pick: pickField, ...swrOptions } = options;
5884
6436
  const {
@@ -5890,47 +6442,16 @@ function useChains(networkId, options = {}) {
5890
6442
  const filterFun = useRef(options?.filter);
5891
6443
  filterFun.current = options?.filter;
5892
6444
  const chainsMap = useRef(/* @__PURE__ */ new Map());
5893
- const brokerId = configStore.get("brokerId");
5894
- const env = configStore.get("env");
5895
- const brokerIdQuery = brokerId !== "orderly" ? `?broker_id=${brokerId}` : "";
5896
- const urlPrefix = env === "prod" ? "https://testnet-api.orderly.org" : "";
5897
6445
  const needFetchFromAPI = options.forceAPI || !customChains;
5898
- const commonSwrOpts = {
5899
- revalidateIfStale: false,
5900
- revalidateOnFocus: false,
5901
- revalidateOnReconnect: false,
5902
- // If false, undefined data gets cached against the key.
5903
- revalidateOnMount: true,
5904
- // don't duplicate a request with the same key for 1hr
5905
- dedupingInterval: 36e5,
5906
- ...swrOptions
5907
- };
5908
- const { data: tokenChainsRes, error: tokenError } = useQuery(
5909
- "https://api.orderly.org/v1/public/token",
5910
- { ...commonSwrOpts }
5911
- );
5912
- const { data: testTokenChainsRes } = useQuery(
5913
- `${urlPrefix}/v1/public/token`,
5914
- {
5915
- ...commonSwrOpts,
5916
- fallbackData: testnetTokenFallback
5917
- }
5918
- );
5919
- const { data: chainInfos, error: chainInfoErr } = useQuery(
5920
- needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerIdQuery}` : null,
5921
- { ...commonSwrOpts }
5922
- );
5923
- const { data: testChainInfos, error: testChainInfoError } = useQuery(
5924
- needFetchFromAPI ? `${urlPrefix}/v1/public/chain_info${brokerIdQuery}` : null,
5925
- {
5926
- ...commonSwrOpts,
5927
- fallbackData: testnetChainFallback,
5928
- onError: (error) => {
5929
- }
5930
- }
5931
- );
6446
+ const { data: tokenChainsRes, error: tokenError } = useMainTokenStore();
6447
+ const testTokenChainsRes = useTestTokenStore((state) => state.data);
6448
+ const chainInfos = useMainnetChainsStore((state) => state.data);
6449
+ const testChainInfos = useTestnetChainsStore((state) => state.data);
5932
6450
  const { swapChains, swapChainsError } = useSwapChains();
5933
6451
  const chains = useMemo(() => {
6452
+ if (!tokenChainsRes || !testTokenChainsRes || !chainInfos || !testChainInfos) {
6453
+ return [];
6454
+ }
5934
6455
  const mainnetChains = formatChains({
5935
6456
  tokenChains: tokenChainsRes,
5936
6457
  chainInfos,
@@ -6038,19 +6559,7 @@ function filterByAllowedChains(chains, allowedChains) {
6038
6559
  }
6039
6560
  function useSwapChains() {
6040
6561
  const { enableSwapDeposit } = useContext(OrderlyContext);
6041
- const { data: swapChainsRes, error: swapChainsError } = useSWR__default(
6042
- () => enableSwapDeposit ? "https://fi-api.woo.org/swap_support" : null,
6043
- (url) => fetch(url).then((res) => res.json()),
6044
- {
6045
- revalidateIfStale: false,
6046
- revalidateOnFocus: false,
6047
- revalidateOnReconnect: false,
6048
- // If false, undefined data gets cached against the key.
6049
- revalidateOnMount: true,
6050
- // dont duplicate a request w/ same key for 1hr
6051
- dedupingInterval: 36e5
6052
- }
6053
- );
6562
+ const { data: swapChainsRes, error: swapChainsError } = useSwapSupportStore();
6054
6563
  const swapChains = useMemo(() => {
6055
6564
  if (!enableSwapDeposit || !swapChainsRes || !swapChainsRes.data) {
6056
6565
  return [];
@@ -6478,7 +6987,7 @@ var useDeposit = (options) => {
6478
6987
  [options.address]
6479
6988
  );
6480
6989
  const fetchBalanceHandler = useCallback(
6481
- async (address, decimals) => {
6990
+ async (address, decimals, token) => {
6482
6991
  let balance2;
6483
6992
  try {
6484
6993
  if (address && isNativeTokenChecker(address)) {
@@ -6492,7 +7001,8 @@ var useDeposit = (options) => {
6492
7001
  }
6493
7002
  } catch (err) {
6494
7003
  if (ignoreBalanceError({
6495
- token: options.srcToken,
7004
+ // TODO: use token params instead of options.srcToken
7005
+ token: token || options.srcToken,
6496
7006
  chainNamespace: account9.walletAdapter?.chainNamespace,
6497
7007
  err
6498
7008
  })) {
@@ -6507,16 +7017,17 @@ var useDeposit = (options) => {
6507
7017
  const fetchBalances = useCallback(async (tokens) => {
6508
7018
  const tasks = [];
6509
7019
  for (const token of tokens) {
6510
- if (isNativeTokenChecker(token.address)) {
6511
- continue;
6512
- }
6513
7020
  tasks.push(
6514
- account9.assetsManager.getBalance(token.address, {
6515
- decimals: token?.decimals
6516
- })
7021
+ fetchBalanceHandler(token.address, token?.decimals, token.symbol)
6517
7022
  );
6518
7023
  }
6519
- const balances = await Promise.all(tasks);
7024
+ const results = await Promise.allSettled(tasks);
7025
+ const balances = {};
7026
+ for (const [index, balance2] of results.entries()) {
7027
+ if (balance2.status === "fulfilled") {
7028
+ balances[tokens[index].symbol] = balance2.value;
7029
+ }
7030
+ }
6520
7031
  return balances;
6521
7032
  }, []);
6522
7033
  const getAllowance = async (inputs) => {
@@ -9516,7 +10027,7 @@ var useSubAccountDataObserver = (accountId) => {
9516
10027
  const { data: indexPrices } = useIndexPricesStream();
9517
10028
  const symbolsInfo = useSymbolsInfo();
9518
10029
  const fundingRates = useFundingRatesStore();
9519
- const tokensInfo = useTokensInfo();
10030
+ const tokensInfo = useAppStore((state) => state.tokensInfo);
9520
10031
  const [holding, setHolding] = useState([]);
9521
10032
  const [positions3, setPositions] = useState(
9522
10033
  POSITION_EMPTY
@@ -9671,7 +10182,9 @@ var useSubAccountDataObserver = (accountId) => {
9671
10182
  var { maxWithdrawalUSDC: maxWithdrawalUSDC2, maxWithdrawalOtherCollateral: maxWithdrawalOtherCollateral2, collateralRatio: collateralRatio3 } = account;
9672
10183
  function useSubAccountMaxWithdrawal(options) {
9673
10184
  const { token, unsettledPnL, freeCollateral, holdings } = options;
9674
- const tokenInfo = useTokenInfo(token);
10185
+ const tokenInfo = useAppStore(
10186
+ (state) => state.tokensInfo?.find((item) => item.token === token)
10187
+ );
9675
10188
  const { data: indexPrices } = useIndexPricesStream();
9676
10189
  const usdc = useMemo(() => {
9677
10190
  const usdc2 = holdings?.find((item) => item.token === "USDC");
@@ -10029,7 +10542,7 @@ var useTPSLOrder = (position, options) => {
10029
10542
  };
10030
10543
  var useMaxLeverage = (symbol) => {
10031
10544
  const symbolsInfo = useSymbolsInfo();
10032
- const accountInfo = useAccountInfo2();
10545
+ const accountInfo = useAccountInfo();
10033
10546
  const maxAccountLeverage = accountInfo?.max_leverage;
10034
10547
  const maxSymbolLeverage = useMemo(() => {
10035
10548
  const symbolInfo = symbolsInfo[symbol];
@@ -10398,6 +10911,16 @@ var useStorageLedgerAddress = () => {
10398
10911
  ledgerWallet
10399
10912
  };
10400
10913
  };
10914
+ var useTokensInfo = () => {
10915
+ const tokensInfo = useAppStore((state) => state.tokensInfo);
10916
+ return tokensInfo;
10917
+ };
10918
+ var useTokenInfo = (token) => {
10919
+ const tokensInfo = useAppStore((state) => state.tokensInfo);
10920
+ return useMemo(() => {
10921
+ return tokensInfo?.find((item) => item.token === token);
10922
+ }, [tokensInfo, token]);
10923
+ };
10401
10924
  var useMarketStore = create(
10402
10925
  (set, get3) => ({
10403
10926
  market: [],
@@ -10443,34 +10966,31 @@ var usePublicDataObserver = () => {
10443
10966
  (state) => state.actions
10444
10967
  );
10445
10968
  const { updateMarket } = useMarketStore((state) => state.actions);
10446
- const setTokensInfo = useTokensInfoStore((state) => state.setTokensInfo);
10969
+ const symbols = useSymbolStore((state) => state.data);
10447
10970
  const { dataAdapter } = useOrderlyContext();
10448
10971
  const resolveList = typeof dataAdapter?.symbolList === "function" ? dataAdapter.symbolList : (oriVal) => oriVal;
10449
- useQuery(`/v1/public/info`, {
10450
- ...publicQueryOptions,
10451
- onSuccess(data) {
10452
- if (!data || !data?.length) {
10453
- return {};
10454
- }
10455
- const obj = {};
10456
- for (let index = 0; index < data.length; index++) {
10457
- const item = data[index];
10458
- const arr = item.symbol.split("_");
10459
- const base_dp = getPrecisionByNumber(item.base_tick);
10460
- const quote_dp = getPrecisionByNumber(item.quote_tick);
10461
- obj[item.symbol] = {
10462
- ...item,
10463
- base_dp,
10464
- quote_dp,
10465
- base: arr[1],
10466
- quote: arr[2],
10467
- type: arr[0],
10468
- name: `${arr[1]}-${arr[0]}`
10469
- };
10470
- }
10471
- setSymbolsInfo(obj);
10972
+ useEffect(() => {
10973
+ if (!symbols || !symbols?.length) {
10974
+ return;
10472
10975
  }
10473
- });
10976
+ const obj = {};
10977
+ for (let index = 0; index < symbols.length; index++) {
10978
+ const item = symbols[index];
10979
+ const arr = item.symbol.split("_");
10980
+ const base_dp = getPrecisionByNumber(item.base_tick);
10981
+ const quote_dp = getPrecisionByNumber(item.quote_tick);
10982
+ obj[item.symbol] = {
10983
+ ...item,
10984
+ base_dp,
10985
+ quote_dp,
10986
+ base: arr[1],
10987
+ quote: arr[2],
10988
+ type: arr[0],
10989
+ name: `${arr[1]}-${arr[0]}`
10990
+ };
10991
+ }
10992
+ setSymbolsInfo(obj);
10993
+ }, [symbols]);
10474
10994
  useQuery(`/v1/public/rwa/info`, {
10475
10995
  ...publicQueryOptions,
10476
10996
  onSuccess(data) {
@@ -10526,16 +11046,6 @@ var usePublicDataObserver = () => {
10526
11046
  return resolveList(data);
10527
11047
  }
10528
11048
  });
10529
- useQuery(`/v1/public/token`, {
10530
- // revalidateOnFocus: false,
10531
- ...publicQueryOptions,
10532
- onSuccess(data) {
10533
- if (!data || !data.length) {
10534
- return [];
10535
- }
10536
- setTokensInfo(data);
10537
- }
10538
- });
10539
11049
  };
10540
11050
  function getEstFundingRate(data) {
10541
11051
  if (!data) {
@@ -10547,9 +11057,26 @@ function getEstFundingRate(data) {
10547
11057
  }
10548
11058
  return est_funding_rate;
10549
11059
  }
11060
+ var useDatabaseInitialization = () => {
11061
+ const [isInitialized, setIsInitialized] = useState(false);
11062
+ const [error, setError] = useState(null);
11063
+ useEffect(() => {
11064
+ const initialize = async () => {
11065
+ try {
11066
+ await initializeAppDatabase(DEFAULT_DATABASE_CONFIG);
11067
+ setIsInitialized(true);
11068
+ } catch (err) {
11069
+ setError(err);
11070
+ }
11071
+ };
11072
+ initialize();
11073
+ }, []);
11074
+ return { isInitialized, error };
11075
+ };
10550
11076
  var DataCenterProvider = ({
10551
11077
  children
10552
11078
  }) => {
11079
+ useDatabaseInitialization();
10553
11080
  const { error, done } = usePreLoadData();
10554
11081
  useInitRwaSymbolsRuntime();
10555
11082
  const calculatorService = useCalculatorService();
@@ -10574,9 +11101,6 @@ var DataCenterProvider = ({
10574
11101
  if (error) {
10575
11102
  return /* @__PURE__ */ jsx("div", { children: "Data load failed" });
10576
11103
  }
10577
- if (!done) {
10578
- return null;
10579
- }
10580
11104
  return /* @__PURE__ */ jsx(DataCenterContext.Provider, { value: memoizedValue, children });
10581
11105
  };
10582
11106
  var OrderlyConfigProvider = (props) => {
@@ -17304,7 +17828,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
17304
17828
  });
17305
17829
  const actions = useMarkPriceActions();
17306
17830
  const symbolConfig = useSymbolsInfo();
17307
- const accountInfo = useAccountInfo2();
17831
+ const accountInfo = useAccountInfo();
17308
17832
  const positions3 = usePositions();
17309
17833
  const symbolLeverage = useLeverageBySymbol(symbol);
17310
17834
  const symbolInfo = symbolConfig[symbol]();
@@ -18011,6 +18535,6 @@ var usePositionClose = (options) => {
18011
18535
  };
18012
18536
  };
18013
18537
 
18014
- export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, ORDERLY_ORDERBOOK_DEPTH_KEY, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, isCurrentlyClosed, isCurrentlyTrading, 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, useFundingRateBySymbol, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useGetRwaSymbolCloseTimeInterval, useGetRwaSymbolInfo, useGetRwaSymbolOpenStatus, useGetRwaSymbolOpenTimeInterval, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInitRwaSymbolsRuntime, 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, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useRwaSymbolsInfo, useRwaSymbolsInfoStore, 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, utils_exports as utils, version_default as version };
18538
+ export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, ORDERLY_ORDERBOOK_DEPTH_KEY, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, indexedDBManager, initializeAppDatabase, isCurrentlyClosed, isCurrentlyTrading, noCacheConfig, parseJSON, persistIndexedDB, resetTimestampOffsetState, timestampWaitingMiddleware, useAccount, useAccountInfo2 as 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, 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, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePortfolio, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, 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, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
18015
18539
  //# sourceMappingURL=out.js.map
18016
18540
  //# sourceMappingURL=index.mjs.map