@orderly.network/hooks 0.0.95 → 1.0.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.mjs CHANGED
@@ -1,40 +1,47 @@
1
- import React2, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
1
  import useSWR, { useSWRConfig } from 'swr';
3
2
  export { SWRConfig, default as useSWR } from 'swr';
4
3
  import { WS, get, mutate } from '@orderly.network/net';
4
+ import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
5
5
  import useSWRMutation from 'swr/mutation';
6
- import useConstant from 'use-constant';
6
+ import useConstant4 from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
- import { SimpleDI, Account, EventEmitter, utils } from '@orderly.network/core';
8
+ import { SimpleDI, Account, EventEmitter, MemoryConfigStore, LocalStorageStore, EtherAdapter, utils } from '@orderly.network/core';
9
9
  import { AccountStatusEnum, OrderStatus, OrderSide, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, WS_WalletStatusEnum, OrderType } from '@orderly.network/types';
10
10
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
11
11
  import useSWRSubscription from 'swr/subscription';
12
12
  import { pathOr, propOr, compose, head, prop, mergeDeepRight, pick, min } from 'ramda';
13
- import { positions, account, order } from '@orderly.network/futures';
13
+ import { positions, account, order } from '@orderly.network/perp';
14
14
  import useSWRInfinite from 'swr/infinite';
15
15
  export * from 'use-debounce';
16
16
  import { createClient } from '@layerzerolabs/scan-client';
17
17
 
18
- var __defProp = Object.defineProperty;
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, { get: all[name], enumerable: true });
22
- };
18
+ // src/useQuery.ts
19
+ var fetcher = (url, init = {}, queryOptions) => get(url, init, queryOptions?.formatter);
23
20
  var OrderlyContext = createContext({
24
21
  // configStore: new MemoryConfigStore(),
25
22
  });
26
23
  var OrderlyProvider = OrderlyContext.Provider;
27
- var fetcher = (url, init = {}, queryOptions) => get(url, init, queryOptions?.formatter);
24
+
25
+ // src/useConfig.ts
26
+ var useConfig = (key, defaultValue) => {
27
+ const { configStore } = useContext(OrderlyContext);
28
+ if (typeof key !== "undefined") {
29
+ if (typeof defaultValue !== "undefined") {
30
+ return configStore.getOr(key, defaultValue);
31
+ }
32
+ return configStore.get(key);
33
+ }
34
+ return configStore;
35
+ };
28
36
 
29
37
  // src/useQuery.ts
