@orderly.network/hooks 0.0.18 → 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,12 @@
1
1
  'use strict';
2
2
 
3
- var React = require('react');
3
+ var React2 = require('react');
4
4
  var useSWR = require('swr');
5
5
  var net = require('@orderly.network/net');
6
6
  var useSWRMutation = require('swr/mutation');
7
7
  var useConstant = require('use-constant');
8
8
  var core = require('@orderly.network/core');
9
9
  var types = require('@orderly.network/types');
10
- var rxjs = require('rxjs');
11
10
  var useSWRSubscription = require('swr/subscription');
12
11
  var utils = require('@orderly.network/utils');
13
12
  var ramda = require('ramda');
@@ -16,7 +15,7 @@ var useSWRInfinite = require('swr/infinite');
16
15
 
17
16
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
17
 
19
- var React__default = /*#__PURE__*/_interopDefault(React);
18
+ var React2__default = /*#__PURE__*/_interopDefault(React2);
20
19
  var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);
21
20
  var useSWRMutation__default = /*#__PURE__*/_interopDefault(useSWRMutation);
22
21
  var useConstant__default = /*#__PURE__*/_interopDefault(useConstant);
@@ -78,7 +77,7 @@ var __async = (__this, __arguments, generator) => {
78
77
  step((generator = generator.apply(__this, __arguments)).next());
79
78
  });
80
79
  };
