@orderly.network/hooks 0.0.95 → 1.0.1

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,49 @@ 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 [account5, setAccount] = React.useState(null);
424
+ const { configStore, keyStore, getWalletAdapter, brokerId, networkId } = props;
425
+ if (!brokerId && typeof configStore === "undefined") {
426
+ console.error("[OrderlyConfigProvider]: brokerId is required");
427
+ }
428
+ const innerConfigStore = useConstant4(() => {
429
+ return configStore || new MemoryConfigStore({ brokerId });
430
+ });
431
+ const innerKeyStore = useConstant4(() => {
432
+ return keyStore || new LocalStorageStore(networkId);
433
+ });
434
+ const innerGetWalletAdapter = useConstant4(() => {
435
+ return getWalletAdapter || ((options) => new EtherAdapter(options));
436
+ });
437
+ useEffect(() => {
438
+ let account6 = SimpleDI.get(Account.instanceName);
439
+ if (!account6) {
440
+ account6 = new Account(
441
+ innerConfigStore,
442
+ innerKeyStore,
443
+ innerGetWalletAdapter
444
+ );
445
+ SimpleDI.registerByName(Account.instanceName, account6);
446
+ }
447
+ setAccount(account6);
448
+ }, []);
449
+ if (!account5) {
450
+ return null;
451
+ }
452
+ return /* @__PURE__ */ React.createElement(
453
+ OrderlyProvider,
454
+ {
455
+ value: {
456
+ configStore: innerConfigStore,
457
+ keyStore: innerKeyStore,
458
+ getWalletAdapter: innerGetWalletAdapter,
459
+ networkId
460
+ // apiBaseUrl,
461
+ }
462
+ },
463
+ props.children
464
+ );
473
465
  };
474
466
  var useMarkPrice = (symbol) => {
475
467
  const ws = useWS();
@@ -1305,12 +1297,8 @@ var usePrivateInfiniteQuery = (getKey, options) => {
1305
1297
  );
1306
1298
  return result;
1307
1299
  };
1308
- var useOrderStream = ({
1309
- status,
1310
- symbol,
1311
- side,
1312
- size = 100
1313
- } = {}) => {
1300
+ var useOrderStream = (params) => {
1301
+ const { status, symbol, side, size = 100 } = params;
1314
1302
  const ws = useWS();
1315
1303
  const { data: markPrices = {} } = useMarkPricesStream();
1316
1304
  const [doCancelOrder] = useMutation("/v1/order", "DELETE");
@@ -1465,7 +1453,6 @@ function rePageData(list, total, pageSize) {
1465
1453
  rows = [];
1466
1454
  }
1467
1455
  }
1468
- console.log("rePageData", list, total, newData);
1469
1456
  return newData;
1470
1457
  }
1471
1458
  function editPageData(list, newOrder) {
@@ -1855,65 +1842,11 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1855
1842
  symbolConfig: symbolInfo[symbol]()
1856
1843
  };
1857
1844
  };
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
1845
 
1891
1846
  // src/orderly/useAccountInfo.ts
