@orderly.network/hooks 0.0.19 → 0.0.21

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,4 +1,4 @@
1
- import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
1
+ import React2, { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
2
2
  import useSWR, { useSWRConfig } from 'swr';
3
3
  export { default as useSWR } from 'swr';
4
4
  import { WS, get, mutate } from '@orderly.network/net';
@@ -6,8 +6,7 @@ import useSWRMutation from 'swr/mutation';
6
6
  import useConstant from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
8
  import { SimpleDI, Account, EventEmitter } from '@orderly.network/core';
9
- import { AccountStatusEnum, SystemStateEnum, ExchangeStatusEnum, OrderSide, OrderType } from '@orderly.network/types';
10
- import { BehaviorSubject } from 'rxjs';
9
+ import { AccountStatusEnum, OrderSide, OrderType } from '@orderly.network/types';
11
10
  import useSWRSubscription from 'swr/subscription';
12
11
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
13
12
  import { pathOr, propOr, compose, head, prop } from 'ramda';
@@ -98,20 +97,19 @@ var useAccountInstance = () => {
98
97
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
99
98
  );
100
99
  }
101
- const account4 = useConstant(() => {
102
- let account5 = SimpleDI.get("account");
103
- if (!account5) {
104
- account5 = new Account(configStore, keyStore, walletAdapter);
105
- SimpleDI.registerByName("account", account5);
100
+ const account5 = useConstant(() => {
101
+ let account6 = SimpleDI.get("account");
102
+ if (!account6) {
103
+ account6 = new Account(configStore, keyStore, walletAdapter);
104
+ SimpleDI.registerByName("account", account6);
106
105
  }
107
- return account5;
106
+ return account6;
108
107
  });
109
- return account4;
108
+ return account5;
110
109
  };
111
110
 
112
111
  // src/useMutation.ts
113
112
  var fetcher2 = (url, options) => {
114
- console.log("muation fetcher", url, options);
115
113
  const init = {
116
114
  method: options.arg.method,
117
115
  headers: __spreadValues({}, options.arg.signature)
@@ -131,8 +129,8 @@ var useMutation = (url, method = "POST", options) => {
131
129
  if (!url.startsWith("http")) {
132
130
  fullUrl = `${apiBaseUrl}${url}`;
133
131
  }
134
- const account4 = useAccountInstance();
135
- const signer = account4.signer;
132
+ const account5 = useAccountInstance();
133
+ const signer = account5.signer;
136
134
  const { trigger, data, error, reset, isMutating } = useSWRMutation(
137
135
  fullUrl,
138
136
  // method === "POST" ? fetcher : deleteFetcher,
@@ -150,14 +148,13 @@ var useMutation = (url, method = "POST", options) => {
150
148
  url: newUrl,
151
149
  data: data2
152
150
  };
153
- console.log("payload", payload);
154
151
  const signature = yield signer.sign(payload);
155
152
  return trigger({
156
153
  data: data2,
157
154
  params,
158
155
  method,
159
156
  signature: __spreadProps(__spreadValues({}, signature), {
160
- "orderly-account-id": account4.accountId
157
+ "orderly-account-id": account5.accountId
161
158
  })
162
159
  });
163
160
  });
@@ -176,9 +173,9 @@ var signatureMiddleware = (useSWRNext) => {
176
173
  return (key, fetcher4, config) => {
177
174
  try {
178
175
  const extendedFetcher = (url) => __async(void 0, null, function* () {
179
- let account4 = SimpleDI.get("account");
176
+ let account5 = SimpleDI.get("account");
180
177
  let fullUrl = `${apiBaseUrl}${url}`;
181
- const signer = account4.signer;
178
+ const signer = account5.signer;
182
179
  const payload = {
183
180
  method: "GET",
184
181
  url
@@ -186,7 +183,7 @@ var signatureMiddleware = (useSWRNext) => {
186
183
  const signature = yield signer.sign(payload);
187
184
  return fetcher4(fullUrl, {
188
185
  headers: __spreadProps(__spreadValues({}, signature), {
189
- "orderly-account-id": account4.accountId
186
+ "orderly-account-id": account5.accountId
190
187
  })
191
188
  });
192
189
  });
@@ -203,7 +200,8 @@ var useAccount = () => {
203
200
  keyStore,
204
201
  walletAdapter,
205
202
  onWalletConnect,
206
- onWalletDisconnect
203
+ onWalletDisconnect,
204
+ onSetChain
207
205
  } = useContext(OrderlyContext);
208
206
  if (!configStore)
209
207
  throw new Error("configStore is not defined, please use OrderlyProvider");
@@ -212,64 +210,69 @@ var useAccount = () => {
212
210
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
213
211
  );
214
212
  }
215
- const account4 = useConstant(() => {
216
- let account5 = SimpleDI.get("account");
217
- if (!account5) {
218
- account5 = new Account(configStore, keyStore, walletAdapter);
219
- SimpleDI.registerByName("account", account5);
213
+ const account5 = useConstant(() => {
214
+ let account6 = SimpleDI.get("account");
215
+ if (!account6) {
216
+ account6 = new Account(configStore, keyStore, walletAdapter);
217
+ SimpleDI.registerByName("account", account6);
220
218
  }
221
- return account5;
219
+ return account6;
222
220
  });
223
- const [state, setState] = useState(account4.stateValue);
221
+ const [state, setState] = useState(account5.stateValue);
224
222
  const statusChangeHandler = (nextState) => {
225
223
  setState(() => nextState);
226
224
  };
227
225
  useEffect(() => {
228
- account4.on("change:status", statusChangeHandler);
226
+ account5.on("change:status", statusChangeHandler);
229
227
  return () => {
230
- account4.off("change:status", statusChangeHandler);
228
+ account5.off("change:status", statusChangeHandler);
231
229
  };
232
230
  }, []);
233
231
  const login = useCallback(
234
232
  (address) => {
235
- account4.login(address);
233
+ account5.login(address);
236
234
  },
237
- [account4]
235
+ [account5]
238
236
  );
239
237
  const createOrderlyKey = useCallback(
240
238
  (remember) => __async(void 0, null, function* () {
241
- return account4.createOrderlyKey(remember ? 365 : 30);
239
+ return account5.createOrderlyKey(remember ? 365 : 30);
242
240
  }),
243
- [account4]
241
+ [account5]
244
242
  );
245
243
  const createAccount = useCallback(() => __async(void 0, null, function* () {
246
- return account4.createAccount();
247
- }), [account4]);
244
+ return account5.createAccount();
245
+ }), [account5]);
248
246
  const connect = useCallback(() => __async(void 0, null, function* () {
249
247
  return onWalletConnect == null ? void 0 : onWalletConnect();
250
- }), [account4]);
248
+ }), [account5]);
251
249
  const disconnect = () => __async(void 0, null, function* () {
252
250
  return onWalletDisconnect == null ? void 0 : onWalletDisconnect();
253
251
  });
252
+ const setChain = (chainId) => __async(void 0, null, function* () {
253
+ return onSetChain == null ? void 0 : onSetChain(chainId);
254
+ });
254
255
  return {
255
256
  // account: state!,
256
- account: account4,
257
+ account: account5,
257
258
  state,
258
259
  // info: {},
259
260
  login,
260
261
  createOrderlyKey,
261
262
  createAccount,
262
263
  disconnect,
263
- connect
264
+ connect,
265
+ setChain
266
+ // settlement,
264
267
  };
265
268
  };
266
269
  var usePrivateQuery = (query, options) => {
267
270
  var _b;
268
271
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
269
- const account4 = useAccount();
272
+ const account5 = useAccount();
270
273
  const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_b = options == null ? void 0 : options.use) != null ? _b : [] : [];
271
274
  return useSWR(
272
- () => account4.state.status >= AccountStatusEnum.EnableTrading ? query : null,
275
+ () => account5.state.status >= AccountStatusEnum.EnableTrading ? query : null,
273
276
  // query,
274
277
  (url, init) => {
275
278
  return fetcher(url, init, { formatter });
@@ -307,35 +310,27 @@ var useTopicObserve = (topic) => {
307
310
  data
308
311
  };
309
312
  };
310
- var AppState = class {
311
- constructor() {
312
- this.systemState$ = new BehaviorSubject(SystemStateEnum.Loading);
313
- this.exchangeState$ = new BehaviorSubject(ExchangeStatusEnum.Normal);
314
- this.prepare = ["symbolInfo", "clientInfo"];
315
- }
316
- updateState(name) {
317
- this.prepare = this.prepare.filter((item) => item !== name);
318
- if (this.prepare.length === 0) {
319
- this.systemState$.next(SystemStateEnum.Ready);
320
- }
321
- }
322
- udpateSystemState(state) {
323
- this.systemState$.next(state);
324
- }
325
- updateExchangeState(state) {
326
- this.exchangeState$.next(state);
327
- }
313
+ var useAppState = () => {
314
+ const { errors, ready } = useContext(OrderlyContext);
315
+ return {
316
+ errors,
317
+ ready
318
+ };
328
319
  };
329
- AppState.instanceName = "AppState";
330
- SimpleDI.registerByName(AppState.instanceName, new AppState());
331
- function getAppState() {
332
- return SimpleDI.get(AppState.instanceName);
333
- }
334
320
 
335
- // src/useAppState.ts
336
- var useAppState = () => {
337
- getAppState();
338
- return {};
321
+ // src/usePreloadData.ts
322
+ var usePreLoadData = (onSuccess) => {
323
+ useSWR(
324
+ "https://fi-api.woo.org/swap_support",
325
+ (url) => fetch(url).then((res) => res.json()),
326
+ {
327
+ revalidateOnFocus: false,
328
+ // suspense: true,
329
+ onSuccess: (data, key, config) => {
330
+ onSuccess("chains_fetch");
331
+ }
332
+ }
333
+ );
339
334
  };
340
335
  var useEventEmitter = (channel) => {
341
336
  return useConstant(() => {
@@ -347,13 +342,86 @@ var useEventEmitter = (channel) => {
347
342
  return ee;
348
343
  });
349
344
  };
345
+ function useSessionStorage(key, initialValue) {
346
+ const readValue = useCallback(() => {
347
+ if (typeof window === "undefined") {
348
+ return initialValue;
349
+ }
350
+ try {
351
+ const item = window.sessionStorage.getItem(key);
352
+ return item ? parseJSON(item) : initialValue;
353
+ } catch (error) {
354
+ console.warn(`Error reading sessionStorage key \u201C${key}\u201D:`, error);
355
+ return initialValue;
356
+ }
357
+ }, [initialValue, key]);
358
+ const [storedValue, setStoredValue] = useState(readValue);
359
+ const setValue = (value) => {
360
+ if (typeof window == "undefined") {
361
+ console.warn(
362
+ `Tried setting sessionStorage key \u201C${key}\u201D even though environment is not a client`
363
+ );
364
+ }
365
+ try {
366
+ const newValue = value instanceof Function ? value(storedValue) : value;
367
+ window.sessionStorage.setItem(key, JSON.stringify(newValue));
368
+ setStoredValue(newValue);
369
+ } catch (error) {
370
+ console.warn(`Error setting sessionStorage key \u201C${key}\u201D:`, error);
371
+ }
372
+ };
373
+ useEffect(() => {
374
+ setStoredValue(readValue());
375
+ }, []);
376
+ useEffect(() => {
377
+ if (typeof window == "undefined") {
378
+ return;
379
+ }
380
+ window.addEventListener("storage", handleStorageChange);
381
+ return () => {
382
+ window.removeEventListener("storage", handleStorageChange);
383
+ };
384
+ });
385
+ const handleStorageChange = useCallback(
386
+ (event) => {
387
+ if ((event == null ? void 0 : event.key) && event.key !== key) {
388
+ return;
389
+ }
390
+ setStoredValue(readValue());
391
+ },
392
+ [key, readValue]
393
+ );
394
+ return [storedValue, setValue];
395
+ }
396
+ function parseJSON(value) {
397
+ try {
398
+ return value === "undefined" ? void 0 : JSON.parse(value != null ? value : "");
399
+ } catch (e) {
400
+ console.log("parsing error on", { value });
401
+ return void 0;
402
+ }
403
+ }
404
+ var useRunOnce = ({ fn, sessionKey }) => {
405
+ const triggered = useRef(false);
406
+ useEffect(() => {
407
+ const hasBeenTriggered = sessionKey ? sessionStorage.getItem(sessionKey) : triggered.current;
408
+ if (!hasBeenTriggered) {
409
+ fn();
410
+ triggered.current = true;
411
+ if (sessionKey) {
412
+ sessionStorage.setItem(sessionKey, "true");
413
+ }
414
+ }
415
+ }, [fn, sessionKey]);
416
+ return null;
417
+ };
350
418
  var DataSourceContext = createContext({});
351
419
  var DataSourceProvider = (props) => {
352
420
  console.log("render DataSourceProvider");
353
421
  useAccountInstance();
354
422
  useConstant(() => {
355
423
  });
356
- return /* @__PURE__ */ React.createElement(DataSourceContext.Provider, { value: {} }, props.children);
424
+ return /* @__PURE__ */ React2.createElement(DataSourceContext.Provider, { value: {} }, props.children);
357
425
  };
358
426
  var WS_NAME = "nativeWebsocketClient";
359
427
  var useWS = () => {
@@ -361,7 +429,7 @@ var useWS = () => {
361
429
  const { configStore } = useContext(OrderlyContext);
362
430
  const ws = useConstant(() => {
363
431
  let websocketClient = SimpleDI.get(WS_NAME);
364
- const account4 = SimpleDI.get(Account.instanceName);
432
+ const account5 = SimpleDI.get(Account.instanceName);
365
433
  if (!websocketClient) {
366
434
  websocketClient = new WS({
367
435
  // accountId: "OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY",
@@ -369,13 +437,13 @@ var useWS = () => {
369
437
  publicUrl: configStore.get("publicWsUrl"),
370
438
  privateUrl: configStore.get("privateWsUrl"),
371
439
  onSigntureRequest: (accountId) => __async(void 0, null, function* () {
372
- const signer = account4.signer;
440
+ const signer = account5.signer;
373
441
  const timestamp = (/* @__PURE__ */ new Date()).getTime();
374
442
  const result = yield signer.signText(timestamp.toString());
375
443
  return __spreadProps(__spreadValues({}, result), { timestamp });
376
444
  })
377
445
  });
378
- account4.on("change:status", (nextState) => {
446
+ account5.on("change:status", (nextState) => {
379
447
  if (nextState.status === AccountStatusEnum.EnableTrading && nextState.accountId) {
380
448
  websocketClient.openPrivate(nextState.accountId);
381
449
  }
@@ -710,7 +778,6 @@ function orderEntityFormatHandle(baseTick, quoteTick) {
710
778
  }
711
779
  function priceInputHandle(inputs) {
712
780
  const [values, input, value, markPrice, config] = inputs;
713
- console.log("priceInputHandle", inputs);
714
781
  if (value === "") {
715
782
  return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
716
783
  }
@@ -727,7 +794,7 @@ function priceInputHandle(inputs) {
727
794
  const quantityDP = total.dp();
728
795
  return [
729
796
  __spreadProps(__spreadValues({}, values), {
730
- total: total.toDecimalPlaces(Math.min(quantityDP, config.baseDP)).toString()
797
+ total: total.todp(Math.max(quantityDP, config.baseDP)).toString()
731
798
  }),
732
799
  input,
733
800
  value,
@@ -859,12 +926,38 @@ var useMarkPricesStream = () => {
859
926
  };
860
927
  });
861
928
  };
929
+
930
+ // src/utils/parseHolding.ts
931
+ var parseHolding = (holding, markPrices) => {
932
+ const nonUSDC = [];
933
+ let USDC_holding = 0;
934
+ holding.forEach((item) => {
935
+ var _a;
936
+ if (item.token === "USDC") {
937
+ USDC_holding = item.holding;
938
+ } else {
939
+ nonUSDC.push({
940
+ holding: item.holding,
941
+ markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
942
+ // markPrice: 0,
943
+ discount: 0
944
+ });
945
+ }
946
+ });
947
+ return [USDC_holding, nonUSDC];
948
+ };
862
949
  var usePositionStream = (symbol, options) => {
863
- const [visibledSymbol, setVisibleSymbol] = useState(
864
- symbol
865
- );
950
+ var _a;
866
951
  const symbolInfo = useSymbolsInfo();
867
952
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
953
+ const { data: holding } = usePrivateQuery(
954
+ "/v1/client/holding",
955
+ {
956
+ formatter: (data2) => {
957
+ return data2.holding;
958
+ }
959
+ }
960
+ );
868
961
  const fundingRates = useFundingRates();
869
962
  const { data, error } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({
870
963
  // revalidateOnFocus: false,
@@ -880,95 +973,158 @@ var usePositionStream = (symbol, options) => {
880
973
  const formatedPositions = useMemo(() => {
881
974
  if (!(data == null ? void 0 : data.rows) || !symbolInfo || !accountInfo)
882
975
  return null;
883
- let totalCollateral = 0;
884
976
  const filteredData = typeof symbol === "undefined" || symbol === "" ? data.rows.filter((item) => {
885
977
  return item.position_qty !== 0;
886
978
  }) : data.rows.filter((item) => {
887
979
  return item.symbol === symbol && item.position_qty !== 0;
888
980
  });
889
- return filteredData.map((item) => {
981
+ let unrealPnL_total = zero, notional_total = zero, unsettlementPnL_total = zero;
982
+ const formatted = filteredData.map((item) => {
983
+ var _a2;
890
984
  const price = propOr(
891
985
  item.mark_price,
892
986
  item.symbol,
893
987
  markPrices
894
988
  );
989
+ const notional = positions.notional(
990
+ item.position_qty,
991
+ item.average_open_price
992
+ );
993
+ const unrealPnl = positions.unrealizedPnL({
994
+ qty: item.position_qty,
995
+ openPrice: item.average_open_price,
996
+ markPrice: price
997
+ });
998
+ const unsettlementPnL = positions.unsettlementPnL({
999
+ positionQty: item.position_qty,
1000
+ markPrice: price,
1001
+ costPosition: item.cost_position,
1002
+ sumUnitaryFunding: (_a2 = fundingRates[item.symbol]) == null ? void 0 : _a2.call(
1003
+ fundingRates,
1004
+ "sum_unitary_funding",
1005
+ 0
1006
+ ),
1007
+ lastSumUnitaryFunding: item.last_sum_unitary_funding
1008
+ });
1009
+ unrealPnL_total = unrealPnL_total.add(unrealPnl);
1010
+ notional_total = notional_total.add(notional);
1011
+ unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL);
1012
+ return __spreadProps(__spreadValues({}, item), {
1013
+ mark_price: price,
1014
+ mm: 0,
1015
+ notional,
1016
+ unsettlement_pnl: unsettlementPnL,
1017
+ unrealized_pnl: unrealPnl
1018
+ });
1019
+ });
1020
+ return [
1021
+ formatted,
1022
+ {
1023
+ unrealPnL: unrealPnL_total.toNumber(),
1024
+ notional: notional_total.toNumber(),
1025
+ unsettledPnL: unsettlementPnL_total.toNumber()
1026
+ }
1027
+ ];
1028
+ }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol, holding]);
1029
+ const [totalCollateral, totalValue, totalUnrealizedROI] = useMemo(() => {
1030
+ if (!holding || !markPrices) {
1031
+ return [zero, zero, 0];
1032
+ }
1033
+ const unsettlemnedPnL = pathOr(0, [1, "unsettledPnL"])(formatedPositions);
1034
+ const unrealizedPnL = pathOr(0, [1, "unrealPnL"])(formatedPositions);
1035
+ const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1036
+ const totalCollateral2 = account.totalCollateral({
1037
+ USDCHolding: USDC_holding,
1038
+ nonUSDCHolding: nonUSDC,
1039
+ unsettlementPnL: unsettlemnedPnL
1040
+ });
1041
+ const totalValue2 = account.totalValue({
1042
+ totalUnsettlementPnL: unsettlemnedPnL,
1043
+ USDCHolding: USDC_holding,
1044
+ nonUSDCHolding: nonUSDC
1045
+ });
1046
+ const totalUnrealizedROI2 = account.totalUnrealizedROI({
1047
+ totalUnrealizedPnL: unrealizedPnL,
1048
+ totalValue: totalValue2.toNumber()
1049
+ });
1050
+ return [totalCollateral2, totalValue2, totalUnrealizedROI2];
1051
+ }, [holding, formatedPositions, markPrices]);
1052
+ const positionsRows = useMemo(() => {
1053
+ if (!formatedPositions)
1054
+ return null;
1055
+ if (!symbolInfo || !accountInfo)
1056
+ return formatedPositions[0];
1057
+ const total = totalCollateral.toNumber();
1058
+ return formatedPositions[0].map((item) => {
895
1059
  const info = symbolInfo == null ? void 0 : symbolInfo[item.symbol];
896
1060
  const MMR = positions.MMR({
897
1061
  baseMMR: info("base_mmr"),
898
1062
  baseIMR: info("base_imr"),
899
1063
  IMRFactor: accountInfo.imr_factor[info("base")],
900
- positionNotional: positions.notional(
901
- item.position_qty,
902
- price
903
- ),
1064
+ positionNotional: item.notional,
904
1065
  IMR_factor_power: 4 / 5
905
1066
  });
906
1067
  return __spreadProps(__spreadValues({}, item), {
907
- mark_price: price,
1068
+ mm: positions.maintenanceMargin({
1069
+ positionQty: item.position_qty,
1070
+ markPrice: item.mark_price,
1071
+ MMR
1072
+ }),
908
1073
  est_liq_price: positions.liqPrice({
909
- markPrice: price,
910
- totalCollateral,
1074
+ markPrice: item.mark_price,
1075
+ totalCollateral: total,
911
1076
  positionQty: item.position_qty,
912
1077
  MMR
913
1078
  }),
914
- notional: positions.notional(
915
- item.position_qty,
916
- item.average_open_price
917
- ),
918
- unrealized_pnl: positions.unrealizedPnL({
919
- qty: item.position_qty,
920
- openPrice: item.average_open_price,
921
- markPrice: price
922
- })
1079
+ MMR
923
1080
  });
924
1081
  });
925
- }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol]);
926
- const aggregatedData = useMemo(() => {
927
- const aggregatedData2 = {
928
- unsettledPnL: NaN,
929
- unrealPnL: NaN,
930
- notional: NaN
931
- };
932
- if (formatedPositions && formatedPositions.length) {
933
- aggregatedData2.unrealPnL = positions.totalUnrealizedPnL(formatedPositions);
934
- aggregatedData2.notional = positions.totalNotional(formatedPositions);
935
- aggregatedData2.unsettledPnL = positions.totalUnsettlementPnL(
936
- formatedPositions.map((item) => {
937
- var _a;
938
- return __spreadProps(__spreadValues({}, item), {
939
- sum_unitary_funding: (_a = fundingRates[item.symbol]) == null ? void 0 : _a.call(
940
- fundingRates,
941
- "sum_unitary_funding",
942
- 0
943
- )
944
- });
945
- })
946
- );
947
- }
948
- return aggregatedData2;
949
- }, [formatedPositions, fundingRates]);
950
- const showSymbol = useCallback((symbol2) => {
951
- setVisibleSymbol(symbol2);
952
- }, []);
1082
+ }, [formatedPositions, symbolInfo, accountInfo, totalCollateral]);
953
1083
  return [
954
- { rows: formatedPositions, aggregated: aggregatedData },
1084
+ {
1085
+ rows: positionsRows,
1086
+ aggregated: (_a = formatedPositions == null ? void 0 : formatedPositions[1]) != null ? _a : {},
1087
+ totalCollateral,
1088
+ totalValue,
1089
+ totalUnrealizedROI
1090
+ },
955
1091
  createGetter(data, 1),
956
1092
  {
957
1093
  // close: onClosePosition,
958
1094
  loading: false,
959
- showSymbol,
1095
+ // showSymbol,
960
1096
  error,
961
1097
  loadMore: () => {
962
1098
  },
963
1099
  refresh: () => {
964
1100
  }
965
- // toggleHideOthers,
966
- // filter: (filter: string) => {},
967
1101
  }
968
1102
  ];
969
1103
  };
970
- var totalUnsettlementPnLPath = pathOr(0, [0, "aggregated", "unsettledPnL"]);
1104
+ var useHolding = () => {
1105
+ const { data, isLoading } = usePrivateQuery(
1106
+ "/v1/client/holding",
1107
+ {
1108
+ formatter: (data2) => {
1109
+ return data2.holding;
1110
+ }
1111
+ }
1112
+ );
1113
+ const usdc = useMemo(() => {
1114
+ const usdc2 = data == null ? void 0 : data.find((item) => item.token === "USDC");
1115
+ return usdc2;
1116
+ }, [data]);
1117
+ return {
1118
+ data,
1119
+ usdc,
1120
+ isLoading
1121
+ };
1122
+ };
1123
+
1124
+ // src/orderly/useCollateral.ts
971
1125
  var positionsPath = pathOr([], [0, "rows"]);
1126
+ pathOr(0, [0, "totalCollateral"]);
1127
+ var unsettledPnL = pathOr(0, [0, "aggregated", "unsettledPnL"]);
972
1128
  var useCollateral = (options = { dp: 6 }) => {
973
1129
  const { dp } = options;
974
1130
  const positions2 = usePositionStream();
@@ -976,46 +1132,13 @@ var useCollateral = (options = { dp: 6 }) => {
976
1132
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
977
1133
  const symbolInfo = useSymbolsInfo();
978
1134
  const { data: markPrices } = useMarkPricesStream();
979
- const { data: holding } = usePrivateQuery(
980
- "/v1/client/holding",
981
- {
982
- formatter: (data) => {
983
- return data.holding;
984
- }
985
- }
986
- );
1135
+ const { usdc } = useHolding();
987
1136
  const [totalCollateral, totalValue] = useMemo(() => {
988
- if (!holding || !markPrices) {
989
- return [zero, zero];
990
- }
991
- const unsettlemnedPnL = totalUnsettlementPnLPath(positions2);
992
- const nonUSDC = [];
993
- let USDC_holding = 0;
994
- holding.forEach((item) => {
995
- var _a;
996
- if (item.token === "USDC") {
997
- USDC_holding = item.holding;
998
- } else {
999
- nonUSDC.push({
1000
- holding: item.holding,
1001
- markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
1002
- // markPrice: 0,
1003
- discount: 0
1004
- });
1005
- }
1006
- });
1007
- const number = account.totalCollateral({
1008
- USDCHolding: USDC_holding,
1009
- nonUSDCHolding: nonUSDC,
1010
- unsettlementPnL: unsettlemnedPnL
1011
- });
1012
- const totalValue2 = account.totalValue({
1013
- totalUnsettlementPnL: unsettlemnedPnL,
1014
- USDCHolding: USDC_holding,
1015
- nonUSDCHolding: nonUSDC
1016
- });
1017
- return [new Decimal(number), totalValue2];
1018
- }, [holding, positions2, markPrices]);
1137
+ return [
1138
+ pathOr(zero, [0, "totalCollateral"], positions2),
1139
+ pathOr(zero, [0, "totalValue"], positions2)
1140
+ ];
1141
+ }, [positions2, markPrices]);
1019
1142
  const totalInitialMarginWithOrders = useMemo(() => {
1020
1143
  if (!accountInfo || !symbolInfo || !markPrices) {
1021
1144
  return 0;
@@ -1029,19 +1152,32 @@ var useCollateral = (options = { dp: 6 }) => {
1029
1152
  symbolInfo
1030
1153
  });
1031
1154
  }, [positions2, orders, markPrices, accountInfo, symbolInfo]);
1032
- return {
1033
- totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1034
- freeCollateral: account.freeCollateral({
1155
+ const freeCollateral = useMemo(() => {
1156
+ return account.freeCollateral({
1035
1157
  totalCollateral,
1036
1158
  totalInitialMarginWithOrders
1037
- }).toDecimalPlaces(dp).toNumber(),
1038
- totalValue: totalValue.toDecimalPlaces(dp).toNumber()
1159
+ });
1160
+ }, [totalCollateral, totalInitialMarginWithOrders]);
1161
+ const availableBalance = useMemo(() => {
1162
+ var _a;
1163
+ return account.availableBalance({
1164
+ USDCHolding: (_a = usdc == null ? void 0 : usdc.holding) != null ? _a : 0,
1165
+ unsettlementPnL: unsettledPnL(positions2)
1166
+ });
1167
+ }, [usdc]);
1168
+ return {
1169
+ totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1170
+ freeCollateral: freeCollateral.toDecimalPlaces(dp).toNumber(),
1171
+ totalValue: totalValue.toDecimalPlaces(dp).toNumber(),
1172
+ availableBalance
1039
1173
  };
1040
1174
  };
1041
1175
  var positionsPath2 = pathOr([], [0, "rows"]);
1042
1176
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1043
1177
  const positionsData = usePositionStream();
1044
- const { data: orders } = usePrivateQuery(`/v1/orders`);
1178
+ const { data: orders } = usePrivateQuery(
1179
+ `/v1/orders?status=NEW`
1180
+ );
1045
1181
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1046
1182
  const symbolInfo = useSymbolsInfo();
1047
1183
  const { totalCollateral } = useCollateral();
@@ -1210,12 +1346,16 @@ var LimitOrderCreator = class extends BaseOrderCreator {
1210
1346
  if (price.lt(minPriceNumber)) {
1211
1347
  errors.order_price = {
1212
1348
  type: "min",
1213
- message: `price must be greater than ${minPriceNumber}`
1349
+ message: `price must be greater than ${new Decimal(
1350
+ minPriceNumber
1351
+ ).todp(symbol.quote_dp)}`
1214
1352
  };
1215
1353
  } else if (price.gt(maxPriceNumber)) {
1216
1354
  errors.order_price = {
1217
1355
  type: "max",
1218
- message: `price must be less than ${maxPriceNumber}`
1356
+ message: `price must be less than ${new Decimal(
1357
+ maxPriceNumber
1358
+ ).todp(symbol.quote_dp)}`
1219
1359
  };
1220
1360
  }
1221
1361
  }
@@ -1452,6 +1592,7 @@ var useLeverage = () => {
1452
1592
  return [prop("max_leverage", data), { update: updateLeverage }];
1453
1593
  };
1454
1594
  var useFundingRate = (symbol) => {
1595
+ var _a;
1455
1596
  if (!symbol) {
1456
1597
  throw new Error("useFuturesForSymbol requires a symbol");
1457
1598
  }
@@ -1486,16 +1627,17 @@ var useFundingRate = (symbol) => {
1486
1627
  };
1487
1628
  }, [data]);
1488
1629
  return __spreadProps(__spreadValues({}, data), {
1630
+ est_funding_rate: (Number((_a = data == null ? void 0 : data.est_funding_rate) != null ? _a : 0) * 100).toFixed(4),
1489
1631
  countDown
1490
1632
  });
1491
1633
  };
1492
1634
  var fetcher3 = (url, init) => get(url, init);
1493
1635
  var usePrivateInfiniteQuery = (getKey, options) => {
1494
1636
  var _a;
1495
- const account4 = useAccount();
1637
+ const account5 = useAccount();
1496
1638
  const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
1497
1639
  const result = useSWRInfinite(
1498
- (pageIndex, previousPageData) => account4.state.status >= AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1640
+ (pageIndex, previousPageData) => account5.state.status >= AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1499
1641
  fetcher3,
1500
1642
  __spreadProps(__spreadValues({}, options), {
1501
1643
  use: [signatureMiddleware, ...middleware]
@@ -1512,8 +1654,10 @@ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1512
1654
  return OrderStatus2;
1513
1655
  })(OrderStatus || {});
1514
1656
  var useOrderStream = ({
1515
- status = "NEW" /* NEW */,
1516
- symbol
1657
+ status,
1658
+ symbol,
1659
+ side,
1660
+ size = 100
1517
1661
  } = {}) => {
1518
1662
  const { data: markPrices = {} } = useMarkPricesStream();
1519
1663
  const [doCancelOrder] = useMutation("/v1/order", "DELETE");
@@ -1521,13 +1665,19 @@ var useOrderStream = ({
1521
1665
  const ordersResponse = usePrivateInfiniteQuery(
1522
1666
  (pageIndex, previousPageData) => {
1523
1667
  const search = new URLSearchParams([
1524
- ["size", "100"],
1525
- ["page", `${pageIndex + 1}`],
1526
- [`status`, status]
1668
+ ["size", size.toString()],
1669
+ ["page", `${pageIndex + 1}`]
1670
+ // [`status`, status],
1527
1671
  ]);
1672
+ if (status) {
1673
+ search.set(`status`, status);
1674
+ }
1528
1675
  if (symbol) {
1529
1676
  search.set(`symbol`, symbol);
1530
1677
  }
1678
+ if (side) {
1679
+ search.set(`side`, side);
1680
+ }
1531
1681
  return `/v1/orders?${search.toString()}`;
1532
1682
  },
1533
1683
  {
@@ -1578,15 +1728,35 @@ var useOrderStream = ({
1578
1728
  }
1579
1729
  ];
1580
1730
  };
1581
-
1582
- // src/orderly/useMarketTradeStream.ts
1583
- var useMarketTradeStream = (symbol) => {
1731
+ var useMarketTradeStream = (symbol, options = {}) => {
1584
1732
  if (!symbol) {
1585
1733
  throw new Error("useTradeStream: symbol is required");
1586
1734
  }
1735
+ useState([]);
1736
+ const { level = 20 } = options;
1587
1737
  const { data, isLoading } = useQuery(
1588
- `/v1/public/market_trades?symbol=${symbol}&limit=20`
1738
+ `/v1/public/market_trades?symbol=${symbol}&limit=${level}`
1739
+ // {
1740
+ // onSuccess: (data) => {
1741
+ // // console.log("trades ^^^^^^", data);
1742
+ // if (Array.isArray(data)) {
1743
+ // setTrades(data);
1744
+ // }
1745
+ // return data;
1746
+ // },
1747
+ // }
1589
1748
  );
1749
+ const ws = useWS();
1750
+ useEffect(() => {
1751
+ const unsubscript = ws.subscribe(`@${symbol}/@trade`, {
1752
+ onMessage: (data2) => {
1753
+ console.log("trade", data2);
1754
+ }
1755
+ });
1756
+ return () => {
1757
+ unsubscript == null ? void 0 : unsubscript();
1758
+ };
1759
+ }, []);
1590
1760
  return { data, isLoading };
1591
1761
  };
1592
1762
 
@@ -1607,17 +1777,21 @@ var useMarginRatio = () => {
1607
1777
  });
1608
1778
  return ratio;
1609
1779
  }, [rows, markPrices, totalCollateral]);
1610
- return marginRatio;
1780
+ const currentLeverage = useMemo(() => {
1781
+ return account.currentLeverage(marginRatio);
1782
+ }, [marginRatio]);
1783
+ return [marginRatio, currentLeverage];
1611
1784
  };
1612
- var useChains = (networkId, options) => {
1785
+ var useChains = (networkId, options = {}) => {
1786
+ const _a = options, swrOptions = __objRest(_a, ["filter", "pick"]);
1613
1787
  const field = options == null ? void 0 : options.pick;
1614
1788
  const { data } = useSWR(
1615
1789
  "https://fi-api.woo.org/swap_support",
1616
1790
  (url) => fetch(url).then((res) => res.json()),
1617
- {
1791
+ __spreadValues({
1618
1792
  revalidateOnFocus: false,
1619
1793
  revalidateOnReconnect: false
1620
- }
1794
+ }, swrOptions)
1621
1795
  );
1622
1796
  const chains = useMemo(() => {
1623
1797
  if (!data || !data.data)
@@ -1675,7 +1849,7 @@ var usePrivateDataObserver = () => {
1675
1849
  const unsubscribe = ws.privateSubscribe("executionreport", {
1676
1850
  onMessage: (data) => {
1677
1851
  console.info("refresh orders");
1678
- mutate2("/v1/orders");
1852
+ console.log(data);
1679
1853
  }
1680
1854
  });
1681
1855
  return () => unsubscribe == null ? void 0 : unsubscribe();
@@ -1711,7 +1885,6 @@ var useExecutionReport = () => {
1711
1885
  // src/apis/index.ts
1712
1886
  var apis_exports = {};
1713
1887
  __export(apis_exports, {
1714
- useFundingRate: () => useFundingRate2,
1715
1888
  useFundingRateBySymbol: () => useFundingRateBySymbol,
1716
1889
  useInfo: () => useInfo,
1717
1890
  useToken: () => useToken
@@ -1737,11 +1910,6 @@ var useFundingRateBySymbol = (symbol) => {
1737
1910
  return useQuery(`/public/funding_rate/${symbol}`);
1738
1911
  };
1739
1912
 
1740
- // src/apis/useFundingRate.ts
1741
- var useFundingRate2 = (symbol) => {
1742
- return useQuery(`/v1/public/funding_rate`);
1743
- };
1744
-
1745
- export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useLeverage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradeStream, useTradingView, useWS };
1913
+ export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useHolding, useLeverage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradeStream, useTradingView, useWS };
1746
1914
  //# sourceMappingURL=out.js.map
1747
1915
  //# sourceMappingURL=index.mjs.map