@orderly.network/hooks 0.0.6 → 0.0.7

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,20 +1,21 @@
1
- import { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
1
+ import React, { createContext, useContext, useCallback, useState, useEffect, useRef, useMemo } from 'react';
2
2
  import useSWR from 'swr';
3
3
  export { default as useSWR } from 'swr';
4
- import { WebSocketClient, get, post } from '@orderly.network/net';
4
+ import { WebSocketClient, WS, get, post } from '@orderly.network/net';
5
5
  import useSWRMutation from 'swr/mutation';
6
- import { getMockSigner, SimpleDI, Account } from '@orderly.network/core';
6
+ import { SimpleDI, Account, getMockSigner } from '@orderly.network/core';
7
7
  import useConstant from 'use-constant';
8
8
  export { default as useConstant } from 'use-constant';
9
9
  import { useObservable, useEventCallback } from 'rxjs-hooks';
10
10
  export { useEventCallback, useObservable } from 'rxjs-hooks';
11
- import { BehaviorSubject, merge, iif } from 'rxjs';
12
- import { map, combineLatestWith, startWith, debounceTime, switchMap, scan, filter, distinct, withLatestFrom } from 'rxjs/operators';
13
- import { compose, defaultTo, head, last, pathOr, pick } from 'ramda';
11
+ import { AccountStatusEnum, SystemStateEnum, ExchangeStatusEnum, OrderSide, OrderType } from '@orderly.network/types';
12
+ import { BehaviorSubject, merge } from 'rxjs';
13
+ import { map, combineLatestWith, startWith, debounceTime, switchMap, scan, withLatestFrom } from 'rxjs/operators';
14
+ import { compose, defaultTo, head, last, pathOr, pick, propOr } from 'ramda';
14
15
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
15
- import { OrderSide, OrderType } from '@orderly.network/types';
16
16
  import { useFormik } from 'formik';
17
17
  import { positions, account, order } from '@orderly.network/futures';
18
+ import useSWRSubscription from 'swr/subscription';
18
19
  import useSWRInfinite from 'swr/infinite';
19
20
 
20
21
  var __defProp = Object.defineProperty;
@@ -82,15 +83,16 @@ var fetcher = (url, init = {}, queryOptions) => get(url, init, queryOptions == n
82
83
  var useQuery = (query, options) => {
83
84
  const { apiBaseUrl } = useContext(OrderlyContext);
84
85
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
85
- if (!query.startsWith("/public")) {
86
+ if (typeof query === "string" && !query.startsWith("/public")) {
86
87
  throw new Error("useQuery is only for public api");
87
88
  }
88
89
  if (typeof apiBaseUrl === "undefined") {
89
90
  throw new Error("please add OrderlyProvider to your app");
90
91
  }
91
92
  return useSWR(
92
- `${apiBaseUrl}${query}`,
93
- (url, init) => fetcher(url, init, { formatter }),
93
+ // `${apiBaseUrl}${query}`,
94
+ query,
95
+ (url, init) => fetcher(`${apiBaseUrl}${url}`, init, { formatter }),
94
96
  swrOptions
95
97
  );
96
98
  };
@@ -106,7 +108,8 @@ var useMutation = (url, options) => {
106
108
  if (!url.startsWith("http")) {
107
109
  url = `${apiBaseUrl}${url}`;
108
110
  }
109
- const signer = getMockSigner();
111
+ let account3 = SimpleDI.get("account");
112
+ const signer = account3.signer;
110
113
  const { trigger, data, error, reset, isMutating } = useSWRMutation(
111
114
  url,
112
115
  fetcher2,
@@ -130,33 +133,84 @@ var useMutation = (url, options) => {
130
133
  };
131
134
  };
132
135
  var signatureMiddleware = (useSWRNext) => {
136
+ const { apiBaseUrl } = useContext(OrderlyContext);
133
137
  return (key, fetcher4, config) => {
134
- const extendedFetcher = (url) => __async(void 0, null, function* () {
135
- const signer = getMockSigner();
136
- const payload = {
137
- method: "GET",
138
- url
139
- };
140
- const signature = yield signer.sign(payload);
141
- return fetcher4(url, {
142
- headers: __spreadProps(__spreadValues({}, signature), {
143
- "orderly-account-id": "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b"
144
- })
138
+ try {
139
+ const extendedFetcher = (url) => __async(void 0, null, function* () {
140
+ let account3 = SimpleDI.get("account");
141
+ let fullUrl = `${apiBaseUrl}${url}`;
142
+ const signer = account3.signer;
143
+ const payload = {
144
+ method: "GET",
145
+ url: fullUrl
146
+ };
147
+ const signature = yield signer.sign(payload);
148
+ return fetcher4(fullUrl, {
149
+ headers: __spreadProps(__spreadValues({}, signature), {
150
+ "orderly-account-id": account3.accountId
151
+ // "orderly-account-id":
152
+ // "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b",
153
+ })
154
+ });
145
155
  });
146
- });
147
- return useSWRNext(key, extendedFetcher, config);
156
+ return useSWRNext(key, extendedFetcher, config);
157
+ } catch (e) {
158
+ console.error("signature error:", e);
159
+ throw e;
160
+ }
161
+ };
162
+ };
163
+ var useAccount = () => {
164
+ const { configStore, keyStore, walletAdapter } = useContext(OrderlyContext);
165
+ if (!configStore)
166
+ throw new Error("configStore is not defined, please use OrderlyProvider");
167
+ if (!keyStore) {
168
+ throw new Error(
169
+ "keyStore is not defined, please use OrderlyProvider and provide keyStore"
170
+ );
171
+ }
172
+ const account3 = useConstant(() => {
173
+ let account4 = SimpleDI.get("account");
174
+ if (!account4) {
175
+ account4 = new Account(configStore, keyStore, walletAdapter);
176
+ SimpleDI.registerByName("account", account4);
177
+ }
178
+ return account4;
179
+ });
180
+ const state = useObservable(
181
+ () => account3.state$,
182
+ account3.stateValue
183
+ );
184
+ const login = useCallback(
185
+ (address) => {
186
+ account3.login(address);
187
+ },
188
+ [account3]
189
+ );
190
+ return {
191
+ // account: state!,
192
+ account: account3,
193
+ state,
194
+ // info: {},
195
+ login
148
196
  };
149
197
  };
150
198
  var usePrivateQuery = (query, options) => {
151
199
  var _b;
152
- const { apiBaseUrl } = useContext(OrderlyContext);
153
200
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
201
+ const account3 = useAccount();
154
202
  const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_b = options == null ? void 0 : options.use) != null ? _b : [] : [];
155
203
  return useSWR(
156
- `${apiBaseUrl}${query}`,
157
- (url, init) => fetcher(url, init, { formatter }),
204
+ () => account3.state.status >= AccountStatusEnum.SignedIn ? query : null,
205
+ // query,
206
+ (url, init) => {
207
+ return fetcher(url, init, { formatter });
208
+ },
158
209
  __spreadProps(__spreadValues({}, swrOptions), {
159
- use: [signatureMiddleware, ...middleware]
210
+ use: [signatureMiddleware, ...middleware],
211
+ onError: (err) => {
212
+ console.log("usePrivateQuery error", err);
213
+ }
160
214
  })
161
215
  );
162
216
  };
@@ -185,41 +239,106 @@ var useTopicObserve = (topic) => {
185
239
  data
186
240
  };
187
241
  };
188
- var useAccount = () => {
189
- const { configStore } = useContext(OrderlyContext);
242
+ var AppState = class {
243
+ constructor() {
244
+ this.systemState$ = new BehaviorSubject(SystemStateEnum.Loading);
245
+ this.exchangeState$ = new BehaviorSubject(ExchangeStatusEnum.Normal);
246
+ this.prepare = ["symbolInfo", "clientInfo"];
247
+ }
248
+ updateState(name) {
249
+ this.prepare = this.prepare.filter((item) => item !== name);
250
+ if (this.prepare.length === 0) {
251
+ this.systemState$.next(SystemStateEnum.Ready);
252
+ }
253
+ }
254
+ udpateSystemState(state) {
255
+ this.systemState$.next(state);
256
+ }
257
+ updateExchangeState(state) {
258
+ this.exchangeState$.next(state);
259
+ }
260
+ };
261
+ AppState.instanceName = "AppState";
262
+ SimpleDI.registerByName(AppState.instanceName, new AppState());
263
+ function getAppState() {
264
+ return SimpleDI.get(AppState.instanceName);
265
+ }
266
+
267
+ // src/useAppState.ts
268
+ var useAppState = () => {
269
+ const appState = getAppState();
270
+ return useObservable(
271
+ () => merge(appState.exchangeState$, appState.systemState$).pipe(
272
+ map((data) => {
273
+ return {
274
+ systemState: SystemStateEnum.Ready,
275
+ exchangeState: ExchangeStatusEnum.Normal
276
+ };
277
+ })
278
+ ),
279
+ {
280
+ systemState: appState.systemState$.value,
281
+ exchangeState: appState.exchangeState$.value
282
+ }
283
+ );
284
+ };
285
+ var WS_NAME = "websocketClient";
286
+ var useWebSocketClient = () => {
287
+ const ws = useConstant(() => {
288
+ let websocketClient = SimpleDI.get(WS_NAME);
289
+ if (!websocketClient) {
290
+ websocketClient = new WebSocketClient({
291
+ accountId: "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b",
292
+ networkId: "testnet",
293
+ onSigntureRequest: (accountId) => __async(void 0, null, function* () {
294
+ const signer = getMockSigner();
295
+ const timestamp = (/* @__PURE__ */ new Date()).getTime();
296
+ const result = yield signer.signText(timestamp.toString());
297
+ return __spreadProps(__spreadValues({}, result), { timestamp });
298
+ })
299
+ });
300
+ SimpleDI.registerByName(WS_NAME, websocketClient);
301
+ }
302
+ return websocketClient;
303
+ });
304
+ return ws;
305
+ };
306
+ var useAccountInstance = () => {
307
+ const { configStore, keyStore } = useContext(OrderlyContext);
190
308
  if (!configStore)
191
309
  throw new Error("configStore is not defined, please use OrderlyProvider");
310
+ if (!keyStore) {
311
+ throw new Error(
312
+ "keyStore is not defined, please use OrderlyProvider and provide keyStore"
313
+ );
314
+ }
192
315
  const account3 = useConstant(() => {
193
316
  let account4 = SimpleDI.get("account");
194
317
  if (!account4) {
195
- account4 = new Account(configStore);
318
+ account4 = new Account(configStore, keyStore);
196
319
  SimpleDI.registerByName("account", account4);
197
320
  }
198
321
  return account4;
199
322
  });
200
- const { data: accountInfo } = usePrivateQuery("/client/info");
201
- const state = useObservable(
202
- () => account3.state$,
203
- account3.stateValue
204
- );
205
- const login = useCallback(
206
- (address) => {
207
- account3.login(address);
208
- },
209
- [account3]
210
- );
211
- return {
212
- account: state,
213
- info: accountInfo,
214
- login
215
- };
323
+ console.log("account instance ======>>>>>", account3);
324
+ return account3;
216
325
  };
217
- var WS_NAME = "websocketClient";
218
- var useWebSocketClient = () => {
326
+
327
+ // src/provider/dataProvider.tsx
328
+ var DataSourceContext = createContext({});
329
+ var DataSourceProvider = (props) => {
330
+ console.log("render DataSourceProvider");
331
+ useAccountInstance();
332
+ useConstant(() => {
333
+ });
334
+ return /* @__PURE__ */ React.createElement(DataSourceContext.Provider, { value: {} }, props.children);
335
+ };
336
+ var WS_NAME2 = "nativeWebsocketClient";
337
+ var useWS = () => {
219
338
  const ws = useConstant(() => {
220
- let websocketClient = SimpleDI.get(WS_NAME);
339
+ let websocketClient = SimpleDI.get(WS_NAME2);
221
340
  if (!websocketClient) {
222
- websocketClient = new WebSocketClient({
341
+ websocketClient = new WS({
223
342
  accountId: "0x47ab075adca7dfe9dd206eb7c50a10f7b99f4f08fa6c3abd4c170d438e15093b",
224
343
  networkId: "testnet",
225
344
  onSigntureRequest: (accountId) => __async(void 0, null, function* () {
@@ -229,7 +348,7 @@ var useWebSocketClient = () => {
229
348
  return __spreadProps(__spreadValues({}, result), { timestamp });
230
349
  })
231
350
  });
232
- SimpleDI.registerByName(WS_NAME, websocketClient);
351
+ SimpleDI.registerByName(WS_NAME2, websocketClient);
233
352
  }
234
353
  return websocketClient;
235
354
  });
@@ -656,77 +775,107 @@ var useMarkPricesSubject = () => {
656
775
  )
657
776
  );
658
777
  };
659
-
660
- // src/orderly/usePositionStream.ts
778
+ var useMarkPricesStream = () => {
779
+ const ws = useWS();
780
+ return useSWRSubscription("markPrices", (key, { next }) => {
781
+ const unsubscribe = ws.subscription(
782
+ { event: "subscribe", topic: "markprices" },
783
+ {
784
+ onMessage: (message) => {
785
+ const data = /* @__PURE__ */ Object.create(null);
786
+ for (let index = 0; index < message.length; index++) {
787
+ const element = message[index];
788
+ data[element.symbol] = element.price;
789
+ }
790
+ next(null, data);
791
+ },
792
+ onUnsubscribe: () => {
793
+ return "markprices";
794
+ },
795
+ onError: (error) => {
796
+ console.log("error", error);
797
+ }
798
+ }
799
+ );
800
+ return () => {
801
+ console.log("unsubscribe!!!!!!!");
802
+ console.log("unsubscribe", unsubscribe);
803
+ unsubscribe == null ? void 0 : unsubscribe();
804
+ };
805
+ });
806
+ };
661
807
  var usePositionStream = (symbol, options) => {
808
+ useState(false);
662
809
  const [visibledSymbol, setVisibleSymbol] = useState(
663
810
  symbol
664
811
  );
665
812
  const symbolInfo = useSymbolsInfo();
666
- const { info: accountInfo } = useAccount();
813
+ const { data: accountInfo } = usePrivateQuery("/client/info");
814
+ const { mutation } = useMutation("/order");
667
815
  const fundingRates = useFundingRates();
668
- const markPrices$ = useMarkPricesSubject();
816
+ useMarkPricesSubject();
669
817
  const { data, error, isLoading } = usePrivateQuery(
670
818
  `/positions`,
671
819
  __spreadProps(__spreadValues({}, options), {
672
- formatter: (data2) => data2
820
+ formatter: (data2) => data2,
821
+ onError: (err) => {
822
+ console.log("usePositionStream error", err);
823
+ }
673
824
  })
674
825
  );
675
- const value = useObservable(
676
- (_, input$) => input$.pipe(
677
- // map((data) => {
678
- // return data[0];
679
- // }),
680
- combineLatestWith(markPrices$),
681
- debounceTime(100),
682
- map(([[data2, symbolInfo2, accountInfo2], markPrices]) => {
683
- let totalCollateral = 0;
684
- return data2 == null ? void 0 : data2.map((item) => {
685
- var _a;
686
- const price = (_a = markPrices[item.symbol]) != null ? _a : item.mark_price;
687
- const info = symbolInfo2 == null ? void 0 : symbolInfo2[item.symbol];
688
- const MMR = positions.MMR({
689
- baseMMR: info("base_mmr"),
690
- baseIMR: info("base_imr"),
691
- IMRFactor: accountInfo2.imr_factor[info("base")],
692
- positionNotional: positions.notional(item.position_qty, price),
693
- IMR_factor_power: 4 / 5
694
- });
695
- return __spreadProps(__spreadValues({}, item), {
696
- mark_price: price,
697
- est_liq_price: positions.liqPrice({
698
- markPrice: price,
699
- totalCollateral,
700
- positionQty: item.position_qty,
701
- MMR
702
- }),
703
- notional: positions.notional(
704
- item.position_qty,
705
- item.average_open_price
706
- ),
707
- unrealized_pnl: positions.unrealizedPnL({
708
- qty: item.position_qty,
709
- openPrice: item.average_open_price,
710
- markPrice: price
711
- })
712
- });
713
- });
714
- })
715
- ),
716
- void 0,
717
- [data == null ? void 0 : data.rows, symbolInfo, accountInfo]
718
- );
826
+ const { data: markPrices } = useMarkPricesStream();
827
+ const formatedPositions = useMemo(() => {
828
+ if (!(data == null ? void 0 : data.rows) || !symbolInfo || !accountInfo)
829
+ return null;
830
+ let totalCollateral = 0;
831
+ return data.rows.map((item) => {
832
+ const price = propOr(
833
+ item.mark_price,
834
+ item.symbol,
835
+ markPrices
836
+ );
837
+ const info = symbolInfo == null ? void 0 : symbolInfo[item.symbol];
838
+ const MMR = positions.MMR({
839
+ baseMMR: info("base_mmr"),
840
+ baseIMR: info("base_imr"),
841
+ IMRFactor: accountInfo.imr_factor[info("base")],
842
+ positionNotional: positions.notional(
843
+ item.position_qty,
844
+ price
845
+ ),
846
+ IMR_factor_power: 4 / 5
847
+ });
848
+ return __spreadProps(__spreadValues({}, item), {
849
+ mark_price: price,
850
+ est_liq_price: positions.liqPrice({
851
+ markPrice: price,
852
+ totalCollateral,
853
+ positionQty: item.position_qty,
854
+ MMR
855
+ }),
856
+ notional: positions.notional(
857
+ item.position_qty,
858
+ item.average_open_price
859
+ ),
860
+ unrealized_pnl: positions.unrealizedPnL({
861
+ qty: item.position_qty,
862
+ openPrice: item.average_open_price,
863
+ markPrice: price
864
+ })
865
+ });
866
+ });
867
+ }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices]);
719
868
  const aggregatedData = useMemo(() => {
720
869
  const aggregatedData2 = {
721
870
  unsettledPnL: NaN,
722
871
  unrealPnL: NaN,
723
872
  notional: NaN
724
873
  };
725
- if (value && value.length) {
726
- aggregatedData2.unrealPnL = positions.totalUnrealizedPnL(value);
727
- aggregatedData2.notional = positions.totalNotional(value);
874
+ if (formatedPositions && formatedPositions.length) {
875
+ aggregatedData2.unrealPnL = positions.totalUnrealizedPnL(formatedPositions);
876
+ aggregatedData2.notional = positions.totalNotional(formatedPositions);
728
877
  aggregatedData2.unsettledPnL = positions.totalUnsettlementPnL(
729
- value.map((item) => {
878
+ formatedPositions.map((item) => {
730
879
  var _a;
731
880
  return __spreadProps(__spreadValues({}, item), {
732
881
  sum_unitary_funding: (_a = fundingRates[item.symbol]) == null ? void 0 : _a.call(
@@ -739,16 +888,22 @@ var usePositionStream = (symbol, options) => {
739
888
  );
740
889
  }
741
890
  return aggregatedData2;
742
- }, [value, fundingRates]);
891
+ }, [formatedPositions, fundingRates]);
743
892
  const showSymbol = useCallback((symbol2) => {
744
893
  setVisibleSymbol(symbol2);
745
894
  }, []);
895
+ const onClosePosition = useCallback(
896
+ (order2) => {
897
+ return mutation(order2).finally(() => {
898
+ });
899
+ },
900
+ []
901
+ );
746
902
  return [
747
- { rows: value, aggregated: aggregatedData },
903
+ { rows: formatedPositions, aggregated: aggregatedData },
748
904
  createGetter(data, 1),
749
905
  {
750
- close: (qty) => {
751
- },
906
+ close: onClosePosition,
752
907
  loading: false,
753
908
  showSymbol,
754
909
  error,
@@ -761,320 +916,155 @@ var usePositionStream = (symbol, options) => {
761
916
  }
762
917
  ];
763
918
  };
764
- var fetcher3 = (url, init) => get(url, init);
765
- var usePrivateInfiniteQuery = (getKey, options) => {
766
- var _a;
767
- const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
768
- const { apiBaseUrl } = useContext(OrderlyContext);
769
- const result = useSWRInfinite(
770
- (index, prevData) => `${apiBaseUrl}${getKey(index, prevData)}`,
771
- fetcher3,
772
- __spreadProps(__spreadValues({}, options), {
773
- use: [signatureMiddleware, ...middleware]
774
- })
775
- );
776
- return result;
777
- };
778
- var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
779
- OrderStatus2["FILLED"] = "FILLED";
780
- OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
781
- OrderStatus2["CANCELED"] = "CANCELED";
782
- OrderStatus2["NEW"] = "NEW";
783
- OrderStatus2["COMPLETED"] = "COMPLETED";
784
- return OrderStatus2;
785
- })(OrderStatus || {});
786
- var useOrderStream = ({
787
- status = "NEW" /* NEW */,
788
- symbol
789
- } = {}) => {
790
- var _a;
791
- const markPrices$ = useMarkPricesSubject();
792
- const res = usePrivateInfiniteQuery(
793
- (pageIndex, previousPageData) => {
794
- const search = new URLSearchParams([
795
- ["size", "100"],
796
- ["page", `${pageIndex + 1}`],
797
- [`status`, status]
798
- ]);
799
- if (symbol) {
800
- search.set(`symbol`, symbol);
801
- }
802
- return `/orders?${search.toString()}`;
803
- },
804
- {
805
- initialSize: 1,
806
- onError: (err) => {
807
- console.error("fetch failed::::", err);
808
- }
809
- }
810
- );
811
- const orders = useObservable(
812
- (_, input$) => input$.pipe(
813
- map(([data]) => {
814
- return data.flat();
815
- }),
816
- combineLatestWith(markPrices$),
817
- map(([data, markPrices]) => {
818
- return data.map((item) => {
819
- var _a2;
820
- return __spreadProps(__spreadValues({}, item), {
821
- mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
822
- });
823
- });
824
- })
825
- ),
826
- null,
827
- [(_a = res.data) != null ? _a : []]
828
- );
829
- const cancelAllOrders = useCallback(() => {
830
- }, [res.data]);
831
- const updateOrder = useCallback((id, data) => {
832
- }, []);
833
- const cancelOrder = useCallback((id) => {
834
- }, []);
835
- return [
836
- orders,
837
- // {
838
- // ...res,
839
- // data: res.data?.reduce((acc, cur) => {
840
- // return [...acc, ...cur];
841
- // }, []),
842
- // },
843
- {
844
- cancelAllOrders,
845
- updateOrder,
846
- cancelOrder
847
- }
848
- ];
849
- };
850
- var useMarkPriceStream = () => {
851
- const markPrice$ = useMarkPricesSubject();
852
- return useObservable(() => markPrice$, {});
853
- };
854
-
855
- // src/orderly/useCollateral.ts
856
919
  var totalUnsettlementPnLPath = pathOr(0, [0, "aggregated", "unsettledPnL"]);
857
920
  var positionsPath = pathOr([], [0, "rows"]);
858
921
  var useCollateral = (dp = 6) => {
859
922
  const positions2 = usePositionStream();
860
- const orders = useOrderStream();
861
- const { info: accountInfo } = useAccount();
923
+ const { data: orders } = usePrivateQuery(`/orders`);
924
+ const { data: accountInfo } = usePrivateQuery("/client/info");
862
925
  const symbolInfo = useSymbolsInfo();
863
- const markPrices = useMarkPriceStream();
864
- const { data } = usePrivateQuery("/client/holding", {
865
- formatter: (data2) => {
866
- return data2.holding;
926
+ const { data: markPrices } = useMarkPricesStream();
927
+ const { data: holding } = usePrivateQuery("/client/holding", {
928
+ formatter: (data) => {
929
+ return data.holding;
867
930
  }
868
931
  });
869
- const totalCollateral = useObservable(
870
- (_, input$) => merge(input$).pipe(
871
- debounceTime(100),
872
- filter((data2) => !!data2[0]),
873
- map(
874
- ([data2, unsettlemnedPnL, markPrices2]) => {
875
- const nonUSDC = [];
876
- let USDC_holding = 0;
877
- data2.forEach((item) => {
878
- if (item.token === "USDC") {
879
- USDC_holding = item.holding;
880
- } else {
881
- nonUSDC.push({
882
- holding: item.holding,
883
- // markPrice: markPrices[item.token] ?? 0,
884
- markPrice: 0,
885
- discount: 0
886
- });
887
- }
888
- });
889
- const number = account.totalCollateral({
890
- USDCHolding: USDC_holding,
891
- nonUSDCHolding: nonUSDC,
892
- unsettlementPnL: unsettlemnedPnL
893
- });
894
- return new Decimal(number);
895
- }
896
- )
897
- ),
898
- zero,
899
- [data, totalUnsettlementPnLPath(positions2), markPrices]
900
- );
901
- const totalInitialMarginWithOrders = useObservable(
902
- (_, input$) => input$.pipe(
903
- filter((data2) => !!data2[3] && !!data2[4]),
904
- map(([positions3, orders2, markPrices2, accountInfo2, symbolInfo2]) => {
905
- var _a;
906
- return account.totalInitialMarginWithOrders({
907
- positions: positionsPath(positions3),
908
- orders: (_a = orders2 == null ? void 0 : orders2[0]) != null ? _a : [],
909
- markPrices: markPrices2,
910
- IMR_Factors: accountInfo2.imr_factor,
911
- maxLeverage: accountInfo2.max_leverage,
912
- symbolInfo: symbolInfo2
932
+ const [totalCollateral, totalValue] = useMemo(() => {
933
+ if (!holding || !markPrices) {
934
+ return [zero, zero];
935
+ }
936
+ const unsettlemnedPnL = totalUnsettlementPnLPath(positions2);
937
+ const nonUSDC = [];
938
+ let USDC_holding = 0;
939
+ holding.forEach((item) => {
940
+ var _a;
941
+ if (item.token === "USDC") {
942
+ USDC_holding = item.holding;
943
+ } else {
944
+ nonUSDC.push({
945
+ holding: item.holding,
946
+ markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
947
+ // markPrice: 0,
948
+ discount: 0
913
949
  });
914
- })
915
- ),
916
- 0,
917
- [positions2, orders, markPrices, accountInfo, symbolInfo]
918
- );
950
+ }
951
+ });
952
+ const number = account.totalCollateral({
953
+ USDCHolding: USDC_holding,
954
+ nonUSDCHolding: nonUSDC,
955
+ unsettlementPnL: unsettlemnedPnL
956
+ });
957
+ const totalValue2 = account.totalValue({
958
+ totalUnsettlementPnL: unsettlemnedPnL,
959
+ USDCHolding: USDC_holding,
960
+ nonUSDCHolding: nonUSDC
961
+ });
962
+ return [new Decimal(number), totalValue2];
963
+ }, [holding, positions2, markPrices]);
964
+ const totalInitialMarginWithOrders = useMemo(() => {
965
+ if (!accountInfo || !symbolInfo || !markPrices) {
966
+ return 0;
967
+ }
968
+ return account.totalInitialMarginWithOrders({
969
+ positions: positionsPath(positions2),
970
+ orders: orders != null ? orders : [],
971
+ markPrices,
972
+ IMR_Factors: accountInfo.imr_factor,
973
+ maxLeverage: accountInfo.max_leverage,
974
+ symbolInfo
975
+ });
976
+ }, [positions2, orders, markPrices, accountInfo, symbolInfo]);
919
977
  return {
920
978
  totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
921
979
  freeCollateral: account.freeCollateral({
922
980
  totalCollateral,
923
981
  totalInitialMarginWithOrders
924
982
  }).toDecimalPlaces(dp).toNumber(),
925
- totalValue: 0
983
+ totalValue: totalValue.toDecimalPlaces(dp).toNumber()
926
984
  };
927
985
  };
928
986
  var positionsPath2 = pathOr([], [0, "rows"]);
929
987
  var useMaxQty = (symbol, side, reduceOnly = false) => {
930
- var _a;
931
- const positions2 = usePositionStream();
932
- const orders = useOrderStream();
933
- const { info: accountInfo } = useAccount();
988
+ const positionsData = usePositionStream();
989
+ const { data: orders } = usePrivateQuery(`/orders`);
990
+ const { data: accountInfo } = usePrivateQuery("/client/info");
934
991
  const symbolInfo = useSymbolsInfo();
935
992
  const { totalCollateral } = useCollateral();
936
- const markPrices = useMarkPriceStream();
937
- const maxQty = useObservable(
938
- (_, input$) => input$.pipe(
939
- switchMap(
940
- ([{ reduceOnly: reduceOnly2 }]) => iif(
941
- () => reduceOnly2,
942
- input$.pipe(
943
- filter(([{ positions: positions3 }]) => positions3.length > 0),
944
- map(
945
- ([
946
- {
947
- positions: positions3,
948
- symbol: symbol2,
949
- side: side2
950
- }
951
- ]) => {
952
- const positionQty = account.getQtyFromPositions(
953
- positions3,
954
- symbol2
955
- );
956
- if (positionQty > 0) {
957
- if (side2 === OrderSide.BUY) {
958
- return 0;
959
- } else {
960
- return Math.abs(positionQty);
961
- }
962
- }
963
- if (positionQty < 0) {
964
- if (side2 === OrderSide.BUY) {
965
- return Math.abs(positionQty);
966
- } else {
967
- return 0;
968
- }
969
- }
970
- return 0;
971
- }
972
- )
973
- ),
974
- input$.pipe(
975
- filter(
976
- ([
977
- {
978
- markPrices: markPrices2,
979
- positions: positions3,
980
- orders: orders2,
981
- accountInfo: accountInfo2,
982
- symbolInfo: symbolInfo2,
983
- symbol: symbol2,
984
- side: side2,
985
- totalCollateral: totalCollateral2
986
- }
987
- ]) => !!symbol2 && !!side2 && !!markPrices2[symbol2] && !!positions3 && !!orders2 && !!accountInfo2 && !!symbolInfo2 && !!totalCollateral2
988
- ),
989
- // 数据准备
990
- map(
991
- ([
992
- {
993
- markPrices: markPrices2,
994
- positions: positions3,
995
- orders: orders2,
996
- accountInfo: accountInfo2,
997
- symbolInfo: symbolInfo2,
998
- symbol: symbol2,
999
- side: side2,
1000
- totalCollateral: totalCollateral2
1001
- }
1002
- ]) => {
1003
- const getSymbolInfo = symbolInfo2[symbol2];
1004
- const positionQty = account.getQtyFromPositions(
1005
- positions3,
1006
- symbol2
1007
- );
1008
- const buyOrdersQty = account.getQtyFromOrdersBySide(
1009
- orders2,
1010
- symbol2,
1011
- OrderSide.BUY
1012
- );
1013
- const sellOrdersQty = account.getQtyFromOrdersBySide(
1014
- orders2,
1015
- symbol2,
1016
- OrderSide.SELL
1017
- );
1018
- const otherPositions = positions3.filter(
1019
- (item) => item.symbol !== symbol2
1020
- );
1021
- const otherOrders = orders2.filter(
1022
- (item) => item.symbol !== symbol2
1023
- );
1024
- const otherIMs = account.otherIMs({
1025
- orders: otherOrders,
1026
- positions: otherPositions,
1027
- symbolInfo: symbolInfo2,
1028
- markPrices: markPrices2,
1029
- IMR_Factors: accountInfo2.imr_factor,
1030
- maxLeverage: accountInfo2.max_leverage
1031
- });
1032
- return [
1033
- side2,
1034
- {
1035
- markPrice: markPrices2[symbol2],
1036
- baseMaxQty: getSymbolInfo("base_max"),
1037
- totalCollateral: totalCollateral2,
1038
- maxLeverage: accountInfo2.max_leverage,
1039
- takerFeeRate: accountInfo2.taker_fee_rate,
1040
- baseIMR: getSymbolInfo("base_imr"),
1041
- otherIMs,
1042
- positionQty,
1043
- buyOrdersQty,
1044
- sellOrdersQty,
1045
- IMR_Factor: accountInfo2.imr_factor[getSymbolInfo("base")]
1046
- },
1047
- {
1048
- dp: getSymbolInfo("base_tick")
1049
- }
1050
- ];
1051
- }
1052
- ),
1053
- map(([side2, inputs, options]) => {
1054
- const maxQty2 = account.maxQty(side2, inputs);
1055
- return maxQty2;
1056
- }),
1057
- distinct()
1058
- // tap((data: number) => console.log("************", data))
1059
- )
1060
- )
1061
- )
1062
- ),
1063
- 0,
1064
- [
1065
- {
1066
- markPrices,
1067
- positions: positionsPath2(positions2),
1068
- orders: (_a = orders[0]) != null ? _a : [],
1069
- accountInfo,
1070
- symbolInfo,
1071
- symbol,
1072
- side,
1073
- totalCollateral,
1074
- reduceOnly
993
+ const { data: markPrices } = useMarkPricesStream();
994
+ const maxQty = useMemo(() => {
995
+ if (!symbol)
996
+ return 0;
997
+ const positions2 = positionsPath2(positionsData);
998
+ const positionQty = account.getQtyFromPositions(positions2, symbol);
999
+ if (reduceOnly) {
1000
+ if (positionQty > 0) {
1001
+ if (side === OrderSide.BUY) {
1002
+ return 0;
1003
+ } else {
1004
+ return Math.abs(positionQty);
1005
+ }
1075
1006
  }
1076
- ]
1077
- );
1007
+ if (positionQty < 0) {
1008
+ if (side === OrderSide.BUY) {
1009
+ return Math.abs(positionQty);
1010
+ } else {
1011
+ return 0;
1012
+ }
1013
+ }
1014
+ return 0;
1015
+ }
1016
+ if (!markPrices || !markPrices[symbol] || !orders || !accountInfo)
1017
+ return 0;
1018
+ const getSymbolInfo = symbolInfo[symbol];
1019
+ const buyOrdersQty = account.getQtyFromOrdersBySide(
1020
+ orders,
1021
+ symbol,
1022
+ OrderSide.BUY
1023
+ );
1024
+ const sellOrdersQty = account.getQtyFromOrdersBySide(
1025
+ orders,
1026
+ symbol,
1027
+ OrderSide.SELL
1028
+ );
1029
+ const otherPositions = positions2.filter(
1030
+ (item) => item.symbol !== symbol
1031
+ );
1032
+ const otherOrders = orders.filter(
1033
+ (item) => item.symbol !== symbol
1034
+ );
1035
+ const otherIMs = account.otherIMs({
1036
+ orders: otherOrders,
1037
+ positions: otherPositions,
1038
+ symbolInfo,
1039
+ markPrices,
1040
+ IMR_Factors: accountInfo.imr_factor,
1041
+ maxLeverage: accountInfo.max_leverage
1042
+ });
1043
+ return account.maxQty(side, {
1044
+ markPrice: markPrices[symbol],
1045
+ symbol,
1046
+ baseMaxQty: getSymbolInfo("base_max"),
1047
+ totalCollateral,
1048
+ maxLeverage: accountInfo.max_leverage,
1049
+ takerFeeRate: accountInfo.taker_fee_rate,
1050
+ baseIMR: getSymbolInfo("base_imr"),
1051
+ otherIMs,
1052
+ positionQty,
1053
+ buyOrdersQty,
1054
+ sellOrdersQty,
1055
+ IMR_Factor: accountInfo.imr_factor[getSymbolInfo("base")]
1056
+ });
1057
+ }, [
1058
+ orders,
1059
+ positionsData,
1060
+ markPrices,
1061
+ accountInfo,
1062
+ symbolInfo,
1063
+ symbol,
1064
+ side,
1065
+ totalCollateral,
1066
+ reduceOnly
1067
+ ]);
1078
1068
  return maxQty;
1079
1069
  };
1080
1070
  var { maxPrice, minPrice } = order;
@@ -1362,6 +1352,11 @@ var useFetures = () => {
1362
1352
  error
1363
1353
  };
1364
1354
  };
1355
+
1356
+ // src/orderly/useAccountInfo.ts
1357
+ var useAccountInfo = () => {
1358
+ return usePrivateQuery("/client/info");
1359
+ };
1365
1360
  var useMarketsStream = () => {
1366
1361
  const ws = useWebSocketClient();
1367
1362
  const { data } = useQuery(`/public/futures`);
@@ -1429,6 +1424,86 @@ var useFundingRate = (symbol) => {
1429
1424
  countDown
1430
1425
  });
1431
1426
  };
1427
+ var fetcher3 = (url, init) => get(url, init);
1428
+ var usePrivateInfiniteQuery = (getKey, options) => {
1429
+ var _a;
1430
+ const account3 = useAccount();
1431
+ const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
1432
+ const result = useSWRInfinite(
1433
+ (pageIndex, previousPageData) => account3.state.status >= AccountStatusEnum.SignedIn ? getKey(pageIndex, previousPageData) : null,
1434
+ fetcher3,
1435
+ __spreadProps(__spreadValues({}, options), {
1436
+ use: [signatureMiddleware, ...middleware]
1437
+ })
1438
+ );
1439
+ return result;
1440
+ };
1441
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1442
+ OrderStatus2["FILLED"] = "FILLED";
1443
+ OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1444
+ OrderStatus2["CANCELED"] = "CANCELED";
1445
+ OrderStatus2["NEW"] = "NEW";
1446
+ OrderStatus2["COMPLETED"] = "COMPLETED";
1447
+ return OrderStatus2;
1448
+ })(OrderStatus || {});
1449
+ var useOrderStream = ({
1450
+ status = "NEW" /* NEW */,
1451
+ symbol
1452
+ } = {}) => {
1453
+ const { data: markPrices = {} } = useMarkPricesStream();
1454
+ const res = usePrivateInfiniteQuery(
1455
+ (pageIndex, previousPageData) => {
1456
+ const search = new URLSearchParams([
1457
+ ["size", "100"],
1458
+ ["page", `${pageIndex + 1}`],
1459
+ [`status`, status]
1460
+ ]);
1461
+ if (symbol) {
1462
+ search.set(`symbol`, symbol);
1463
+ }
1464
+ return `/orders?${search.toString()}`;
1465
+ },
1466
+ {
1467
+ initialSize: 1,
1468
+ onError: (err) => {
1469
+ console.error("fetch failed::::", err);
1470
+ }
1471
+ }
1472
+ );
1473
+ const orders = useMemo(() => {
1474
+ var _a;
1475
+ if (!res.data) {
1476
+ return null;
1477
+ }
1478
+ console.log("orders:::", markPrices);
1479
+ return (_a = res.data) == null ? void 0 : _a.flat().map((item) => {
1480
+ var _a2;
1481
+ return __spreadProps(__spreadValues({}, item), {
1482
+ mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
1483
+ });
1484
+ });
1485
+ }, [res.data, markPrices]);
1486
+ const cancelAllOrders = useCallback(() => {
1487
+ }, [res.data]);
1488
+ const updateOrder = useCallback((id, data) => {
1489
+ }, []);
1490
+ const cancelOrder = useCallback((id) => {
1491
+ }, []);
1492
+ return [
1493
+ orders,
1494
+ // {
1495
+ // ...res,
1496
+ // data: res.data?.reduce((acc, cur) => {
1497
+ // return [...acc, ...cur];
1498
+ // }, []),
1499
+ // },
1500
+ {
1501
+ cancelAllOrders,
1502
+ updateOrder,
1503
+ cancelOrder
1504
+ }
1505
+ ];
1506
+ };
1432
1507
 
1433
1508
  // src/apis/index.ts
1434
1509
  var apis_exports = {};
@@ -1464,6 +1539,6 @@ var useFundingRate2 = (symbol) => {
1464
1539
  return useQuery(`/public/funding_rate`);
1465
1540
  };
1466
1541
 
1467
- export { OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useCollateral, useFetures, useFundingRate, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbook, usePositionStream, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWebSocketClient };
1542
+ export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAppState, useCollateral, useFetures, useFundingRate, useMarkPricesStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbook, usePositionStream, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS, useWebSocketClient };
1468
1543
  //# sourceMappingURL=out.js.map
1469
1544
  //# sourceMappingURL=index.mjs.map