1892
1847
  var useAccountInfo = () => {
1893
1848
  return usePrivateQuery("/v1/client/info");
1894
1849
  };
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
1850
  var useMarketsStream = () => {
1918
1851
  const ws = useWS();
1919
1852
  const { data: futures } = useQuery(`/v1/public/futures`, {
@@ -2031,7 +1964,6 @@ var useMarketTradeStream = (symbol, options = {}) => {
2031
1964
  }
2032
1965
  const [trades, setTrades] = useState([]);
2033
1966
  const [isLoading, setIsLoading] = useState(false);
2034
- useState(() => symbol);
2035
1967
  const { limit = 50 } = options;
2036
1968
  const ws = useWS();
2037
1969
  useEffect(() => {
@@ -3119,9 +3051,9 @@ var isNativeTokenChecker = (address) => address === nativeTokenAddress;
3119
3051
  // src/orderly/useChains.ts
3120
3052
  var useChains = (networkId, options = {}) => {
3121
3053
  const { filter, pick: pick3, crossEnabled, wooSwapEnabled, ...swrOptions } = options;
3122
- const { configStore, networkId: envNetworkId } = useContext(OrderlyContext);
3054
+ const { configStore } = useContext(OrderlyContext);
3123
3055
  const field = options?.pick;
3124
- const map2 = useRef(
3056
+ const map = useRef(
3125
3057
  /* @__PURE__ */ new Map()
3126
3058
  );
3127
3059
  const { data, error: swapSupportError } = useSWR(
@@ -3179,7 +3111,7 @@ var useChains = (networkId, options = {}) => {
3179
3111
  if (!options.filter(_chain))
3180
3112
  return;
3181
3113
  }
3182
- map2.current.set(chainId, _chain);
3114
+ map.current.set(chainId, _chain);
3183
3115
  orderlyChainsArr.push(_chain);
3184
3116
  });
3185
3117
  });
@@ -3228,7 +3160,7 @@ var useChains = (networkId, options = {}) => {
3228
3160
  });
3229
3161
  if (item.token_infos?.length === 0)
3230
3162
  return;
3231
- map2.current.set(item.network_infos.chain_id, item);
3163
+ map.current.set(item.network_infos.chain_id, item);
3232
3164
  if (typeof options?.filter === "function") {
3233
3165
  if (!options.filter(item))
3234
3166
  return;
@@ -3263,7 +3195,7 @@ var useChains = (networkId, options = {}) => {
3263
3195
  }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
3264
3196
  const findByChainId = useCallback(
3265
3197
  (chainId, field2) => {
3266
- const chain = map2.current.get(chainId);
3198
+ const chain = map.current.get(chainId);
3267
3199
  if (chain) {
3268
3200
  chain.nativeToken = chain.token_infos?.find(
3269
3201
  (item) => item.address === nativeTokenAddress
@@ -3274,7 +3206,7 @@ var useChains = (networkId, options = {}) => {
3274
3206
  }
3275
3207
  return chain;
3276
3208
  },
3277
- [chains, map2.current]
3209
+ [chains, map.current]
3278
3210
  );
3279
3211
  return [
3280
3212
  chains,
@@ -3529,7 +3461,7 @@ var useWalletSubscription = (options) => {
3529
3461
  {
3530
3462
  onMessage: (data) => {
3531
3463
  options?.onMessage?.(data);
3532
- next(data);
3464
+ next(null, data);
3533
3465
  }
3534
3466
  }
3535
3467
  );
@@ -3556,17 +3488,6 @@ var useSettleSubscription = (options) => {
3556
3488
  return () => unsubscribe();
3557
3489
  });
3558
3490
  };
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
3491
  var usePrivateDataObserver = () => {
3571
3492
  const ws = useWS();
3572
3493
  const { mutate: mutate2 } = useSWRConfig();
@@ -3620,34 +3541,6 @@ var usePrivateDataObserver = () => {
3620
3541
  };
3621
3542
  }, [state.accountId]);
3622
3543
  };
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
3544
  var useWooSwapQuery = () => {
3652
3545
  const { configStore } = useContext(OrderlyContext);
3653
3546
  const account5 = useAccountInstance();
@@ -3791,7 +3684,8 @@ var useCrossSwap = () => {
3791
3684
  );
3792
3685
  const txHashFromBridge = useRef();
3793
3686
  const account5 = useAccountInstance();
3794
- const { networkId, configStore } = useContext(OrderlyContext);
3687
+ const { configStore } = useContext(OrderlyContext);
3688
+ const networkId = useConfig("networkId");
3795
3689
  const client = useRef(createClient(networkId)).current;
3796
3690
  const timer = useRef();
3797
3691
  useEffect(() => {
@@ -4249,6 +4143,6 @@ var useSwap = () => {
4249
4143
  };
4250
4144
  };
4251
4145
 
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 };
4146
+ 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
4147
  //# sourceMappingURL=out.js.map
4254
4148
  //# sourceMappingURL=index.mjs.map