30
38
  var useQuery = (query, options) => {
31
- const { apiBaseUrl } = useContext(OrderlyContext);
39
+ const apiBaseUrl = useConfig("apiBaseUrl");
32
40
  const { formatter, ...swrOptions } = options || {};
33
41
  if (typeof apiBaseUrl === "undefined") {
34
- throw new Error("please add OrderlyProvider to your app");
42
+ throw new Error("please add OrderlyConfigProvider to your app");
35
43
  }
36
44
  return useSWR(
37
- // `${apiBaseUrl}${query}`,
38
45
  query,
39
46
  (url, init) => fetcher(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init, {
40
47
  formatter
@@ -43,10 +50,10 @@ var useQuery = (query, options) => {
43
50
  );
44
51
  };
45
52
  var useLazyQuery = (query, options) => {
46
- const { apiBaseUrl } = useContext(OrderlyContext);
53
+ const apiBaseUrl = useConfig("apiBaseUrl");
47
54
  const { formatter, init, ...swrOptions } = options || {};
48
55
  if (typeof apiBaseUrl === "undefined") {
49
- throw new Error("please add OrderlyProvider to your app");
56
+ throw new Error("please add OrderlyConfigProvider to your app");
50
57
  }
51
58
  return useSWRMutation(
52
59
  query,
@@ -66,7 +73,7 @@ var useLazyQuery = (query, options) => {
66
73
  );
67
74
  };
68
75
  var useAccountInstance = () => {
69
- const { configStore, keyStore, contractManager, getWalletAdapter } = useContext(OrderlyContext);
76
+ const { configStore, keyStore, getWalletAdapter } = useContext(OrderlyContext);
70
77
  if (!configStore)
71
78
  throw new Error("configStore is not defined, please use OrderlyProvider");
72
79
  if (!keyStore) {
@@ -74,13 +81,12 @@ var useAccountInstance = () => {
74
81
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
75
82
  );
76
83
  }
77
- const account5 = useConstant(() => {
84
+ const account5 = useConstant4(() => {
78
85
  let account6 = SimpleDI.get("account");
79
86
  if (!account6) {
80
87
  account6 = new Account(
81
88
  configStore,
82
89
  keyStore,
83
- contractManager,
84
90
  getWalletAdapter
85
91
  // walletAdapter
86
92
  );
@@ -109,7 +115,7 @@ var fetcher2 = (url, options) => {
109
115
  return mutate(url, init);
110
116
  };
111
117
  var useMutation = (url, method = "POST", options) => {
112
- const { apiBaseUrl } = useContext(OrderlyContext);
118
+ const apiBaseUrl = useConfig("apiBaseUrl");
113
119
  let fullUrl = url;
114
120
  if (!url.startsWith("http")) {
115
121
  fullUrl = `${apiBaseUrl}${url}`;
@@ -155,7 +161,7 @@ var useMutation = (url, method = "POST", options) => {
155
161
  ];
156
162
  };
157
163
  var signatureMiddleware = (useSWRNext) => {
158
- const { apiBaseUrl } = useContext(OrderlyContext);
164
+ const apiBaseUrl = useConfig("apiBaseUrl");
159
165
  return (key, fetcher3, config) => {
160
166
  try {
161
167
  const extendedFetcher = async (args) => {
@@ -168,6 +174,7 @@ var signatureMiddleware = (useSWRNext) => {
168
174
  url
169
175
  };
170
176
  const signature = await signer.sign(payload);
177
+ console.log("signature:", fullUrl);
171
178
  return fetcher3(fullUrl, {
172
179
  headers: {
173
180
  ...signature,
@@ -185,10 +192,10 @@ var signatureMiddleware = (useSWRNext) => {
185
192
  var useAccount = () => {
186
193
  const {
187
194
  configStore,
188
- keyStore,
189
- onWalletConnect,
190
- onWalletDisconnect,
191
- onSetChain
195
+ keyStore
196
+ // onWalletConnect,
197
+ // onWalletDisconnect,
198
+ // onSetChain,
192
199
  } = useContext(OrderlyContext);
193
200
  if (!configStore)
194
201
  throw new Error("configStore is not defined, please use OrderlyProvider");
@@ -217,26 +224,16 @@ var useAccount = () => {
217
224
  const createAccount = useCallback(async () => {
218
225
  return account5.createAccount();
219
226
  }, [account5]);
220
- const connect = useCallback(async () => {
221
- return onWalletConnect?.();
222
- }, [account5]);
223
- const disconnect = async () => {
224
- return onWalletDisconnect?.();
225
- };
226
- const setChain = async (chainId) => {
227
- return onSetChain?.(chainId);
228
- };
229
227
  return {
230
- // account: state!,
231
228
  account: account5,
232
229
  state,
233
230
  // info: {},
234
231
  // login,
235
232
  createOrderlyKey,
236
- createAccount,
237
- disconnect,
238
- connect,
239
- setChain
233
+ createAccount
234
+ // disconnect,
235
+ // connect,
236
+ // setChain,
240
237
  // settlement,
241
238
  };
242
239
  };
@@ -246,7 +243,6 @@ var usePrivateQuery = (query, options) => {
246
243
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
247
244
  return useSWR(
248
245
  () => account5.state.status >= AccountStatusEnum.EnableTrading ? [query, account5.state.accountId] : null,
249
- // query,
250
246
  (url, init) => {
251
247
  return fetcher(url, init, { formatter });
252
248
  },
@@ -265,28 +261,6 @@ var useBoolean = (initialValue = false) => {
265
261
  const toggle = useCallback(() => setValue((v) => !v), []);
266
262
  return [value, { setTrue, setFalse, toggle }];
267
263
  };
268
-
269
- // src/useTradingView.ts
270
- var useTradingView = () => {
271
- return {};
272
- };
273
- var useTopicObserve = (topic) => {
274
- const [data, setData] = useState();
275
- useEffect(() => {
276
- return () => {
277
- };
278
- }, []);
279
- return {
280
- data
281
- };
282
- };
283
- var useAppState = () => {
284
- const { errors } = useContext(OrderlyContext);
285
- return {
286
- errors
287
- // ready,
288
- };
289
- };
290
264
  var usePreLoadData = () => {
291
265
  const { configStore } = useContext(OrderlyContext);
292
266
  const { error: swapSupportError, data: swapSupportData } = useSWR(
@@ -307,8 +281,8 @@ var usePreLoadData = () => {
307
281
  done: isDone
308
282
  };
309
283
  };
310
- var useEventEmitter = (channel) => {
311
- return useConstant(() => {
284
+ var useEventEmitter = () => {
285
+ return useConstant4(() => {
312
286
  let ee = SimpleDI.get("EE");
313
287
  if (!ee) {
314
288
  ee = new EventEmitter();
@@ -415,32 +389,10 @@ function useLocalStorage(key, initialValue) {
415
389
  }, []);
416
390
  return [storedValue, setValue];
417
391
  }
418
- var useRunOnce = ({ fn, sessionKey }) => {
419
- const triggered = useRef(false);
420
- useEffect(() => {
421
- const hasBeenTriggered = sessionKey ? sessionStorage.getItem(sessionKey) : triggered.current;
422
- if (!hasBeenTriggered) {
423
- fn();
424
- triggered.current = true;
425
- if (sessionKey) {
426
- sessionStorage.setItem(sessionKey, "true");
427
- }
428
- }
429
- }, [fn, sessionKey]);
430
- return null;
431
- };
432
- var DataSourceContext = createContext({});
433
- var DataSourceProvider = (props) => {
434
- useAccountInstance();
435
- useConstant(() => {
436
- });
437
- return /* @__PURE__ */ React2.createElement(DataSourceContext.Provider, { value: {} }, props.children);
438
- };
439
392
  var WS_NAME = "nativeWebsocketClient";
440
393
  var useWS = () => {
441
- useAccount();
442
394
  const { configStore } = useContext(OrderlyContext);
443
- const ws = useConstant(() => {
395
+ const ws = useConstant4(() => {
444
396
  let websocketClient = SimpleDI.get(WS_NAME);
445
397
  const account5 = SimpleDI.get(Account.instanceName);
446
398
  if (!websocketClient) {
@@ -467,9 +419,44 @@ var useWS = () => {
467
419
  });
468
420
  return ws;
469
421
  };
470
- var useConfig = () => {
471
- const { configStore } = useContext(OrderlyContext);
472
- return configStore;
422
+ var OrderlyConfigProvider = (props) => {
423
+ const { configStore, keyStore, getWalletAdapter, brokerId, networkId } = props;
424
+ if (!brokerId && typeof configStore === "undefined") {
425
+ console.error("[OrderlyConfigProvider]: brokerId is required");
426
+ }
427
+ const innerConfigStore = useConstant4(() => {
428
+ return configStore || new MemoryConfigStore({ brokerId });
429
+ });
430
+ const innerKeyStore = useConstant4(() => {
431
+ return keyStore || new LocalStorageStore(networkId);
432
+ });
433
+ const innerGetWalletAdapter = useConstant4(() => {
434
+ return getWalletAdapter || ((options) => new EtherAdapter(options));
435
+ });
436
+ useEffect(() => {
437
+ let account5 = SimpleDI.get(Account.instanceName);
438
+ if (!account5) {
439
+ account5 = new Account(
440
+ innerConfigStore,
441
+ innerKeyStore,
442
+ innerGetWalletAdapter
443
+ );
444
+ SimpleDI.registerByName(Account.instanceName, account5);
445
+ }
446
+ }, []);
447
+ return /* @__PURE__ */ React.createElement(
448
+ OrderlyProvider,
449
+ {
450
+ value: {
451
+ configStore: innerConfigStore,
452
+ keyStore: innerKeyStore,
453
+ getWalletAdapter: innerGetWalletAdapter,
454
+ networkId
455
+ // apiBaseUrl,
456
+ }
457
+ },
458
+ props.children
459
+ );
473
460
  };
474
461
  var useMarkPrice = (symbol) => {
475
462
  const ws = useWS();
@@ -1305,12 +1292,8 @@ var usePrivateInfiniteQuery = (getKey, options) => {
1305
1292
  );
1306
1293
  return result;
1307
1294
  };
1308
- var useOrderStream = ({
1309
- status,
1310
- symbol,
1311
- side,
1312
- size = 100
1313
- } = {}) => {
1295
+ var useOrderStream = (params) => {
1296
+ const { status, symbol, side, size = 100 } = params;
1314
1297
  const ws = useWS();
1315
1298
  const { data: markPrices = {} } = useMarkPricesStream();
1316
1299
  const [doCancelOrder] = useMutation("/v1/order", "DELETE");
@@ -1465,7 +1448,6 @@ function rePageData(list, total, pageSize) {
1465
1448
  rows = [];
1466
1449
  }
1467
1450
  }
1468
- console.log("rePageData", list, total, newData);
1469
1451
  return newData;
1470
1452
  }
1471
1453
  function editPageData(list, newOrder) {
@@ -1855,65 +1837,11 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1855
1837
  symbolConfig: symbolInfo[symbol]()
1856
1838
  };
1857
1839
  };
1858
- var useFetures = () => {
1859
- const { data, isLoading, error } = useQuery(
1860
- `/v1/public/futures`,
1861
- {
1862
- revalidateOnFocus: false
1863
- }
1864
- );
1865
- const [sortedData, setSortedData] = useState(data);
1866
- useWS();
1867
- useEffect(() => {
1868
- }, []);
1869
- useEffect(() => {
1870
- if (data) {
1871
- const sortedData2 = data.sort((a, b) => {
1872
- return 0;
1873
- });
1874
- setSortedData(sortedData2);
1875
- }
1876
- }, [data]);
1877
- const sortBy = useCallback((key) => {
1878
- }, [data]);
1879
- const filterBy = useCallback((key) => {
1880
- }, [data]);
1881
- return {
1882
- // ...data,
1883
- data: sortedData,
1884
- sortBy,
1885
- filterBy,
1886
- isLoading,
1887
- error
1888
- };
1889
- };
1890
1840
 
1891
1841
  // src/orderly/useAccountInfo.ts
1892
1842
  var useAccountInfo = () => {
1893
1843
  return usePrivateQuery("/v1/client/info");
1894
1844
  };
1895
-
1896
- // src/orderly/useTokenInfo.ts
1897
- var useTokenInfo = () => {
1898
- const { data = {} } = useQuery(
1899
- "/v1/public/token",
1900
- {
1901
- focusThrottleInterval: 1e3 * 60 * 60 * 24,
1902
- revalidateOnFocus: false,
1903
- formatter(data2) {
1904
- if (!data2?.rows || !data2?.rows?.length) {
1905
- return {};
1906
- }
1907
- const obj = /* @__PURE__ */ Object.create(null);
1908
- for (let index = 0; index < data2.rows.length; index++) {
1909
- data2.rows[index];
1910
- }
1911
- return obj;
1912
- }
1913
- }
1914
- );
1915
- return createGetter(data);
1916
- };
1917
1845
  var useMarketsStream = () => {
1918
1846
  const ws = useWS();
1919
1847
  const { data: futures } = useQuery(`/v1/public/futures`, {
@@ -2031,7 +1959,6 @@ var useMarketTradeStream = (symbol, options = {}) => {
2031
1959
  }
2032
1960
  const [trades, setTrades] = useState([]);
2033
1961
  const [isLoading, setIsLoading] = useState(false);
2034
- useState(() => symbol);
2035
1962
  const { limit = 50 } = options;
2036
1963
  const ws = useWS();
2037
1964
  useEffect(() => {
@@ -3119,9 +3046,9 @@ var isNativeTokenChecker = (address) => address === nativeTokenAddress;
3119
3046
  // src/orderly/useChains.ts
3120
3047
  var useChains = (networkId, options = {}) => {
3121
3048
  const { filter, pick: pick3, crossEnabled, wooSwapEnabled, ...swrOptions } = options;
3122
- const { configStore, networkId: envNetworkId } = useContext(OrderlyContext);
3049
+ const { configStore } = useContext(OrderlyContext);
3123
3050
  const field = options?.pick;
3124
- const map2 = useRef(
3051
+ const map = useRef(
3125
3052
  /* @__PURE__ */ new Map()
3126
3053
  );
3127
3054
  const { data, error: swapSupportError } = useSWR(
@@ -3179,7 +3106,7 @@ var useChains = (networkId, options = {}) => {
3179
3106
  if (!options.filter(_chain))
3180
3107
  return;
3181
3108
  }
3182
- map2.current.set(chainId, _chain);
3109
+ map.current.set(chainId, _chain);
3183
3110
  orderlyChainsArr.push(_chain);
3184
3111
  });
3185
3112
  });
@@ -3228,7 +3155,7 @@ var useChains = (networkId, options = {}) => {
3228
3155
  });
3229
3156
  if (item.token_infos?.length === 0)
3230
3157
  return;
3231
- map2.current.set(item.network_infos.chain_id, item);
3158
+ map.current.set(item.network_infos.chain_id, item);
3232
3159
  if (typeof options?.filter === "function") {
3233
3160
  if (!options.filter(item))
3234
3161
  return;
@@ -3263,7 +3190,7 @@ var useChains = (networkId, options = {}) => {
3263
3190
  }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
3264
3191
  const findByChainId = useCallback(
3265
3192
  (chainId, field2) => {
3266
- const chain = map2.current.get(chainId);
3193
+ const chain = map.current.get(chainId);
3267
3194
  if (chain) {
3268
3195
  chain.nativeToken = chain.token_infos?.find(
3269
3196
  (item) => item.address === nativeTokenAddress
@@ -3274,7 +3201,7 @@ var useChains = (networkId, options = {}) => {
3274
3201
  }
3275
3202
  return chain;
3276
3203
  },
3277
- [chains, map2.current]
3204
+ [chains, map.current]
3278
3205
  );
3279
3206
  return [
3280
3207
  chains,
@@ -3529,7 +3456,7 @@ var useWalletSubscription = (options) => {
3529
3456
  {
3530
3457
  onMessage: (data) => {
3531
3458
  options?.onMessage?.(data);
3532
- next(data);
3459
+ next(null, data);
3533
3460
  }
3534
3461
  }
3535
3462
  );
@@ -3556,17 +3483,6 @@ var useSettleSubscription = (options) => {
3556
3483
  return () => unsubscribe();
3557
3484
  });
3558
3485
  };
3559
- var useBalance = () => {
3560
- const ws = useWS();
3561
- const { data } = useSWRSubscription("balance", (_, { next }) => {
3562
- const unsubscribe = ws.privateSubscribe("balance", {
3563
- onMessage: (data2) => {
3564
- }
3565
- });
3566
- return () => unsubscribe();
3567
- });
3568
- return data;
3569
- };
3570
3486
  var usePrivateDataObserver = () => {
3571
3487
  const ws = useWS();
3572
3488
  const { mutate: mutate2 } = useSWRConfig();
@@ -3620,34 +3536,6 @@ var usePrivateDataObserver = () => {
3620
3536
  };
3621
3537
  }, [state.accountId]);
3622
3538
  };
3623
-
3624
- // src/apis/index.ts
3625
- var apis_exports = {};
3626
- __export(apis_exports, {
3627
- useFundingRateBySymbol: () => useFundingRateBySymbol,
3628
- useInfo: () => useInfo,
3629
- useToken: () => useToken
3630
- });
3631
-
3632
- // src/apis/useInfo.ts
3633
- var useInfo = () => {
3634
- return useQuery("/v1/public/info", {
3635
- // refreshInterval: 1000 * 60 * 60 * 24,
3636
- });
3637
- };
3638
-
3639
- // src/apis/useToken.ts
3640
- var useToken = () => {
3641
- return useQuery("/v1/public/token");
3642
- };
3643
-
3644
- // src/apis/useFundingRateBySymbol.ts
3645
- var useFundingRateBySymbol = (symbol) => {
3646
- if (!symbol) {
3647
- throw new Error("symbol is required");
3648
- }
3649
- return useQuery(`/public/funding_rate/${symbol}`);
3650
- };
3651
3539
  var useWooSwapQuery = () => {
3652
3540
  const { configStore } = useContext(OrderlyContext);
3653
3541
  const account5 = useAccountInstance();
@@ -3791,7 +3679,8 @@ var useCrossSwap = () => {
3791
3679
  );
3792
3680
  const txHashFromBridge = useRef();
3793
3681
  const account5 = useAccountInstance();
3794
- const { networkId, configStore } = useContext(OrderlyContext);
3682
+ const { configStore } = useContext(OrderlyContext);
3683
+ const networkId = useConfig("networkId");
3795
3684
  const client = useRef(createClient(networkId)).current;
3796
3685
  const timer = useRef();
3797
3686
  useEffect(() => {
@@ -4249,6 +4138,6 @@ var useSwap = () => {
4249
4138
  };
4250
4139
  };
4251
4140
 
4252
- export { DataSourceProvider, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useFetures, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOpenInterest, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4141
+ export { OrderlyConfigProvider, OrderlyContext, OrderlyProvider, useAccount, useAccountInfo, useAccountInstance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateQuery, useQuery, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useWS, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4253
4142
  //# sourceMappingURL=out.js.map
4254
4143
  //# sourceMappingURL=index.mjs.map