81
- var OrderlyContext = React.createContext({
80
+ var OrderlyContext = React2.createContext({
82
81
  // configStore: new MemoryConfigStore(),
83
82
  });
84
83
  var OrderlyProvider = OrderlyContext.Provider;
@@ -86,7 +85,7 @@ var fetcher = (url, init = {}, queryOptions) => net.get(url, init, queryOptions
86
85
 
87
86
  // src/useQuery.ts
88
87
  var useQuery = (query, options) => {
89
- const { apiBaseUrl } = React.useContext(OrderlyContext);
88
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
90
89
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
91
90
  if (typeof apiBaseUrl === "undefined") {
92
91
  throw new Error("please add OrderlyProvider to your app");
@@ -99,7 +98,7 @@ var useQuery = (query, options) => {
99
98
  );
100
99
  };
101
100
  var useAccountInstance = () => {
102
- const { configStore, keyStore, walletAdapter } = React.useContext(OrderlyContext);
101
+ const { configStore, keyStore, walletAdapter } = React2.useContext(OrderlyContext);
103
102
  if (!configStore)
104
103
  throw new Error("configStore is not defined, please use OrderlyProvider");
105
104
  if (!keyStore) {
@@ -107,20 +106,19 @@ var useAccountInstance = () => {
107
106
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
108
107
  );
109
108
  }
110
- const account4 = useConstant__default.default(() => {
111
- let account5 = core.SimpleDI.get("account");
112
- if (!account5) {
113
- account5 = new core.Account(configStore, keyStore, walletAdapter);
114
- core.SimpleDI.registerByName("account", account5);
109
+ const account5 = useConstant__default.default(() => {
110
+ let account6 = core.SimpleDI.get("account");
111
+ if (!account6) {
112
+ account6 = new core.Account(configStore, keyStore, walletAdapter);
113
+ core.SimpleDI.registerByName("account", account6);
115
114
  }
116
- return account5;
115
+ return account6;
117
116
  });
118
- return account4;
117
+ return account5;
119
118
  };
120
119
 
121
120
  // src/useMutation.ts
122
121
  var fetcher2 = (url, options) => {
123
- console.log("muation fetcher", url, options);
124
122
  const init = {
125
123
  method: options.arg.method,
126
124
  headers: __spreadValues({}, options.arg.signature)
@@ -135,13 +133,13 @@ var fetcher2 = (url, options) => {
135
133
  return net.mutate(url, init);
136
134
  };
137
135
  var useMutation = (url, method = "POST", options) => {
138
- const { apiBaseUrl } = React.useContext(OrderlyContext);
136
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
139
137
  let fullUrl = url;
140
138
  if (!url.startsWith("http")) {
141
139
  fullUrl = `${apiBaseUrl}${url}`;
142
140
  }
143
- const account4 = useAccountInstance();
144
- const signer = account4.signer;
141
+ const account5 = useAccountInstance();
142
+ const signer = account5.signer;
145
143
  const { trigger, data, error, reset, isMutating } = useSWRMutation__default.default(
146
144
  fullUrl,
147
145
  // method === "POST" ? fetcher : deleteFetcher,
@@ -159,14 +157,13 @@ var useMutation = (url, method = "POST", options) => {
159
157
  url: newUrl,
160
158
  data: data2
161
159
  };
162
- console.log("payload", payload);
163
160
  const signature = yield signer.sign(payload);
164
161
  return trigger({
165
162
  data: data2,
166
163
  params,
167
164
  method,
168
165
  signature: __spreadProps(__spreadValues({}, signature), {
169
- "orderly-account-id": account4.accountId
166
+ "orderly-account-id": account5.accountId
170
167
  })
171
168
  });
172
169
  });
@@ -181,13 +178,13 @@ var useMutation = (url, method = "POST", options) => {
181
178
  ];
182
179
  };
183
180
  var signatureMiddleware = (useSWRNext) => {
184
- const { apiBaseUrl } = React.useContext(OrderlyContext);
181
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
185
182
  return (key, fetcher4, config) => {
186
183
  try {
187
184
  const extendedFetcher = (url) => __async(void 0, null, function* () {
188
- let account4 = core.SimpleDI.get("account");
185
+ let account5 = core.SimpleDI.get("account");
189
186
  let fullUrl = `${apiBaseUrl}${url}`;
190
- const signer = account4.signer;
187
+ const signer = account5.signer;
191
188
  const payload = {
192
189
  method: "GET",
193
190
  url
@@ -195,7 +192,7 @@ var signatureMiddleware = (useSWRNext) => {
195
192
  const signature = yield signer.sign(payload);
196
193
  return fetcher4(fullUrl, {
197
194
  headers: __spreadProps(__spreadValues({}, signature), {
198
- "orderly-account-id": account4.accountId
195
+ "orderly-account-id": account5.accountId
199
196
  })
200
197
  });
201
198
  });
@@ -212,8 +209,9 @@ var useAccount = () => {
212
209
  keyStore,
213
210
  walletAdapter,
214
211
  onWalletConnect,
215
- onWalletDisconnect
216
- } = React.useContext(OrderlyContext);
212
+ onWalletDisconnect,
213
+ onSetChain
214
+ } = React2.useContext(OrderlyContext);
217
215
  if (!configStore)
218
216
  throw new Error("configStore is not defined, please use OrderlyProvider");
219
217
  if (!keyStore) {
@@ -221,64 +219,69 @@ var useAccount = () => {
221
219
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
222
220
  );
223
221
  }
224
- const account4 = useConstant__default.default(() => {
225
- let account5 = core.SimpleDI.get("account");
226
- if (!account5) {
227
- account5 = new core.Account(configStore, keyStore, walletAdapter);
228
- core.SimpleDI.registerByName("account", account5);
222
+ const account5 = useConstant__default.default(() => {
223
+ let account6 = core.SimpleDI.get("account");
224
+ if (!account6) {
225
+ account6 = new core.Account(configStore, keyStore, walletAdapter);
226
+ core.SimpleDI.registerByName("account", account6);
229
227
  }
230
- return account5;
228
+ return account6;
231
229
  });
232
- const [state, setState] = React.useState(account4.stateValue);
230
+ const [state, setState] = React2.useState(account5.stateValue);
233
231
  const statusChangeHandler = (nextState) => {
234
232
  setState(() => nextState);
235
233
  };
236
- React.useEffect(() => {
237
- account4.on("change:status", statusChangeHandler);
234
+ React2.useEffect(() => {
235
+ account5.on("change:status", statusChangeHandler);
238
236
  return () => {
239
- account4.off("change:status", statusChangeHandler);
237
+ account5.off("change:status", statusChangeHandler);
240
238
  };
241
239
  }, []);
242
- const login = React.useCallback(
240
+ const login = React2.useCallback(
243
241
  (address) => {
244
- account4.login(address);
242
+ account5.login(address);
245
243
  },
246
- [account4]
244
+ [account5]
247
245
  );
248
- const createOrderlyKey = React.useCallback(
246
+ const createOrderlyKey = React2.useCallback(
249
247
  (remember) => __async(void 0, null, function* () {
250
- return account4.createOrderlyKey(remember ? 365 : 30);
248
+ return account5.createOrderlyKey(remember ? 365 : 30);
251
249
  }),
252
- [account4]
250
+ [account5]
253
251
  );
254
- const createAccount = React.useCallback(() => __async(void 0, null, function* () {
255
- return account4.createAccount();
256
- }), [account4]);
257
- const connect = React.useCallback(() => __async(void 0, null, function* () {
252
+ const createAccount = React2.useCallback(() => __async(void 0, null, function* () {
253
+ return account5.createAccount();
254
+ }), [account5]);
255
+ const connect = React2.useCallback(() => __async(void 0, null, function* () {
258
256
  return onWalletConnect == null ? void 0 : onWalletConnect();
259
- }), [account4]);
257
+ }), [account5]);
260
258
  const disconnect = () => __async(void 0, null, function* () {
261
259
  return onWalletDisconnect == null ? void 0 : onWalletDisconnect();
262
260
  });
261
+ const setChain = (chainId) => __async(void 0, null, function* () {
262
+ return onSetChain == null ? void 0 : onSetChain(chainId);
263
+ });
263
264
  return {
264
265
  // account: state!,
265
- account: account4,
266
+ account: account5,
266
267
  state,
267
268
  // info: {},
268
269
  login,
269
270
  createOrderlyKey,
270
271
  createAccount,
271
272
  disconnect,
272
- connect
273
+ connect,
274
+ setChain
275
+ // settlement,
273
276
  };
274
277
  };
275
278
  var usePrivateQuery = (query, options) => {
276
279
  var _b;
277
280
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
278
- const account4 = useAccount();
281
+ const account5 = useAccount();
279
282
  const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_b = options == null ? void 0 : options.use) != null ? _b : [] : [];
280
283
  return useSWR__default.default(
281
- () => account4.state.status >= types.AccountStatusEnum.EnableTrading ? query : null,
284
+ () => account5.state.status >= types.AccountStatusEnum.EnableTrading ? query : null,
282
285
  // query,
283
286
  (url, init) => {
284
287
  return fetcher(url, init, { formatter });
@@ -297,8 +300,8 @@ var useTradingView = () => {
297
300
  return {};
298
301
  };
299
302
  var usePrivateObserve = () => {
300
- const [data, setData] = React.useState();
301
- React.useEffect(() => {
303
+ const [data, setData] = React2.useState();
304
+ React2.useEffect(() => {
302
305
  return () => {
303
306
  };
304
307
  }, []);
@@ -307,8 +310,8 @@ var usePrivateObserve = () => {
307
310
  };
308
311
  };
309
312
  var useTopicObserve = (topic) => {
310
- const [data, setData] = React.useState();
311
- React.useEffect(() => {
313
+ const [data, setData] = React2.useState();
314
+ React2.useEffect(() => {
312
315
  return () => {
313
316
  };
314
317
  }, []);
@@ -316,35 +319,27 @@ var useTopicObserve = (topic) => {
316
319
  data
317
320
  };
318
321
  };
319
- var AppState = class {
320
- constructor() {
321
- this.systemState$ = new rxjs.BehaviorSubject(types.SystemStateEnum.Loading);
322
- this.exchangeState$ = new rxjs.BehaviorSubject(types.ExchangeStatusEnum.Normal);
323
- this.prepare = ["symbolInfo", "clientInfo"];
324
- }
325
- updateState(name) {
326
- this.prepare = this.prepare.filter((item) => item !== name);
327
- if (this.prepare.length === 0) {
328
- this.systemState$.next(types.SystemStateEnum.Ready);
329
- }
330
- }
331
- udpateSystemState(state) {
332
- this.systemState$.next(state);
333
- }
334
- updateExchangeState(state) {
335
- this.exchangeState$.next(state);
336
- }
322
+ var useAppState = () => {
323
+ const { errors, ready } = React2.useContext(OrderlyContext);
324
+ return {
325
+ errors,
326
+ ready
327
+ };
337
328
  };
338
- AppState.instanceName = "AppState";
339
- core.SimpleDI.registerByName(AppState.instanceName, new AppState());
340
- function getAppState() {
341
- return core.SimpleDI.get(AppState.instanceName);
342
- }
343
329
 
344
- // src/useAppState.ts
345
- var useAppState = () => {
346
- getAppState();
347
- return {};
330
+ // src/usePreloadData.ts
331
+ var usePreLoadData = (onSuccess) => {
332
+ useSWR__default.default(
333
+ "https://fi-api.woo.org/swap_support",
334
+ (url) => fetch(url).then((res) => res.json()),
335
+ {
336
+ revalidateOnFocus: false,
337
+ // suspense: true,
338
+ onSuccess: (data, key, config) => {
339
+ onSuccess("chains_fetch");
340
+ }
341
+ }
342
+ );
348
343
  };
349
344
  var useEventEmitter = (channel) => {
350
345
  return useConstant__default.default(() => {
@@ -356,21 +351,94 @@ var useEventEmitter = (channel) => {
356
351
  return ee;
357
352
  });
358
353
  };
359
- var DataSourceContext = React.createContext({});
354
+ function useSessionStorage(key, initialValue) {
355
+ const readValue = React2.useCallback(() => {
356
+ if (typeof window === "undefined") {
357
+ return initialValue;
358
+ }
359
+ try {
360
+ const item = window.sessionStorage.getItem(key);
361
+ return item ? parseJSON(item) : initialValue;
362
+ } catch (error) {
363
+ console.warn(`Error reading sessionStorage key \u201C${key}\u201D:`, error);
364
+ return initialValue;
365
+ }
366
+ }, [initialValue, key]);
367
+ const [storedValue, setStoredValue] = React2.useState(readValue);
368
+ const setValue = (value) => {
369
+ if (typeof window == "undefined") {
370
+ console.warn(
371
+ `Tried setting sessionStorage key \u201C${key}\u201D even though environment is not a client`
372
+ );
373
+ }
374
+ try {
375
+ const newValue = value instanceof Function ? value(storedValue) : value;
376
+ window.sessionStorage.setItem(key, JSON.stringify(newValue));
377
+ setStoredValue(newValue);
378
+ } catch (error) {
379
+ console.warn(`Error setting sessionStorage key \u201C${key}\u201D:`, error);
380
+ }
381
+ };
382
+ React2.useEffect(() => {
383
+ setStoredValue(readValue());
384
+ }, []);
385
+ React2.useEffect(() => {
386
+ if (typeof window == "undefined") {
387
+ return;
388
+ }
389
+ window.addEventListener("storage", handleStorageChange);
390
+ return () => {
391
+ window.removeEventListener("storage", handleStorageChange);
392
+ };
393
+ });
394
+ const handleStorageChange = React2.useCallback(
395
+ (event) => {
396
+ if ((event == null ? void 0 : event.key) && event.key !== key) {
397
+ return;
398
+ }
399
+ setStoredValue(readValue());
400
+ },
401
+ [key, readValue]
402
+ );
403
+ return [storedValue, setValue];
404
+ }
405
+ function parseJSON(value) {
406
+ try {
407
+ return value === "undefined" ? void 0 : JSON.parse(value != null ? value : "");
408
+ } catch (e) {
409
+ console.log("parsing error on", { value });
410
+ return void 0;
411
+ }
412
+ }
413
+ var useRunOnce = ({ fn, sessionKey }) => {
414
+ const triggered = React2.useRef(false);
415
+ React2.useEffect(() => {
416
+ const hasBeenTriggered = sessionKey ? sessionStorage.getItem(sessionKey) : triggered.current;
417
+ if (!hasBeenTriggered) {
418
+ fn();
419
+ triggered.current = true;
420
+ if (sessionKey) {
421
+ sessionStorage.setItem(sessionKey, "true");
422
+ }
423
+ }
424
+ }, [fn, sessionKey]);
425
+ return null;
426
+ };
427
+ var DataSourceContext = React2.createContext({});
360
428
  var DataSourceProvider = (props) => {
361
429
  console.log("render DataSourceProvider");
362
430
  useAccountInstance();
363
431
  useConstant__default.default(() => {
364
432
  });
365
- return /* @__PURE__ */ React__default.default.createElement(DataSourceContext.Provider, { value: {} }, props.children);
433
+ return /* @__PURE__ */ React2__default.default.createElement(DataSourceContext.Provider, { value: {} }, props.children);
366
434
  };
367
435
  var WS_NAME = "nativeWebsocketClient";
368
436
  var useWS = () => {
369
437
  useAccount();
370
- const { configStore } = React.useContext(OrderlyContext);
438
+ const { configStore } = React2.useContext(OrderlyContext);
371
439
  const ws = useConstant__default.default(() => {
372
440
  let websocketClient = core.SimpleDI.get(WS_NAME);
373
- const account4 = core.SimpleDI.get(core.Account.instanceName);
441
+ const account5 = core.SimpleDI.get(core.Account.instanceName);
374
442
  if (!websocketClient) {
375
443
  websocketClient = new net.WS({
376
444
  // accountId: "OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY",
@@ -378,13 +446,13 @@ var useWS = () => {
378
446
  publicUrl: configStore.get("publicWsUrl"),
379
447
  privateUrl: configStore.get("privateWsUrl"),
380
448
  onSigntureRequest: (accountId) => __async(void 0, null, function* () {
381
- const signer = account4.signer;
449
+ const signer = account5.signer;
382
450
  const timestamp = (/* @__PURE__ */ new Date()).getTime();
383
451
  const result = yield signer.signText(timestamp.toString());
384
452
  return __spreadProps(__spreadValues({}, result), { timestamp });
385
453
  })
386
454
  });
387
- account4.on("change:status", (nextState) => {
455
+ account5.on("change:status", (nextState) => {
388
456
  if (nextState.status === types.AccountStatusEnum.EnableTrading && nextState.accountId) {
389
457
  websocketClient.openPrivate(nextState.accountId);
390
458
  }
@@ -430,7 +498,7 @@ var useTickerStream = (symbol) => {
430
498
  };
431
499
  }
432
500
  );
433
- const value = React.useMemo(() => {
501
+ const value = React2.useMemo(() => {
434
502
  if (!info)
435
503
  return null;
436
504
  if (!ticker)
@@ -534,18 +602,18 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
534
602
  if (!symbol) {
535
603
  throw new Error("useOrderbookStream requires a symbol");
536
604
  }
537
- const [requestData, setRequestData] = React.useState(null);
538
- const [data, setData] = React.useState(initial);
539
- const [isLoading, setIsLoading] = React.useState(true);
540
- const [depth, setDepth] = React.useState(1e-3);
541
- const [level, setLevel] = React.useState(() => {
605
+ const [requestData, setRequestData] = React2.useState(null);
606
+ const [data, setData] = React2.useState(initial);
607
+ const [isLoading, setIsLoading] = React2.useState(true);
608
+ const [depth, setDepth] = React2.useState(1e-3);
609
+ const [level, setLevel] = React2.useState(() => {
542
610
  var _a;
543
611
  return (_a = options == null ? void 0 : options.level) != null ? _a : 10;
544
612
  });
545
613
  const ws = useWS();
546
614
  const ticker = useTickerStream(symbol);
547
615
  const eventEmitter = useEventEmitter();
548
- React.useEffect(() => {
616
+ React2.useEffect(() => {
549
617
  ws.onceSubscribe(
550
618
  {
551
619
  event: "request",
@@ -571,7 +639,7 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
571
639
  };
572
640
  }, [symbol]);
573
641
  const { data: markPrice } = useMarkPrice(symbol);
574
- React.useEffect(() => {
642
+ React2.useEffect(() => {
575
643
  if (!requestData)
576
644
  return;
577
645
  const subscription = ws.subscribe(
@@ -593,13 +661,13 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
593
661
  subscription == null ? void 0 : subscription();
594
662
  };
595
663
  }, [symbol, requestData]);
596
- const onItemClick = React.useCallback((item) => {
664
+ const onItemClick = React2.useCallback((item) => {
597
665
  eventEmitter.emit("orderbook:item:click", item);
598
666
  }, []);
599
- const onDepthChange = React.useCallback((depth2) => {
667
+ const onDepthChange = React2.useCallback((depth2) => {
600
668
  console.log("Orderbook depth has changed:", depth2);
601
669
  }, []);
602
- const middlePrice = React.useMemo(() => {
670
+ const middlePrice = React2.useMemo(() => {
603
671
  let asksFrist = 0, bidsFirst = 0;
604
672
  if (data.asks.length > 0) {
605
673
  asksFrist = data.asks[data.asks.length - 1][0];
@@ -719,7 +787,6 @@ function orderEntityFormatHandle(baseTick, quoteTick) {
719
787
  }
720
788
  function priceInputHandle(inputs) {
721
789
  const [values, input, value, markPrice, config] = inputs;
722
- console.log("priceInputHandle", inputs);
723
790
  if (value === "") {
724
791
  return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
725
792
  }
@@ -736,7 +803,7 @@ function priceInputHandle(inputs) {
736
803
  const quantityDP = total.dp();
737
804
  return [
738
805
  __spreadProps(__spreadValues({}, values), {
739
- total: total.toDecimalPlaces(Math.min(quantityDP, config.baseDP)).toString()
806
+ total: total.todp(Math.max(quantityDP, config.baseDP)).toString()
740
807
  }),
741
808
  input,
742
809
  value,
@@ -868,12 +935,38 @@ var useMarkPricesStream = () => {
868
935
  };
869
936
  });
870
937
  };
938
+
939
+ // src/utils/parseHolding.ts
940
+ var parseHolding = (holding, markPrices) => {
941
+ const nonUSDC = [];
942
+ let USDC_holding = 0;
943
+ holding.forEach((item) => {
944
+ var _a;
945
+ if (item.token === "USDC") {
946
+ USDC_holding = item.holding;
947
+ } else {
948
+ nonUSDC.push({
949
+ holding: item.holding,
950
+ markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
951
+ // markPrice: 0,
952
+ discount: 0
953
+ });
954
+ }
955
+ });
956
+ return [USDC_holding, nonUSDC];
957
+ };
871
958
  var usePositionStream = (symbol, options) => {
872
- const [visibledSymbol, setVisibleSymbol] = React.useState(
873
- symbol
874
- );
959
+ var _a;
875
960
  const symbolInfo = useSymbolsInfo();
876
961
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
962
+ const { data: holding } = usePrivateQuery(
963
+ "/v1/client/holding",
964
+ {
965
+ formatter: (data2) => {
966
+ return data2.holding;
967
+ }
968
+ }
969
+ );
877
970
  const fundingRates = useFundingRates();
878
971
  const { data, error } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({
879
972
  // revalidateOnFocus: false,
@@ -886,98 +979,161 @@ var usePositionStream = (symbol, options) => {
886
979
  }
887
980
  }));
888
981
  const { data: markPrices } = useMarkPricesStream();
889
- const formatedPositions = React.useMemo(() => {
982
+ const formatedPositions = React2.useMemo(() => {
890
983
  if (!(data == null ? void 0 : data.rows) || !symbolInfo || !accountInfo)
891
984
  return null;
892
- let totalCollateral = 0;
893
985
  const filteredData = typeof symbol === "undefined" || symbol === "" ? data.rows.filter((item) => {
894
986
  return item.position_qty !== 0;
895
987
  }) : data.rows.filter((item) => {
896
988
  return item.symbol === symbol && item.position_qty !== 0;
897
989
  });
898
- return filteredData.map((item) => {
990
+ let unrealPnL_total = utils.zero, notional_total = utils.zero, unsettlementPnL_total = utils.zero;
991
+ const formatted = filteredData.map((item) => {
992
+ var _a2;
899
993
  const price = ramda.propOr(
900
994
  item.mark_price,
901
995
  item.symbol,
902
996
  markPrices
903
997
  );
998
+ const notional = futures.positions.notional(
999
+ item.position_qty,
1000
+ item.average_open_price
1001
+ );
1002
+ const unrealPnl = futures.positions.unrealizedPnL({
1003
+ qty: item.position_qty,
1004
+ openPrice: item.average_open_price,
1005
+ markPrice: price
1006
+ });
1007
+ const unsettlementPnL = futures.positions.unsettlementPnL({
1008
+ positionQty: item.position_qty,
1009
+ markPrice: price,
1010
+ costPosition: item.cost_position,
1011
+ sumUnitaryFunding: (_a2 = fundingRates[item.symbol]) == null ? void 0 : _a2.call(
1012
+ fundingRates,
1013
+ "sum_unitary_funding",
1014
+ 0
1015
+ ),
1016
+ lastSumUnitaryFunding: item.last_sum_unitary_funding
1017
+ });
1018
+ unrealPnL_total = unrealPnL_total.add(unrealPnl);
1019
+ notional_total = notional_total.add(notional);
1020
+ unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL);
1021
+ return __spreadProps(__spreadValues({}, item), {
1022
+ mark_price: price,
1023
+ mm: 0,
1024
+ notional,
1025
+ unsettlement_pnl: unsettlementPnL,
1026
+ unrealized_pnl: unrealPnl
1027
+ });
1028
+ });
1029
+ return [
1030
+ formatted,
1031
+ {
1032
+ unrealPnL: unrealPnL_total.toNumber(),
1033
+ notional: notional_total.toNumber(),
1034
+ unsettledPnL: unsettlementPnL_total.toNumber()
1035
+ }
1036
+ ];
1037
+ }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol, holding]);
1038
+ const [totalCollateral, totalValue, totalUnrealizedROI] = React2.useMemo(() => {
1039
+ if (!holding || !markPrices) {
1040
+ return [utils.zero, utils.zero, 0];
1041
+ }
1042
+ const unsettlemnedPnL = ramda.pathOr(0, [1, "unsettledPnL"])(formatedPositions);
1043
+ const unrealizedPnL = ramda.pathOr(0, [1, "unrealPnL"])(formatedPositions);
1044
+ const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1045
+ const totalCollateral2 = futures.account.totalCollateral({
1046
+ USDCHolding: USDC_holding,
1047
+ nonUSDCHolding: nonUSDC,
1048
+ unsettlementPnL: unsettlemnedPnL
1049
+ });
1050
+ const totalValue2 = futures.account.totalValue({
1051
+ totalUnsettlementPnL: unsettlemnedPnL,
1052
+ USDCHolding: USDC_holding,
1053
+ nonUSDCHolding: nonUSDC
1054
+ });
1055
+ const totalUnrealizedROI2 = futures.account.totalUnrealizedROI({
1056
+ totalUnrealizedPnL: unrealizedPnL,
1057
+ totalValue: totalValue2.toNumber()
1058
+ });
1059
+ return [totalCollateral2, totalValue2, totalUnrealizedROI2];
1060
+ }, [holding, formatedPositions, markPrices]);
1061
+ const positionsRows = React2.useMemo(() => {
1062
+ if (!formatedPositions)
1063
+ return null;
1064
+ if (!symbolInfo || !accountInfo)
1065
+ return formatedPositions[0];
1066
+ const total = totalCollateral.toNumber();
1067
+ return formatedPositions[0].map((item) => {
904
1068
  const info = symbolInfo == null ? void 0 : symbolInfo[item.symbol];
905
1069
  const MMR = futures.positions.MMR({
906
1070
  baseMMR: info("base_mmr"),
907
1071
  baseIMR: info("base_imr"),
908
1072
  IMRFactor: accountInfo.imr_factor[info("base")],
909
- positionNotional: futures.positions.notional(
910
- item.position_qty,
911
- price
912
- ),
1073
+ positionNotional: item.notional,
913
1074
  IMR_factor_power: 4 / 5
914
1075
  });
915
1076
  return __spreadProps(__spreadValues({}, item), {
916
- mark_price: price,
1077
+ mm: futures.positions.maintenanceMargin({
1078
+ positionQty: item.position_qty,
1079
+ markPrice: item.mark_price,
1080
+ MMR
1081
+ }),
917
1082
  est_liq_price: futures.positions.liqPrice({
918
- markPrice: price,
919
- totalCollateral,
1083
+ markPrice: item.mark_price,
1084
+ totalCollateral: total,
920
1085
  positionQty: item.position_qty,
921
1086
  MMR
922
1087
  }),
923
- notional: futures.positions.notional(
924
- item.position_qty,
925
- item.average_open_price
926
- ),
927
- unrealized_pnl: futures.positions.unrealizedPnL({
928
- qty: item.position_qty,
929
- openPrice: item.average_open_price,
930
- markPrice: price
931
- })
1088
+ MMR
932
1089
  });
933
1090
  });
934
- }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol]);
935
- const aggregatedData = React.useMemo(() => {
936
- const aggregatedData2 = {
937
- unsettledPnL: NaN,
938
- unrealPnL: NaN,
939
- notional: NaN
940
- };
941
- if (formatedPositions && formatedPositions.length) {
942
- aggregatedData2.unrealPnL = futures.positions.totalUnrealizedPnL(formatedPositions);
943
- aggregatedData2.notional = futures.positions.totalNotional(formatedPositions);
944
- aggregatedData2.unsettledPnL = futures.positions.totalUnsettlementPnL(
945
- formatedPositions.map((item) => {
946
- var _a;
947
- return __spreadProps(__spreadValues({}, item), {
948
- sum_unitary_funding: (_a = fundingRates[item.symbol]) == null ? void 0 : _a.call(
949
- fundingRates,
950
- "sum_unitary_funding",
951
- 0
952
- )
953
- });
954
- })
955
- );
956
- }
957
- return aggregatedData2;
958
- }, [formatedPositions, fundingRates]);
959
- const showSymbol = React.useCallback((symbol2) => {
960
- setVisibleSymbol(symbol2);
961
- }, []);
1091
+ }, [formatedPositions, symbolInfo, accountInfo, totalCollateral]);
962
1092
  return [
963
- { rows: formatedPositions, aggregated: aggregatedData },
1093
+ {
1094
+ rows: positionsRows,
1095
+ aggregated: (_a = formatedPositions == null ? void 0 : formatedPositions[1]) != null ? _a : {},
1096
+ totalCollateral,
1097
+ totalValue,
1098
+ totalUnrealizedROI
1099
+ },
964
1100
  createGetter(data, 1),
965
1101
  {
966
1102
  // close: onClosePosition,
967
1103
  loading: false,
968
- showSymbol,
1104
+ // showSymbol,
969
1105
  error,
970
1106
  loadMore: () => {
971
1107
  },
972
1108
  refresh: () => {
973
1109
  }
974
- // toggleHideOthers,
975
- // filter: (filter: string) => {},
976
1110
  }
977
1111
  ];
978
1112
  };
979
- var totalUnsettlementPnLPath = ramda.pathOr(0, [0, "aggregated", "unsettledPnL"]);
1113
+ var useHolding = () => {
1114
+ const { data, isLoading } = usePrivateQuery(
1115
+ "/v1/client/holding",
1116
+ {
1117
+ formatter: (data2) => {
1118
+ return data2.holding;
1119
+ }
1120
+ }
1121
+ );
1122
+ const usdc = React2.useMemo(() => {
1123
+ const usdc2 = data == null ? void 0 : data.find((item) => item.token === "USDC");
1124
+ return usdc2;
1125
+ }, [data]);
1126
+ return {
1127
+ data,
1128
+ usdc,
1129
+ isLoading
1130
+ };
1131
+ };
1132
+
1133
+ // src/orderly/useCollateral.ts
980
1134
  var positionsPath = ramda.pathOr([], [0, "rows"]);
1135
+ ramda.pathOr(0, [0, "totalCollateral"]);
1136
+ var unsettledPnL = ramda.pathOr(0, [0, "aggregated", "unsettledPnL"]);
981
1137
  var useCollateral = (options = { dp: 6 }) => {
982
1138
  const { dp } = options;
983
1139
  const positions2 = usePositionStream();
@@ -985,47 +1141,14 @@ var useCollateral = (options = { dp: 6 }) => {
985
1141
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
986
1142
  const symbolInfo = useSymbolsInfo();
987
1143
  const { data: markPrices } = useMarkPricesStream();
988
- const { data: holding } = usePrivateQuery(
989
- "/v1/client/holding",
990
- {
991
- formatter: (data) => {
992
- return data.holding;
993
- }
994
- }
995
- );
996
- const [totalCollateral, totalValue] = React.useMemo(() => {
997
- if (!holding || !markPrices) {
998
- return [utils.zero, utils.zero];
999
- }
1000
- const unsettlemnedPnL = totalUnsettlementPnLPath(positions2);
1001
- const nonUSDC = [];
1002
- let USDC_holding = 0;
1003
- holding.forEach((item) => {
1004
- var _a;
1005
- if (item.token === "USDC") {
1006
- USDC_holding = item.holding;
1007
- } else {
1008
- nonUSDC.push({
1009
- holding: item.holding,
1010
- markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
1011
- // markPrice: 0,
1012
- discount: 0
1013
- });
1014
- }
1015
- });
1016
- const number = futures.account.totalCollateral({
1017
- USDCHolding: USDC_holding,
1018
- nonUSDCHolding: nonUSDC,
1019
- unsettlementPnL: unsettlemnedPnL
1020
- });
1021
- const totalValue2 = futures.account.totalValue({
1022
- totalUnsettlementPnL: unsettlemnedPnL,
1023
- USDCHolding: USDC_holding,
1024
- nonUSDCHolding: nonUSDC
1025
- });
1026
- return [new utils.Decimal(number), totalValue2];
1027
- }, [holding, positions2, markPrices]);
1028
- const totalInitialMarginWithOrders = React.useMemo(() => {
1144
+ const { usdc } = useHolding();
1145
+ const [totalCollateral, totalValue] = React2.useMemo(() => {
1146
+ return [
1147
+ ramda.pathOr(utils.zero, [0, "totalCollateral"], positions2),
1148
+ ramda.pathOr(utils.zero, [0, "totalValue"], positions2)
1149
+ ];
1150
+ }, [positions2, markPrices]);
1151
+ const totalInitialMarginWithOrders = React2.useMemo(() => {
1029
1152
  if (!accountInfo || !symbolInfo || !markPrices) {
1030
1153
  return 0;
1031
1154
  }
@@ -1038,24 +1161,37 @@ var useCollateral = (options = { dp: 6 }) => {
1038
1161
  symbolInfo
1039
1162
  });
1040
1163
  }, [positions2, orders, markPrices, accountInfo, symbolInfo]);
1041
- return {
1042
- totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1043
- freeCollateral: futures.account.freeCollateral({
1164
+ const freeCollateral = React2.useMemo(() => {
1165
+ return futures.account.freeCollateral({
1044
1166
  totalCollateral,
1045
1167
  totalInitialMarginWithOrders
1046
- }).toDecimalPlaces(dp).toNumber(),
1047
- totalValue: totalValue.toDecimalPlaces(dp).toNumber()
1168
+ });
1169
+ }, [totalCollateral, totalInitialMarginWithOrders]);
1170
+ const availableBalance = React2.useMemo(() => {
1171
+ var _a;
1172
+ return futures.account.availableBalance({
1173
+ USDCHolding: (_a = usdc == null ? void 0 : usdc.holding) != null ? _a : 0,
1174
+ unsettlementPnL: unsettledPnL(positions2)
1175
+ });
1176
+ }, [usdc]);
1177
+ return {
1178
+ totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1179
+ freeCollateral: freeCollateral.toDecimalPlaces(dp).toNumber(),
1180
+ totalValue: totalValue.toDecimalPlaces(dp).toNumber(),
1181
+ availableBalance
1048
1182
  };
1049
1183
  };
1050
1184
  var positionsPath2 = ramda.pathOr([], [0, "rows"]);
1051
1185
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1052
1186
  const positionsData = usePositionStream();
1053
- const { data: orders } = usePrivateQuery(`/v1/orders`);
1187
+ const { data: orders } = usePrivateQuery(
1188
+ `/v1/orders?status=NEW`
1189
+ );
1054
1190
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1055
1191
  const symbolInfo = useSymbolsInfo();
1056
1192
  const { totalCollateral } = useCollateral();
1057
1193
  const { data: markPrices } = useMarkPricesStream();
1058
- const maxQty = React.useMemo(() => {
1194
+ const maxQty = React2.useMemo(() => {
1059
1195
  if (!symbol)
1060
1196
  return 0;
1061
1197
  const positions2 = positionsPath2(positionsData);
@@ -1219,12 +1355,16 @@ var LimitOrderCreator = class extends BaseOrderCreator {
1219
1355
  if (price.lt(minPriceNumber)) {
1220
1356
  errors.order_price = {
1221
1357
  type: "min",
1222
- message: `price must be greater than ${minPriceNumber}`
1358
+ message: `price must be greater than ${new utils.Decimal(
1359
+ minPriceNumber
1360
+ ).todp(symbol.quote_dp)}`
1223
1361
  };
1224
1362
  } else if (price.gt(maxPriceNumber)) {
1225
1363
  errors.order_price = {
1226
1364
  type: "max",
1227
- message: `price must be less than ${maxPriceNumber}`
1365
+ message: `price must be less than ${new utils.Decimal(
1366
+ maxPriceNumber
1367
+ ).todp(symbol.quote_dp)}`
1228
1368
  };
1229
1369
  }
1230
1370
  }
@@ -1283,11 +1423,11 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1283
1423
  const { freeCollateral } = useCollateral();
1284
1424
  const symbolInfo = useSymbolsInfo();
1285
1425
  const tokenInfo = useTokenInfo();
1286
- const baseDP = React.useMemo(
1426
+ const baseDP = React2.useMemo(
1287
1427
  () => utils.getPrecisionByNumber(symbolInfo[symbol]("base_tick", 0)),
1288
1428
  [symbolInfo]
1289
1429
  );
1290
- const quoteDP = React.useMemo(() => {
1430
+ const quoteDP = React2.useMemo(() => {
1291
1431
  return tokenInfo.USDC("decimals", 0);
1292
1432
  }, [tokenInfo]);
1293
1433
  const { data: markPrice } = useMarkPrice(symbol);
@@ -1330,7 +1470,7 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1330
1470
  });
1331
1471
  });
1332
1472
  };
1333
- const calculate = React.useCallback(
1473
+ const calculate = React2.useCallback(
1334
1474
  (values, field, value) => {
1335
1475
  console.log("calculate", values, field, value, markPrice);
1336
1476
  const fieldHandler = getCalculateHandler(field);
@@ -1372,11 +1512,11 @@ var useFetures = () => {
1372
1512
  revalidateOnFocus: false
1373
1513
  }
1374
1514
  );
1375
- const [sortedData, setSortedData] = React.useState(data);
1515
+ const [sortedData, setSortedData] = React2.useState(data);
1376
1516
  useWS();
1377
- React.useEffect(() => {
1517
+ React2.useEffect(() => {
1378
1518
  }, []);
1379
- React.useEffect(() => {
1519
+ React2.useEffect(() => {
1380
1520
  if (data) {
1381
1521
  const sortedData2 = data.sort((a, b) => {
1382
1522
  return 0;
@@ -1384,9 +1524,9 @@ var useFetures = () => {
1384
1524
  setSortedData(sortedData2);
1385
1525
  }
1386
1526
  }, [data]);
1387
- const sortBy = React.useCallback((key) => {
1527
+ const sortBy = React2.useCallback((key) => {
1388
1528
  }, [data]);
1389
- const filterBy = React.useCallback((key) => {
1529
+ const filterBy = React2.useCallback((key) => {
1390
1530
  }, [data]);
1391
1531
  return {
1392
1532
  // ...data,
@@ -1428,7 +1568,7 @@ var useMarketsStream = () => {
1428
1568
  unsubscribe == null ? void 0 : unsubscribe();
1429
1569
  };
1430
1570
  });
1431
- const value = React.useMemo(() => {
1571
+ const value = React2.useMemo(() => {
1432
1572
  if (!futures)
1433
1573
  return null;
1434
1574
  if (!tickers)
@@ -1453,7 +1593,7 @@ var useMarketsStream = () => {
1453
1593
  var useLeverage = () => {
1454
1594
  const { data, mutate: mutate2 } = usePrivateQuery("/v1/client/info");
1455
1595
  const [update] = useMutation("/v1/client/leverage");
1456
- const updateLeverage = React.useCallback((data2) => {
1596
+ const updateLeverage = React2.useCallback((data2) => {
1457
1597
  return update(data2).then((res) => {
1458
1598
  return mutate2();
1459
1599
  });
@@ -1461,10 +1601,11 @@ var useLeverage = () => {
1461
1601
  return [ramda.prop("max_leverage", data), { update: updateLeverage }];
1462
1602
  };
1463
1603
  var useFundingRate = (symbol) => {
1604
+ var _a;
1464
1605
  if (!symbol) {
1465
1606
  throw new Error("useFuturesForSymbol requires a symbol");
1466
1607
  }
1467
- const [countDown, setCountDown] = React.useState("00:00:00");
1608
+ const [countDown, setCountDown] = React2.useState("00:00:00");
1468
1609
  const { data } = useQuery(
1469
1610
  `/v1/public/funding_rate/${symbol}`,
1470
1611
  {
@@ -1474,7 +1615,7 @@ var useFundingRate = (symbol) => {
1474
1615
  }
1475
1616
  }
1476
1617
  );
1477
- React.useEffect(() => {
1618
+ React2.useEffect(() => {
1478
1619
  if (!data)
1479
1620
  return;
1480
1621
  const { next_funding_time } = data;
@@ -1495,16 +1636,17 @@ var useFundingRate = (symbol) => {
1495
1636
  };
1496
1637
  }, [data]);
1497
1638
  return __spreadProps(__spreadValues({}, data), {
1639
+ est_funding_rate: (Number((_a = data == null ? void 0 : data.est_funding_rate) != null ? _a : 0) * 100).toFixed(4),
1498
1640
  countDown
1499
1641
  });
1500
1642
  };
1501
1643
  var fetcher3 = (url, init) => net.get(url, init);
1502
1644
  var usePrivateInfiniteQuery = (getKey, options) => {
1503
1645
  var _a;
1504
- const account4 = useAccount();
1646
+ const account5 = useAccount();
1505
1647
  const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
1506
1648
  const result = useSWRInfinite__default.default(
1507
- (pageIndex, previousPageData) => account4.state.status >= types.AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1649
+ (pageIndex, previousPageData) => account5.state.status >= types.AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1508
1650
  fetcher3,
1509
1651
  __spreadProps(__spreadValues({}, options), {
1510
1652
  use: [signatureMiddleware, ...middleware]
@@ -1521,8 +1663,10 @@ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1521
1663
  return OrderStatus2;
1522
1664
  })(OrderStatus || {});
1523
1665
  var useOrderStream = ({
1524
- status = "NEW" /* NEW */,
1525
- symbol
1666
+ status,
1667
+ symbol,
1668
+ side,
1669
+ size = 100
1526
1670
  } = {}) => {
1527
1671
  const { data: markPrices = {} } = useMarkPricesStream();
1528
1672
  const [doCancelOrder] = useMutation("/v1/order", "DELETE");
@@ -1530,13 +1674,19 @@ var useOrderStream = ({
1530
1674
  const ordersResponse = usePrivateInfiniteQuery(
1531
1675
  (pageIndex, previousPageData) => {
1532
1676
  const search = new URLSearchParams([
1533
- ["size", "100"],
1534
- ["page", `${pageIndex + 1}`],
1535
- [`status`, status]
1677
+ ["size", size.toString()],
1678
+ ["page", `${pageIndex + 1}`]
1679
+ // [`status`, status],
1536
1680
  ]);
1681
+ if (status) {
1682
+ search.set(`status`, status);
1683
+ }
1537
1684
  if (symbol) {
1538
1685
  search.set(`symbol`, symbol);
1539
1686
  }
1687
+ if (side) {
1688
+ search.set(`side`, side);
1689
+ }
1540
1690
  return `/v1/orders?${search.toString()}`;
1541
1691
  },
1542
1692
  {
@@ -1546,7 +1696,7 @@ var useOrderStream = ({
1546
1696
  }
1547
1697
  }
1548
1698
  );
1549
- const orders = React.useMemo(() => {
1699
+ const orders = React2.useMemo(() => {
1550
1700
  var _a;
1551
1701
  if (!ordersResponse.data) {
1552
1702
  return null;
@@ -1558,13 +1708,13 @@ var useOrderStream = ({
1558
1708
  });
1559
1709
  });
1560
1710
  }, [ordersResponse.data, markPrices]);
1561
- const cancelAllOrders = React.useCallback(() => {
1711
+ const cancelAllOrders = React2.useCallback(() => {
1562
1712
  }, [ordersResponse.data]);
1563
- const updateOrder = React.useCallback((orderId, order2) => {
1713
+ const updateOrder = React2.useCallback((orderId, order2) => {
1564
1714
  console.log("updateOrder", order2, orderId);
1565
1715
  return doUpdateOrder(__spreadProps(__spreadValues({}, order2), { order_id: orderId }));
1566
1716
  }, []);
1567
- const cancelOrder = React.useCallback((orderId, symbol2) => {
1717
+ const cancelOrder = React2.useCallback((orderId, symbol2) => {
1568
1718
  return doCancelOrder(null, {
1569
1719
  order_id: orderId,
1570
1720
  symbol: symbol2
@@ -1587,16 +1737,36 @@ var useOrderStream = ({
1587
1737
  }
1588
1738
  ];
1589
1739
  };
1590
-
1591
- // src/orderly/useMarketTradeStream.ts
1592
- var useMarketTradeStream = (symbol) => {
1740
+ var useMarketTradeStream = (symbol, options = {}) => {
1593
1741
  if (!symbol) {
1594
1742
  throw new Error("useTradeStream: symbol is required");
1595
1743
  }
1596
- const { data, isLoading } = useQuery(
1597
- `/v1/public/market_trades?symbol=${symbol}&limit=20`
1744
+ const [trades, setTrades] = React2.useState([]);
1745
+ const { level = 20 } = options;
1746
+ const { isLoading } = useQuery(
1747
+ `/v1/public/market_trades?symbol=${symbol}&limit=${level}`,
1748
+ {
1749
+ onSuccess: (data) => {
1750
+ console.log("trades ^^^^^^", data);
1751
+ if (Array.isArray(data)) {
1752
+ setTrades(data);
1753
+ }
1754
+ return data;
1755
+ }
1756
+ }
1598
1757
  );
1599
- return { data, isLoading };
1758
+ const ws = useWS();
1759
+ React2.useEffect(() => {
1760
+ const unsubscript = ws.subscribe(`@${symbol}/@trade`, {
1761
+ onMessage: (data) => {
1762
+ console.log("trade", data);
1763
+ }
1764
+ });
1765
+ return () => {
1766
+ unsubscript == null ? void 0 : unsubscript();
1767
+ };
1768
+ }, []);
1769
+ return { trades, isLoading };
1600
1770
  };
1601
1771
 
1602
1772
  // src/orderly/useTrades.tsx
@@ -1608,7 +1778,7 @@ var useMarginRatio = () => {
1608
1778
  const [{ rows }] = usePositionStream();
1609
1779
  const { data: markPrices } = useMarkPricesStream();
1610
1780
  const { totalCollateral } = useCollateral();
1611
- const marginRatio = React.useMemo(() => {
1781
+ const marginRatio = React2.useMemo(() => {
1612
1782
  const ratio = futures.account.totalMarginRatio({
1613
1783
  totalCollateral,
1614
1784
  markPrices,
@@ -1616,19 +1786,23 @@ var useMarginRatio = () => {
1616
1786
  });
1617
1787
  return ratio;
1618
1788
  }, [rows, markPrices, totalCollateral]);
1619
- return marginRatio;
1789
+ const currentLeverage = React2.useMemo(() => {
1790
+ return futures.account.currentLeverage(marginRatio);
1791
+ }, [marginRatio]);
1792
+ return [marginRatio, currentLeverage];
1620
1793
  };
1621
- var useChains = (networkId, options) => {
1794
+ var useChains = (networkId, options = {}) => {
1795
+ const _a = options, swrOptions = __objRest(_a, ["filter", "pick"]);
1622
1796
  const field = options == null ? void 0 : options.pick;
1623
1797
  const { data } = useSWR__default.default(
1624
1798
  "https://fi-api.woo.org/swap_support",
1625
1799
  (url) => fetch(url).then((res) => res.json()),
1626
- {
1800
+ __spreadValues({
1627
1801
  revalidateOnFocus: false,
1628
1802
  revalidateOnReconnect: false
1629
- }
1803
+ }, swrOptions)
1630
1804
  );
1631
- const chains = React.useMemo(() => {
1805
+ const chains = React2.useMemo(() => {
1632
1806
  if (!data || !data.data)
1633
1807
  return data;
1634
1808
  let arr = [];
@@ -1654,7 +1828,7 @@ var useChains = (networkId, options) => {
1654
1828
  }
1655
1829
  return arr;
1656
1830
  }, [data, networkId, field, options]);
1657
- const findByChainId = React.useCallback(
1831
+ const findByChainId = React2.useCallback(
1658
1832
  (chainId) => {
1659
1833
  if (!data || !data.data)
1660
1834
  return void 0;
@@ -1679,17 +1853,17 @@ var useBalance = () => {
1679
1853
  var usePrivateDataObserver = () => {
1680
1854
  const ws = useWS();
1681
1855
  const { mutate: mutate2 } = useSWR.useSWRConfig();
1682
- React.useEffect(() => {
1856
+ React2.useEffect(() => {
1683
1857
  console.log("subscribe: executionreport");
1684
1858
  const unsubscribe = ws.privateSubscribe("executionreport", {
1685
1859
  onMessage: (data) => {
1686
1860
  console.info("refresh orders");
1687
- mutate2("/v1/orders");
1861
+ console.log(data);
1688
1862
  }
1689
1863
  });
1690
1864
  return () => unsubscribe == null ? void 0 : unsubscribe();
1691
1865
  }, []);
1692
- React.useEffect(() => {
1866
+ React2.useEffect(() => {
1693
1867
  console.log("subscribe: position");
1694
1868
  const unsubscribe = ws.privateSubscribe("position", {
1695
1869
  onMessage: (data) => {
@@ -1720,7 +1894,6 @@ var useExecutionReport = () => {
1720
1894
  // src/apis/index.ts
1721
1895
  var apis_exports = {};
1722
1896
  __export(apis_exports, {
1723
- useFundingRate: () => useFundingRate2,
1724
1897
  useFundingRateBySymbol: () => useFundingRateBySymbol,
1725
1898
  useInfo: () => useInfo,
1726
1899
  useToken: () => useToken
@@ -1746,11 +1919,6 @@ var useFundingRateBySymbol = (symbol) => {
1746
1919
  return useQuery(`/public/funding_rate/${symbol}`);
1747
1920
  };
1748
1921
 
1749
- // src/apis/useFundingRate.ts
1750
- var useFundingRate2 = (symbol) => {
1751
- return useQuery(`/v1/public/funding_rate`);
1752
- };
1753
-
1754
1922
  Object.defineProperty(exports, 'useSWR', {
1755
1923
  enumerable: true,
1756
1924
  get: function () { return useSWR__default.default; }
@@ -1766,6 +1934,7 @@ exports.OrderlyProvider = OrderlyProvider;
1766
1934
  exports.apis = apis_exports;
1767
1935
  exports.useAccount = useAccount;
1768
1936
  exports.useAccountInfo = useAccountInfo;
1937
+ exports.useAccountInstance = useAccountInstance;
1769
1938
  exports.useAppState = useAppState;
1770
1939
  exports.useBalance = useBalance;
1771
1940
  exports.useChains = useChains;
@@ -1774,6 +1943,7 @@ exports.useEventEmitter = useEventEmitter;
1774
1943
  exports.useExecutionReport = useExecutionReport;
1775
1944
  exports.useFetures = useFetures;
1776
1945
  exports.useFundingRate = useFundingRate;
1946
+ exports.useHolding = useHolding;
1777
1947
  exports.useLeverage = useLeverage;
1778
1948
  exports.useMarginRatio = useMarginRatio;
1779
1949
  exports.useMarkPrice = useMarkPrice;
@@ -1786,10 +1956,13 @@ exports.useOrderEntry = useOrderEntry;
1786
1956
  exports.useOrderStream = useOrderStream;
1787
1957
  exports.useOrderbookStream = useOrderbookStream;
1788
1958
  exports.usePositionStream = usePositionStream;
1959
+ exports.usePreLoadData = usePreLoadData;
1789
1960
  exports.usePrivateDataObserver = usePrivateDataObserver;
1790
1961
  exports.usePrivateObserve = usePrivateObserve;
1791
1962
  exports.usePrivateQuery = usePrivateQuery;
1792
1963
  exports.useQuery = useQuery;
1964
+ exports.useRunOnce = useRunOnce;
1965
+ exports.useSessionStorage = useSessionStorage;
1793
1966
  exports.useSymbolsInfo = useSymbolsInfo;
1794
1967
  exports.useTickerStream = useTickerStream;
1795
1968
  exports.useTokenInfo = useTokenInfo;