@orderly.network/hooks 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var useSWR = require('swr');
4
3
  var net = require('@orderly.network/net');
5
- var React = require('react');
4
+ var useSWR = require('swr');
6
5
  var types = require('@orderly.network/types');
6
+ var React = require('react');
7
7
  var useSWRMutation = require('swr/mutation');
8
8
  var useConstant = require('use-constant');
9
9
  var core = require('@orderly.network/core');
@@ -12,9 +12,9 @@ var lodash = require('lodash');
12
12
  var useSWRInfinite = require('swr/infinite');
13
13
  var amplitude = require('@amplitude/analytics-browser');
14
14
  var jsxRuntime = require('react/jsx-runtime');
15
- var ramda = require('ramda');
16
15
  var zustand = require('zustand');
17
16
  var immer = require('zustand/middleware/immer');
17
+ var ramda = require('ramda');
18
18
  var perp = require('@orderly.network/perp');
19
19
  var useSWRSubscription = require('swr/subscription');
20
20
  var useDebounce = require('use-debounce');
@@ -44,7 +44,7 @@ function _interopNamespace(e) {
44
44
  return Object.freeze(n);
45
45
  }
46
46
 
47
- var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);
47
+ var useSWR__namespace = /*#__PURE__*/_interopNamespace(useSWR);
48
48
  var React__default = /*#__PURE__*/_interopDefault(React);
49
49
  var useSWRMutation__default = /*#__PURE__*/_interopDefault(useSWRMutation);
50
50
  var useConstant__default = /*#__PURE__*/_interopDefault(useConstant);
@@ -61,9 +61,9 @@ var __export = (target, all) => {
61
61
  // src/version.ts
62
62
  if (typeof window !== "undefined") {
63
63
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
64
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.2.0";
64
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.3.0";
65
65
  }
66
- var version_default = "2.2.0";
66
+ var version_default = "2.3.0";
67
67
  var fetcher = (url, init2 = {}, queryOptions) => net.get(url, init2, queryOptions?.formatter);
68
68
  var OrderlyContext = React.createContext({
69
69
  // configStore: new MemoryConfigStore(),
@@ -84,13 +84,15 @@ function useConfig(key, defaultValue) {
84
84
  }
85
85
  return configStore;
86
86
  }
87
+
88
+ // src/useQuery.ts
87
89
  var useQuery = (query, options) => {
88
90
  const apiBaseUrl = useConfig("apiBaseUrl");
89
91
  const { formatter, ...swrOptions } = options || {};
90
92
  if (typeof apiBaseUrl === "undefined") {
91
93
  throw new types.SDKError("please add OrderlyConfigProvider to your app");
92
94
  }
93
- return useSWR__default.default(
95
+ return useSWR__namespace.default(
94
96
  query,
95
97
  (url, init2) => fetcher(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init2, {
96
98
  formatter
@@ -109,14 +111,10 @@ var useLazyQuery = (query, options) => {
109
111
  (url, options2) => {
110
112
  url = url.startsWith("http") ? url : `${apiBaseUrl}${url}`;
111
113
  if (options2?.arg) {
112
- const queryString = Object.entries(options2.arg).map(
113
- ([key, value]) => `${key}=${encodeURIComponent(value)}`
114
- ).join("&");
114
+ const queryString = Object.entries(options2.arg).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
115
115
  url = `${url}?${queryString}`;
116
116
  }
117
- return fetcher(url, init2, {
118
- formatter
119
- });
117
+ return fetcher(url, init2, { formatter });
120
118
  },
121
119
  swrOptions
122
120
  );
@@ -132,20 +130,20 @@ var useAccountInstance = () => {
132
130
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
133
131
  );
134
132
  }
135
- const account5 = useConstant__default.default(() => {
136
- let account6 = core.SimpleDI.get("account");
137
- if (!account6) {
138
- account6 = new core.Account(
133
+ const account7 = useConstant__default.default(() => {
134
+ let account8 = core.SimpleDI.get("account");
135
+ if (!account8) {
136
+ account8 = new core.Account(
139
137
  configStore,
140
138
  keyStore,
141
139
  // getWalletAdapter,
142
140
  walletAdapters
143
141
  );
144
- core.SimpleDI.registerByName("account", account6);
142
+ core.SimpleDI.registerByName("account", account8);
145
143
  }
146
- return account6;
144
+ return account8;
147
145
  });
148
- return account5;
146
+ return account7;
149
147
  };
150
148
  var fetcher2 = (url, options) => {
151
149
  const init2 = {
@@ -169,7 +167,7 @@ var useMutation = (url, method = "POST", options) => {
169
167
  if (!url.startsWith("http")) {
170
168
  fullUrl = `${apiBaseUrl}${url}`;
171
169
  }
172
- const account5 = useAccountInstance();
170
+ const account7 = useAccountInstance();
173
171
  const { trigger, data, error, reset, isMutating } = useSWRMutation__default.default(
174
172
  fullUrl,
175
173
  // method === "POST" ? fetcher : deleteFetcher,
@@ -187,7 +185,7 @@ var useMutation = (url, method = "POST", options) => {
187
185
  url: newUrl,
188
186
  data: data2
189
187
  };
190
- const signer = account5.signer;
188
+ const signer = account7.signer;
191
189
  const signature = await signer.sign(payload, utils.getTimestamp());
192
190
  return trigger(
193
191
  {
@@ -196,7 +194,7 @@ var useMutation = (url, method = "POST", options) => {
196
194
  method,
197
195
  signature: {
198
196
  ...signature,
199
- "orderly-account-id": account5.accountId
197
+ "orderly-account-id": account7.accountId
200
198
  }
201
199
  },
202
200
  options2
@@ -214,22 +212,22 @@ var useMutation = (url, method = "POST", options) => {
214
212
  };
215
213
  var signatureMiddleware = (useSWRNext) => {
216
214
  const apiBaseUrl = useConfig("apiBaseUrl");
217
- return (key, fetcher3, config) => {
215
+ return (key, fetcher4, config) => {
218
216
  try {
219
217
  const extendedFetcher = async (args) => {
220
- let url = Array.isArray(args) ? args[0] : args;
221
- let account5 = core.SimpleDI.get("account");
222
- let fullUrl = `${apiBaseUrl}${url}`;
223
- const signer = account5.signer;
218
+ const url = Array.isArray(args) ? args[0] : args;
219
+ const account7 = core.SimpleDI.get("account");
220
+ const fullUrl = `${apiBaseUrl}${url}`;
221
+ const signer = account7.signer;
224
222
  const payload = {
225
223
  method: "GET",
226
224
  url
227
225
  };
228
226
  const signature = await signer.sign(payload, utils.getTimestamp());
229
- return fetcher3(fullUrl, {
227
+ return fetcher4(fullUrl, {
230
228
  headers: {
231
229
  ...signature,
232
- "orderly-account-id": account5.accountId
230
+ "orderly-account-id": account7.accountId
233
231
  }
234
232
  });
235
233
  };
@@ -296,16 +294,47 @@ var useTrack = () => {
296
294
  setIdentify
297
295
  };
298
296
  };
297
+ var WS_NAME = "nativeWebsocketClient";
298
+ var useWS = () => {
299
+ const { configStore } = React.useContext(OrderlyContext);
300
+ const ws = useConstant__default.default(() => {
301
+ let websocketClient = core.SimpleDI.get(WS_NAME);
302
+ const account7 = core.SimpleDI.get(core.Account.instanceName);
303
+ if (!websocketClient) {
304
+ websocketClient = new net.WS({
305
+ networkId: configStore.get("networkId"),
306
+ publicUrl: configStore.get("publicWsUrl"),
307
+ privateUrl: configStore.get("privateWsUrl"),
308
+ onSigntureRequest: async (accountId) => {
309
+ const signer = account7.signer;
310
+ const timestamp = utils.getTimestamp();
311
+ const result = await signer.signText(timestamp.toString());
312
+ return { ...result, timestamp };
313
+ }
314
+ });
315
+ if ((account7.stateValue.status === types.AccountStatusEnum.EnableTrading || account7.stateValue.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
316
+ websocketClient.openPrivate(account7.accountId);
317
+ }
318
+ account7.on("change:status", (nextState) => {
319
+ if ((nextState.status === types.AccountStatusEnum.EnableTrading || nextState.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
320
+ websocketClient.openPrivate(account7.accountId);
321
+ } else {
322
+ websocketClient.closePrivate(1e3, "switch account");
323
+ }
324
+ });
325
+ if (typeof window !== "undefined") {
326
+ utils.getGlobalObject()["__Orderly_WS"] = websocketClient;
327
+ }
328
+ core.SimpleDI.registerByName(WS_NAME, websocketClient);
329
+ }
330
+ return websocketClient;
331
+ });
332
+ return ws;
333
+ };
299
334
 
300
335
  // src/useAccount.ts
301
336
  var useAccount = () => {
302
- const {
303
- configStore,
304
- keyStore
305
- // onWalletConnect,
306
- // onWalletDisconnect,
307
- // onSetChain,
308
- } = React.useContext(OrderlyContext);
337
+ const { configStore, keyStore } = React.useContext(OrderlyContext);
309
338
  if (!configStore)
310
339
  throw new types.SDKError(
311
340
  "configStore is not defined, please use OrderlyProvider"
@@ -315,49 +344,83 @@ var useAccount = () => {
315
344
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
316
345
  );
317
346
  }
318
- const account5 = useAccountInstance();
319
- const [state, setState] = React.useState(account5.stateValue);
347
+ const account7 = useAccountInstance();
348
+ const [state, setState] = React.useState(account7.stateValue);
320
349
  const { track: track2 } = useTrack();
321
350
  const statusChangeHandler = (nextState) => {
322
351
  setState(() => nextState);
323
352
  };
324
353
  React.useEffect(() => {
325
- account5.on("change:status", statusChangeHandler);
354
+ account7.on("change:status", statusChangeHandler);
326
355
  return () => {
327
- account5.off("change:status", statusChangeHandler);
356
+ account7.off("change:status", statusChangeHandler);
328
357
  };
329
- }, []);
358
+ }, [account7]);
330
359
  const createOrderlyKey = React.useCallback(
331
360
  async (remember) => {
332
361
  track2(types.TrackerEventName.signinSuccess, {
333
- network: account5.chainId,
362
+ network: account7.chainId,
334
363
  wallet: state.connectWallet?.name
335
364
  });
336
- return account5.createOrderlyKey(remember ? 365 : 30);
365
+ return account7.createOrderlyKey(remember ? 365 : 30).then((res) => {
366
+ return account7.restoreSubAccount().then((_) => {
367
+ return res;
368
+ });
369
+ });
370
+ },
371
+ [account7, state]
372
+ );
373
+ const ws = useWS();
374
+ const switchAccount = React.useCallback(
375
+ async (accountId) => {
376
+ ws.closePrivate(1e3, "switch account");
377
+ return account7.switchAccount(accountId);
337
378
  },
338
- [account5, state]
379
+ [account7]
339
380
  );
340
381
  const createAccount = React.useCallback(async () => {
341
- return account5.createAccount();
342
- }, [account5]);
382
+ return account7.createAccount();
383
+ }, [account7]);
384
+ const createSubAccount = React.useCallback(
385
+ async (description) => {
386
+ return account7.createSubAccount(description);
387
+ },
388
+ [account7]
389
+ );
390
+ const updateSubAccount = React.useCallback(
391
+ async (value) => {
392
+ return account7.updateSubAccount(value);
393
+ },
394
+ [account7]
395
+ );
396
+ const refreshSubAccountBalances = React.useCallback(() => {
397
+ return account7.refreshSubAccountBalances();
398
+ }, [account7]);
399
+ const isSubAccount = React.useMemo(() => {
400
+ return state.accountId !== state.mainAccountId;
401
+ }, [state]);
343
402
  return {
344
- account: account5,
403
+ account: account7,
345
404
  state,
346
- // info: {},
347
- // login,
405
+ isSubAccount,
406
+ isMainAccount: !isSubAccount,
407
+ subAccount: {
408
+ refresh: refreshSubAccountBalances,
409
+ create: createSubAccount,
410
+ update: updateSubAccount
411
+ },
412
+ switchAccount,
348
413
  createOrderlyKey,
349
414
  createAccount
350
- // disconnect,
351
- // connect,
352
- // setChain,
353
- // settlement,
354
415
  };
355
416
  };
417
+
418
+ // src/usePrivateQuery.ts
356
419
  var usePrivateQuery = (query, options) => {
357
420
  const { formatter, ...swrOptions } = options || {};
358
421
  const { state } = useAccount();
359
422
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
360
- return useSWR__default.default(
423
+ return useSWR__namespace.default(
361
424
  () => state.status >= types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected ? [query, state.accountId] : null,
362
425
  (url, init2) => {
363
426
  return fetcher(url, init2, { formatter });
@@ -365,7 +428,7 @@ var usePrivateQuery = (query, options) => {
365
428
  {
366
429
  ...swrOptions,
367
430
  use: [signatureMiddleware, ...middleware],
368
- onError: (err) => {
431
+ onError: () => {
369
432
  }
370
433
  }
371
434
  );
@@ -376,6 +439,8 @@ var usePrivateInfiniteQuery = (getKey, options) => {
376
439
  const middleware = Array.isArray(restOptions?.use) ? restOptions?.use ?? [] : [];
377
440
  const result = useSWRInfinite__default.default(
378
441
  (pageIndex, previousPageData) => {
442
+ if (!getKey)
443
+ return null;
379
444
  const queryKey = getKey(pageIndex, previousPageData);
380
445
  if (queryKey && (state.status >= types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected)) {
381
446
  return [queryKey, state.accountId];
@@ -423,7 +488,7 @@ var usePreLoadData = () => {
423
488
  }
424
489
  );
425
490
  const apiBaseUrl = useConfig("apiBaseUrl");
426
- const { data: systemInfo } = useSWR__default.default(
491
+ const { data: systemInfo } = useSWR__namespace.default(
427
492
  "/v1/public/system_info",
428
493
  async (url, init2) => {
429
494
  const data = await fetch(
@@ -514,14 +579,16 @@ function useSessionStorage(key, initialValue) {
514
579
  );
515
580
  return [storedValue, setValue];
516
581
  }
517
- function useLocalStorage(key, initialValue) {
582
+ function useLocalStorage(key, initialValue, options = {
583
+ parseJSON
584
+ }) {
518
585
  const readValue = React.useCallback(() => {
519
586
  if (typeof window === "undefined") {
520
587
  return initialValue;
521
588
  }
522
589
  try {
523
590
  const item = window.localStorage.getItem(key);
524
- return item ? parseJSON(item) : initialValue;
591
+ return item ? options.parseJSON(item) : initialValue;
525
592
  } catch (error) {
526
593
  return initialValue;
527
594
  }
@@ -650,43 +717,6 @@ var useTrackingInstance = () => {
650
717
  });
651
718
  return trackInstace;
652
719
  };
653
- var WS_NAME = "nativeWebsocketClient";
654
- var useWS = () => {
655
- const { configStore } = React.useContext(OrderlyContext);
656
- const ws = useConstant__default.default(() => {
657
- let websocketClient = core.SimpleDI.get(WS_NAME);
658
- const account5 = core.SimpleDI.get(core.Account.instanceName);
659
- if (!websocketClient) {
660
- websocketClient = new net.WS({
661
- networkId: configStore.get("networkId"),
662
- publicUrl: configStore.get("publicWsUrl"),
663
- privateUrl: configStore.get("privateWsUrl"),
664
- onSigntureRequest: async (accountId) => {
665
- const signer = account5.signer;
666
- const timestamp = utils.getTimestamp();
667
- const result = await signer.signText(timestamp.toString());
668
- return { ...result, timestamp };
669
- }
670
- });
671
- if ((account5.stateValue.status === types.AccountStatusEnum.EnableTrading || account5.stateValue.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account5.stateValue.accountId) {
672
- websocketClient.openPrivate(account5.stateValue.accountId);
673
- }
674
- account5.on("change:status", (nextState) => {
675
- if ((nextState.status === types.AccountStatusEnum.EnableTrading || nextState.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && nextState.accountId) {
676
- websocketClient.openPrivate(nextState.accountId);
677
- } else {
678
- websocketClient.closePrivate(1e3, "switch account");
679
- }
680
- });
681
- if (typeof window !== "undefined") {
682
- utils.getGlobalObject()["__Orderly_WS"] = websocketClient;
683
- }
684
- core.SimpleDI.registerByName(WS_NAME, websocketClient);
685
- }
686
- return websocketClient;
687
- });
688
- return ws;
689
- };
690
720
  var useKeyStore = () => {
691
721
  const ctx = React.useContext(OrderlyContext);
692
722
  return ctx.keyStore;
@@ -742,6 +772,73 @@ var StatusProvider = (props) => {
742
772
  const wsStatus = useWsStatus();
743
773
  return /* @__PURE__ */ jsxRuntime.jsx(StatusContext.Provider, { value: { ws: wsStatus }, children: props.children });
744
774
  };
775
+ var useWSObserver = (calculatorService) => {
776
+ const ws = useWS();
777
+ React.useEffect(() => {
778
+ const markPriceSubscription = ws.subscribe("markprices", {
779
+ onMessage: (message) => {
780
+ const data = /* @__PURE__ */ Object.create(null);
781
+ for (let index = 0; index < message.length; index++) {
782
+ const element = message[index];
783
+ data[element.symbol] = element.price;
784
+ }
785
+ calculatorService.calc("markPrice" /* MARK_PRICE */, data, {
786
+ skipWhenOnPause: true
787
+ });
788
+ },
789
+ onError: (error) => {
790
+ }
791
+ });
792
+ const indexPriceSubscription = ws.subscribe("indexprices", {
793
+ onMessage: (message) => {
794
+ if (!Array.isArray(message))
795
+ return;
796
+ const prices = /* @__PURE__ */ Object.create(null);
797
+ for (let index = 0; index < message.length; index++) {
798
+ const element = message[index];
799
+ prices[element.symbol.replace("SPOT", "PERP")] = element.price;
800
+ }
801
+ calculatorService.calc("indexPrice" /* INDEX_PRICE */, prices, {
802
+ skipWhenOnPause: true
803
+ });
804
+ }
805
+ });
806
+ return () => {
807
+ markPriceSubscription?.();
808
+ indexPriceSubscription?.();
809
+ };
810
+ }, []);
811
+ };
812
+ var useApiStatusStore = zustand.create()(
813
+ immer.immer((set) => ({
814
+ apis: {
815
+ positions: {
816
+ loading: false
817
+ }
818
+ },
819
+ actions: {
820
+ updateStatus: (key, status) => {
821
+ set((state) => {
822
+ state.apis[key] = status;
823
+ });
824
+ },
825
+ updateApiLoading: (key, loading) => {
826
+ set((state) => {
827
+ state.apis[key].loading = loading;
828
+ });
829
+ },
830
+ updateApiError: (key, error) => {
831
+ set((state) => {
832
+ state.apis[key] = {
833
+ loading: false,
834
+ error
835
+ };
836
+ });
837
+ }
838
+ }
839
+ }))
840
+ );
841
+ var useApiStatusActions = () => useApiStatusStore((state) => state.actions);
745
842
  var BaseMergeHandler = class {
746
843
  constructor(message) {
747
844
  this.message = message;
@@ -965,72 +1062,6 @@ var AlgoOrderMergeHandler = class _AlgoOrderMergeHandler extends BaseMergeHandle
965
1062
  return rootOrder;
966
1063
  }
967
1064
  };
968
-
969
- // src/services/orderMerge/regularOrderMergeHandler.ts
970
- var RegularOrderMergeHandler = class extends BaseMergeHandler {
971
- get orderId() {
972
- return this.data.order_id;
973
- }
974
- get status() {
975
- return this.data.status;
976
- }
977
- pre(message, prevData) {
978
- return object2underscore(message);
979
- }
980
- isFullFilled() {
981
- return "total_executed_quantity" in this.data && this.data.total_executed_quantity === this.data.quantity;
982
- }
983
- };
984
-
985
- // src/utils/swr.ts
986
- var generateKeyFun = (args) => (pageIndex, previousPageData) => {
987
- if (previousPageData && !previousPageData.rows?.length)
988
- return null;
989
- const { status, symbol, side, size = 100, page, dateRange } = args;
990
- const search = new URLSearchParams([
991
- ["size", size.toString()],
992
- ["page", `${pageIndex + 1}`],
993
- ["source_type", "ALL"]
994
- ]);
995
- if (dateRange) {
996
- if (dateRange.from) {
997
- search.set("start_t", `${dateRange.from.getTime()}`);
998
- }
999
- if (dateRange.to) {
1000
- search.set("end_t", `${dateRange.to.getTime()}`);
1001
- }
1002
- }
1003
- if (page) {
1004
- search.set("page", `${page}`);
1005
- }
1006
- if (status) {
1007
- search.set(`status`, status);
1008
- }
1009
- if (symbol) {
1010
- search.set(`symbol`, symbol);
1011
- }
1012
- if (side) {
1013
- search.set(`side`, side);
1014
- }
1015
- return `/v1/orders?${search.toString()}`;
1016
- };
1017
- var updateOrdersHandler = (key, updatedOrder, orders) => {
1018
- if (!orders) {
1019
- return;
1020
- }
1021
- const handler = new RegularOrderMergeHandler(updatedOrder);
1022
- return handler.merge(key, updatedOrder, orders);
1023
- };
1024
- function updateAlgoOrdersHandler(key, message, orders) {
1025
- if (!orders) {
1026
- return;
1027
- }
1028
- const mergeHandler = new AlgoOrderMergeHandler(message);
1029
- const result = mergeHandler.merge(key, message, orders);
1030
- return result;
1031
- }
1032
- function getPositionBySymbol(symbol) {
1033
- }
1034
1065
  var useAppStore = zustand.create()(
1035
1066
  immer.immer((set) => ({
1036
1067
  // accountInfo: null,
@@ -1450,9 +1481,9 @@ var usePositionStore = zustand.create()(
1450
1481
  all: POSITION_EMPTY
1451
1482
  },
1452
1483
  actions: {
1453
- setPositions: (key, positions2) => {
1484
+ setPositions: (key, positions3) => {
1454
1485
  set((state) => {
1455
- state.positions[key] = positions2;
1486
+ state.positions[key] = positions3;
1456
1487
  });
1457
1488
  },
1458
1489
  closePosition: (symbol) => {
@@ -1472,36 +1503,6 @@ var usePositionStore = zustand.create()(
1472
1503
  );
1473
1504
  var usePositions = (symbol = "all") => usePositionStore((state) => (state.positions[symbol] ?? POSITION_EMPTY).rows);
1474
1505
  var usePositionActions = () => usePositionStore((state) => state.actions);
1475
- var useApiStatusStore = zustand.create()(
1476
- immer.immer((set) => ({
1477
- apis: {
1478
- positions: {
1479
- loading: false
1480
- }
1481
- },
1482
- actions: {
1483
- updateStatus: (key, status) => {
1484
- set((state) => {
1485
- state.apis[key] = status;
1486
- });
1487
- },
1488
- updateApiLoading: (key, loading) => {
1489
- set((state) => {
1490
- state.apis[key].loading = loading;
1491
- });
1492
- },
1493
- updateApiError: (key, error) => {
1494
- set((state) => {
1495
- state.apis[key] = {
1496
- loading: false,
1497
- error
1498
- };
1499
- });
1500
- }
1501
- }
1502
- }))
1503
- );
1504
- var useApiStatusActions = () => useApiStatusStore((state) => state.actions);
1505
1506
 
1506
1507
  // src/orderly/calculator/positions.ts
1507
1508
  var NAME_PREFIX = "positionCalculator";
@@ -1537,38 +1538,41 @@ var PositionCalculator = class extends BaseCalculator {
1537
1538
  }
1538
1539
  }
1539
1540
  calcByMarkPrice(markPrice, ctx) {
1540
- let positions2 = this.getPosition(markPrice, ctx);
1541
- if (!positions2 || !Array.isArray(positions2.rows) || !positions2.rows.length)
1542
- return positions2;
1543
- positions2 = {
1544
- ...positions2,
1545
- rows: positions2.rows.map((item) => ({
1546
- ...item,
1547
- mark_price: markPrice[item.symbol] || item.mark_price
1548
- }))
1541
+ let positions3 = this.getPosition(markPrice, ctx);
1542
+ useAppStore.getState().fundingRates;
1543
+ if (!positions3 || !Array.isArray(positions3.rows) || !positions3.rows.length)
1544
+ return positions3;
1545
+ positions3 = {
1546
+ ...positions3,
1547
+ rows: positions3.rows.map((item) => {
1548
+ return {
1549
+ ...item,
1550
+ mark_price: markPrice[item.symbol] || item.mark_price
1551
+ };
1552
+ })
1549
1553
  };
1550
- return this.format(positions2, ctx);
1554
+ return this.format(positions3, ctx);
1551
1555
  }
1552
1556
  calcByIndexPrice(indexPrice, ctx) {
1553
- let positions2 = this.getPosition(indexPrice, ctx);
1554
- if (!positions2) {
1555
- return positions2;
1556
- }
1557
- if (!Array.isArray(positions2.rows) || !positions2.rows.length)
1558
- return positions2;
1559
- positions2 = {
1560
- ...positions2,
1561
- rows: positions2.rows.map((item) => ({
1557
+ let positions3 = this.getPosition(indexPrice, ctx);
1558
+ if (!positions3) {
1559
+ return positions3;
1560
+ }
1561
+ if (!Array.isArray(positions3.rows) || !positions3.rows.length)
1562
+ return positions3;
1563
+ positions3 = {
1564
+ ...positions3,
1565
+ rows: positions3.rows.map((item) => ({
1562
1566
  ...item,
1563
1567
  index_price: indexPrice[item.symbol] || item.index_price || item.mark_price
1564
1568
  }))
1565
1569
  };
1566
- return this.format(positions2, ctx);
1570
+ return this.format(positions3, ctx);
1567
1571
  }
1568
- calcByPosition(positions2, ctx) {
1569
- if (positions2.rows.length === 0)
1570
- return positions2;
1571
- return this.format(positions2, ctx);
1572
+ calcByPosition(positions3, ctx) {
1573
+ if (positions3.rows.length === 0)
1574
+ return positions3;
1575
+ return this.format(positions3, ctx);
1572
1576
  }
1573
1577
  format(data, ctx) {
1574
1578
  const { accountInfo, symbolsInfo, fundingRates, portfolio } = ctx;
@@ -1578,6 +1582,7 @@ var PositionCalculator = class extends BaseCalculator {
1578
1582
  let unrealPnL_total = utils.zero, unrealPnL_total_index = utils.zero, notional_total = utils.zero, unsettlementPnL_total = utils.zero;
1579
1583
  let rows = data.rows.map((item) => {
1580
1584
  const info = symbolsInfo[item.symbol];
1585
+ const sum_unitary_funding = fundingRates?.[item.symbol]?.["sum_unitary_funding"] ?? 0;
1581
1586
  const notional = perp.positions.notional(item.position_qty, item.mark_price);
1582
1587
  const unrealPnl = perp.positions.unrealizedPnL({
1583
1588
  qty: item.position_qty,
@@ -1636,8 +1641,10 @@ var PositionCalculator = class extends BaseCalculator {
1636
1641
  unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
1637
1642
  notional_total = notional_total.add(notional);
1638
1643
  unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL2);
1644
+ const fundingFee = new utils.Decimal(sum_unitary_funding).sub(item.last_sum_unitary_funding).mul(item.position_qty).negated().toNumber();
1639
1645
  return {
1640
1646
  ...item,
1647
+ fundingFee,
1641
1648
  mm: perp.positions.maintenanceMargin({
1642
1649
  positionQty: item.position_qty,
1643
1650
  markPrice: item.mark_price,
@@ -1706,12 +1713,12 @@ var PositionCalculator = class extends BaseCalculator {
1706
1713
  };
1707
1714
  }
1708
1715
  getPosition(_, ctx) {
1709
- let positions2 = ctx.get((output) => output[this.name]) || usePositionStore.getState().positions[this.symbol];
1716
+ const positions3 = ctx.get((output) => output[this.name]) || usePositionStore.getState().positions[this.symbol];
1710
1717
  if (this.symbol === AllPositions) {
1711
- return positions2;
1718
+ return positions3;
1712
1719
  }
1713
- if (positions2 && Array.isArray(positions2.rows)) {
1714
- return positions2;
1720
+ if (positions3 && Array.isArray(positions3.rows)) {
1721
+ return positions3;
1715
1722
  }
1716
1723
  return this.preprocess(this.getAllPositions(ctx));
1717
1724
  }
@@ -1726,25 +1733,6 @@ var PositionCalculator = class extends BaseCalculator {
1726
1733
  PositionCalculator.logPosition = (symbol = "all") => {
1727
1734
  return usePositionStore.getState().positions[symbol];
1728
1735
  };
1729
-
1730
- // src/utils/parseHolding.ts
1731
- var parseHolding = (holding, markPrices) => {
1732
- const nonUSDC = [];
1733
- let USDC_holding = 0;
1734
- holding.forEach((item) => {
1735
- if (item.token === "USDC") {
1736
- USDC_holding = item.holding;
1737
- } else {
1738
- nonUSDC.push({
1739
- holding: item.holding,
1740
- markPrice: markPrices[item.token] ?? 0,
1741
- // markPrice: 0,
1742
- discount: 0
1743
- });
1744
- }
1745
- });
1746
- return [USDC_holding, nonUSDC];
1747
- };
1748
1736
  function createGetter(data, depth = 2) {
1749
1737
  const getValue = (value, defaultValue) => {
1750
1738
  if (defaultValue === void 0) {
@@ -1775,6 +1763,25 @@ function createGetter(data, depth = 2) {
1775
1763
  });
1776
1764
  }
1777
1765
 
1766
+ // src/utils/parseHolding.ts
1767
+ var parseHolding = (holding, markPrices) => {
1768
+ const nonUSDC = [];
1769
+ let USDC_holding = 0;
1770
+ holding.forEach((item) => {
1771
+ if (item.token === "USDC") {
1772
+ USDC_holding = item.holding;
1773
+ } else {
1774
+ nonUSDC.push({
1775
+ holding: item.holding,
1776
+ markPrice: markPrices[item.token] ?? 0,
1777
+ // markPrice: 0,
1778
+ discount: 0
1779
+ });
1780
+ }
1781
+ });
1782
+ return [USDC_holding, nonUSDC];
1783
+ };
1784
+
1778
1785
  // src/orderly/calculator/portfolio.ts
1779
1786
  var PortfolioCalculatorName = "portfolio";
1780
1787
  var PortfolioCalculator = class extends BaseCalculator {
@@ -1783,7 +1790,7 @@ var PortfolioCalculator = class extends BaseCalculator {
1783
1790
  this.name = PortfolioCalculatorName;
1784
1791
  }
1785
1792
  calc(scope, data, ctx) {
1786
- let markPrices, positions2;
1793
+ let markPrices, positions3;
1787
1794
  const portfolio = this.getPortfolio(ctx);
1788
1795
  if (scope === "markPrice" /* MARK_PRICE */) {
1789
1796
  markPrices = data;
@@ -1792,27 +1799,31 @@ var PortfolioCalculator = class extends BaseCalculator {
1792
1799
  (cache) => cache[MarketCalculatorName]
1793
1800
  );
1794
1801
  }
1795
- positions2 = ctx.get(
1802
+ positions3 = ctx.get(
1796
1803
  (output) => output.positionCalculator_all
1797
1804
  );
1798
1805
  let holding = portfolio.holding;
1799
1806
  if (scope === "portfolio" /* PORTFOLIO */ && data.holding && Array.isArray(holding)) {
1800
- holding = holding.map((item) => {
1801
- if (data.holding[item.token]) {
1802
- return {
1803
- ...item,
1804
- holding: data.holding[item.token].holding,
1805
- frozen: data.holding[item.token].frozen
1806
- };
1807
- }
1808
- return item;
1809
- });
1807
+ if (Array.isArray(data.holding)) {
1808
+ holding = data.holding;
1809
+ } else {
1810
+ holding = holding.map((item) => {
1811
+ if (data.holding[item.token]) {
1812
+ return {
1813
+ ...item,
1814
+ holding: data.holding[item.token].holding,
1815
+ frozen: data.holding[item.token].frozen
1816
+ };
1817
+ }
1818
+ return item;
1819
+ });
1820
+ }
1810
1821
  }
1811
1822
  const accountInfo = ctx.accountInfo;
1812
1823
  const symbolsInfo = ctx.symbolsInfo;
1813
1824
  return this.format({
1814
1825
  holding,
1815
- positions: positions2,
1826
+ positions: positions3,
1816
1827
  markPrices,
1817
1828
  accountInfo,
1818
1829
  symbolsInfo
@@ -1822,12 +1833,12 @@ var PortfolioCalculator = class extends BaseCalculator {
1822
1833
  return ctx.get((output) => output[this.name]) || useAppStore.getState().portfolio;
1823
1834
  }
1824
1835
  format(inputs) {
1825
- const { holding, positions: positions2, markPrices, accountInfo, symbolsInfo } = inputs;
1826
- if (!holding || !positions2 || !Array.isArray(positions2.rows) || !markPrices || !accountInfo) {
1836
+ const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
1837
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo) {
1827
1838
  return null;
1828
1839
  }
1829
- const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions2);
1830
- const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions2);
1840
+ const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
1841
+ const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
1831
1842
  const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1832
1843
  const usdc = holding.find((item) => item.token === "USDC");
1833
1844
  const totalCollateral = perp.account.totalCollateral({
@@ -1845,7 +1856,7 @@ var PortfolioCalculator = class extends BaseCalculator {
1845
1856
  totalValue: totalValue.toNumber()
1846
1857
  });
1847
1858
  const totalInitialMarginWithOrders = perp.account.totalInitialMarginWithQty({
1848
- positions: positions2.rows,
1859
+ positions: positions3.rows,
1849
1860
  markPrices,
1850
1861
  IMR_Factors: accountInfo.imr_factor,
1851
1862
  maxLeverage: accountInfo.max_leverage,
@@ -1857,7 +1868,7 @@ var PortfolioCalculator = class extends BaseCalculator {
1857
1868
  });
1858
1869
  const availableBalance = perp.account.availableBalance({
1859
1870
  USDCHolding: usdc?.holding ?? 0,
1860
- unsettlementPnL: positions2.total_unsettled_pnl ?? 0
1871
+ unsettlementPnL: positions3.total_unsettled_pnl ?? 0
1861
1872
  });
1862
1873
  return {
1863
1874
  totalCollateral,
@@ -1949,6 +1960,75 @@ var useCalculatorService = () => {
1949
1960
  return calculatorService;
1950
1961
  };
1951
1962
 
1963
+ // src/services/orderMerge/regularOrderMergeHandler.ts
1964
+ var RegularOrderMergeHandler = class extends BaseMergeHandler {
1965
+ get orderId() {
1966
+ return this.data.order_id;
1967
+ }
1968
+ get status() {
1969
+ return this.data.status;
1970
+ }
1971
+ pre(message, prevData) {
1972
+ return object2underscore(message);
1973
+ }
1974
+ isFullFilled() {
1975
+ return "total_executed_quantity" in this.data && this.data.total_executed_quantity === this.data.quantity;
1976
+ }
1977
+ };
1978
+
1979
+ // src/utils/swr.ts
1980
+ var generateKeyFun = (url, args) => (pageIndex, previousPageData) => {
1981
+ if (previousPageData && !previousPageData.rows?.length)
1982
+ return null;
1983
+ const { status, symbol, side, size = 100, page, dateRange } = args;
1984
+ const search = new URLSearchParams([
1985
+ ["size", size.toString()],
1986
+ ["page", `${pageIndex + 1}`]
1987
+ // ["source_type", "ALL"],
1988
+ ]);
1989
+ if (args.sourceTypeAll) {
1990
+ search.set("source_type", "ALL");
1991
+ }
1992
+ if (dateRange) {
1993
+ if (dateRange.from) {
1994
+ search.set("start_t", `${dateRange.from.getTime()}`);
1995
+ }
1996
+ if (dateRange.to) {
1997
+ search.set("end_t", `${dateRange.to.getTime()}`);
1998
+ }
1999
+ }
2000
+ if (page) {
2001
+ search.set("page", `${page}`);
2002
+ }
2003
+ if (status) {
2004
+ search.set(`status`, status);
2005
+ }
2006
+ if (symbol) {
2007
+ search.set(`symbol`, symbol);
2008
+ }
2009
+ if (side) {
2010
+ search.set(`side`, side);
2011
+ }
2012
+ return `${url}?${search.toString()}`;
2013
+ };
2014
+ var updateOrdersHandler = (key, updatedOrder, orders) => {
2015
+ if (!orders) {
2016
+ return;
2017
+ }
2018
+ const handler = new RegularOrderMergeHandler(updatedOrder);
2019
+ return handler.merge(key, updatedOrder, orders);
2020
+ };
2021
+ function updateAlgoOrdersHandler(key, message, orders) {
2022
+ if (!orders) {
2023
+ return;
2024
+ }
2025
+ const mergeHandler = new AlgoOrderMergeHandler(message);
2026
+ const result = mergeHandler.merge(key, message, orders);
2027
+ return result;
2028
+ }
2029
+ function getPositionBySymbol(symbol) {
2030
+ }
2031
+
1952
2032
  // src/orderly/orderbook.service.ts
1953
2033
  var defaultRawOrderBook = {
1954
2034
  asks: [],
@@ -2071,10 +2151,10 @@ var useMarkPrice = (symbol) => {
2071
2151
  };
2072
2152
  var useSymbolsInfo = () => {
2073
2153
  const symbolsInfo = useAppStore((state) => state.symbolsInfo);
2074
- return React.useMemo(
2075
- () => createGetter({ ...symbolsInfo }),
2076
- [symbolsInfo]
2077
- );
2154
+ return React.useMemo(() => createGetter({ ...symbolsInfo }), [symbolsInfo]);
2155
+ };
2156
+ var useSymbolsInfoStore = () => {
2157
+ return useAppStore((state) => state.symbolsInfo);
2078
2158
  };
2079
2159
  var useIndexPrice = (symbol) => {
2080
2160
  symbol = symbol.replace("PERP", "SPOT");
@@ -2430,41 +2510,8 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2430
2510
  bids: [...data.bids]
2431
2511
  });
2432
2512
  React.useEffect(() => {
2433
- const updateData = [
2434
- [
2435
- reducedData.asks?.[reducedData.asks.length - 1]?.[0],
2436
- reducedData.bids?.[0]?.[0]
2437
- ],
2438
- [
2439
- reducedData.asks?.[reducedData.asks.length - 2]?.[0],
2440
- reducedData.bids?.[1]?.[0]
2441
- ],
2442
- [
2443
- reducedData.asks?.[reducedData.asks.length - 3]?.[0],
2444
- reducedData.bids?.[2]?.[0]
2445
- ],
2446
- [
2447
- reducedData.asks?.[reducedData.asks.length - 4]?.[0],
2448
- reducedData.bids?.[3]?.[0]
2449
- ],
2450
- [
2451
- reducedData.asks?.[reducedData.asks.length - 5]?.[0],
2452
- reducedData.bids?.[4]?.[0]
2453
- ]
2454
- ];
2455
- eventEmitter.emit("orderbook:update", updateData);
2456
- }, [
2457
- reducedData.asks?.[reducedData.asks.length - 1]?.[0],
2458
- reducedData.asks?.[reducedData.asks.length - 2]?.[0],
2459
- reducedData.asks?.[reducedData.asks.length - 3]?.[0],
2460
- reducedData.asks?.[reducedData.asks.length - 4]?.[0],
2461
- reducedData.asks?.[reducedData.asks.length - 5]?.[0],
2462
- reducedData.bids?.[0]?.[0],
2463
- reducedData.bids?.[1]?.[0],
2464
- reducedData.bids?.[2]?.[0],
2465
- reducedData.bids?.[3]?.[0],
2466
- reducedData.bids?.[4]?.[0]
2467
- ]);
2513
+ eventEmitter.emit("orderbook:update", reducedData);
2514
+ }, [reducedData]);
2468
2515
  const middlePrice = React.useMemo(() => {
2469
2516
  let asksFrist = 0, bidsFirst = 0;
2470
2517
  if (data.asks.length > 0) {
@@ -2493,7 +2540,9 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2493
2540
 
2494
2541
  // src/orderly/useAccountInfo.ts
2495
2542
  var useAccountInfo2 = () => {
2496
- return usePrivateQuery("/v1/client/info");
2543
+ return usePrivateQuery("/v1/client/info", {
2544
+ revalidateOnFocus: false
2545
+ });
2497
2546
  };
2498
2547
  var useMarketsStream = () => {
2499
2548
  const ws = useWS();
@@ -2558,6 +2607,10 @@ var useFundingRates = () => {
2558
2607
  const data = useAppStore((state) => state.fundingRates);
2559
2608
  return createGetter({ ...data });
2560
2609
  };
2610
+ var useFundingRatesStore = () => {
2611
+ const data = useAppStore((state) => state.fundingRates);
2612
+ return data;
2613
+ };
2561
2614
  var DefaultTab = { name: "Popular", id: 1 };
2562
2615
  var marketsKey = "markets";
2563
2616
  var useMarket = (type) => {
@@ -3144,6 +3197,12 @@ var useMarkPricesStream = () => {
3144
3197
  const data = useMarkPriceStore((state) => state.markPrices);
3145
3198
  return { data };
3146
3199
  };
3200
+
3201
+ // src/orderly/useIndexPricesStream.ts
3202
+ var useIndexPricesStream = () => {
3203
+ const data = useIndexPriceStore((state) => state.indexPrices);
3204
+ return { data };
3205
+ };
3147
3206
  var generateLeverageLevers = (max3) => {
3148
3207
  const min3 = 1;
3149
3208
  const parts = 5;
@@ -3155,8 +3214,11 @@ var generateLeverageLevers = (max3) => {
3155
3214
  return result;
3156
3215
  };
3157
3216
  var useLeverage = () => {
3158
- const { data, mutate: mutate3 } = usePrivateQuery(
3159
- "/v1/client/info"
3217
+ const { data, mutate: mutate5 } = usePrivateQuery(
3218
+ "/v1/client/info",
3219
+ {
3220
+ revalidateOnFocus: false
3221
+ }
3160
3222
  );
3161
3223
  const [update, { isMutating }] = useMutation("/v1/client/leverage");
3162
3224
  const { data: leverageConfig, isLoading } = useQuery("/v1/public/leverage", {
@@ -3168,12 +3230,12 @@ var useLeverage = () => {
3168
3230
  async (data2) => {
3169
3231
  const res = await update(data2);
3170
3232
  if (res.success) {
3171
- return mutate3();
3233
+ return mutate5();
3172
3234
  } else {
3173
3235
  throw new Error(res.message);
3174
3236
  }
3175
3237
  },
3176
- [update, mutate3]
3238
+ [update, mutate5]
3177
3239
  );
3178
3240
  const memoizedCurLeverage = React.useMemo(() => {
3179
3241
  if (data?.max_leverage !== void 0) {
@@ -3324,6 +3386,11 @@ var findPositionTPSLFromOrders = (orders, symbol) => {
3324
3386
  };
3325
3387
 
3326
3388
  // src/orderly/usePositionStream/usePositionStream.ts
3389
+ var scopes = [
3390
+ "position" /* POSITION */,
3391
+ "markPrice" /* MARK_PRICE */,
3392
+ "indexPrice" /* INDEX_PRICE */
3393
+ ];
3327
3394
  var usePositionStream = (symbol = "all", options) => {
3328
3395
  const { calcMode } = options || {};
3329
3396
  const { includedPendingOrder = false } = options || {};
@@ -3344,49 +3411,34 @@ var usePositionStream = (symbol = "all", options) => {
3344
3411
  (state) => state.apis
3345
3412
  );
3346
3413
  React.useEffect(() => {
3347
- if (symbol === "all")
3414
+ if (symbol === "all") {
3348
3415
  return;
3416
+ }
3349
3417
  positionCalculator.current = new PositionCalculator(symbol);
3350
- calculatorService.register(
3351
- "position" /* POSITION */,
3352
- positionCalculator.current
3353
- );
3354
- calculatorService.register(
3355
- "markPrice" /* MARK_PRICE */,
3356
- positionCalculator.current
3357
- );
3358
- calculatorService.register(
3359
- "indexPrice" /* INDEX_PRICE */,
3360
- positionCalculator.current
3361
- );
3418
+ for (const scope of scopes) {
3419
+ calculatorService.register(scope, positionCalculator.current);
3420
+ }
3362
3421
  return () => {
3363
- calculatorService.unregister(
3364
- "position" /* POSITION */,
3365
- positionCalculator.current
3366
- );
3367
- calculatorService.unregister(
3368
- "markPrice" /* MARK_PRICE */,
3369
- positionCalculator.current
3370
- );
3371
- calculatorService.unregister(
3372
- "indexPrice" /* INDEX_PRICE */,
3373
- positionCalculator.current
3374
- );
3422
+ for (const scope of scopes) {
3423
+ calculatorService.unregister(scope, positionCalculator.current);
3424
+ }
3375
3425
  };
3376
3426
  }, [symbol]);
3377
3427
  const formattedPositions = usePositionStore((state) => {
3378
- const positions2 = state.positions[symbol] ?? POSITION_EMPTY;
3379
- return [positions2.rows, ramda.omit(["rows"], positions2)];
3428
+ const positions3 = state.positions[symbol] ?? POSITION_EMPTY;
3429
+ return [positions3.rows, ramda.omit(["rows"], positions3)];
3380
3430
  });
3381
3431
  const { totalCollateral, totalValue, totalUnrealizedROI } = useAppStore(
3382
3432
  (state) => state.portfolio
3383
3433
  );
3384
3434
  const aggregated = React.useMemo(() => {
3385
- let data = formattedPositions[1];
3386
- if (!data)
3435
+ const data = formattedPositions[1];
3436
+ if (!data) {
3387
3437
  return {};
3388
- if (calcMode === "markPrice")
3438
+ }
3439
+ if (calcMode === "markPrice") {
3389
3440
  return data;
3441
+ }
3390
3442
  const { total_unreal_pnl_index, unrealPnlROI_index, ...rest } = data;
3391
3443
  return {
3392
3444
  ...rest,
@@ -3438,7 +3490,10 @@ var usePositionStream = (symbol = "all", options) => {
3438
3490
  });
3439
3491
  }
3440
3492
  }
3441
- const positionInfoGetter = createGetter(aggregated, 1);
3493
+ const positionInfoGetter = createGetter(
3494
+ aggregated,
3495
+ 1
3496
+ );
3442
3497
  return [
3443
3498
  {
3444
3499
  rows,
@@ -3475,10 +3530,15 @@ var useOrderStream = (params, options) => {
3475
3530
  side,
3476
3531
  size = 50,
3477
3532
  page,
3478
- dateRange
3533
+ dateRange,
3534
+ sourceTypeAll
3479
3535
  } = params;
3480
- const [includes2, setIncludes] = React.useState(params.includes ?? ["ALL"]);
3481
- const [excludes, setExcludes] = React.useState(params.excludes ?? []);
3536
+ const [includes2, setIncludes] = React.useState(
3537
+ params.includes ?? ["ALL"]
3538
+ );
3539
+ const [excludes, setExcludes] = React.useState(
3540
+ params.excludes ?? []
3541
+ );
3482
3542
  const { data: markPrices } = useMarkPricesStream();
3483
3543
  const { registerKeyHandler, unregisterKeyHandler } = useDataCenterContext();
3484
3544
  const [
@@ -3499,38 +3559,63 @@ var useOrderStream = (params, options) => {
3499
3559
  doUpdateAlgoOrder,
3500
3560
  { error: updateAlgoOrderError, isMutating: updateAlgoMutating }
3501
3561
  ] = useMutation("/v1/algo/order", "PUT");
3562
+ const normalOrderKeyFn = React.useMemo(() => {
3563
+ return generateKeyFun("/v1/orders", {
3564
+ status,
3565
+ symbol,
3566
+ side,
3567
+ size,
3568
+ page,
3569
+ dateRange,
3570
+ sourceTypeAll
3571
+ });
3572
+ }, [status, symbol, side, size, page, dateRange]);
3573
+ const algoOrderKeyFn = React.useMemo(() => {
3574
+ return sourceTypeAll ? null : generateKeyFun("/v1/algo/orders", {
3575
+ status,
3576
+ symbol,
3577
+ side,
3578
+ size: 100,
3579
+ page,
3580
+ dateRange
3581
+ });
3582
+ }, [status, symbol, side, dateRange, size]);
3502
3583
  React.useEffect(() => {
3503
3584
  const formatKey = (value) => value ? `:${value}` : "";
3504
3585
  const key = `orders${formatKey(status)}${formatKey(symbol)}${formatKey(
3505
3586
  side
3506
3587
  )}${formatKey(size.toString())}`;
3507
- registerKeyHandler?.(
3508
- key,
3509
- generateKeyFun({ status, symbol, side, size, page, dateRange })
3510
- );
3588
+ registerKeyHandler?.(key, normalOrderKeyFn);
3589
+ if (algoOrderKeyFn) {
3590
+ registerKeyHandler?.(key.replace("orders", "algoOrders"), algoOrderKeyFn);
3591
+ }
3511
3592
  return () => {
3512
3593
  if (!options?.stopOnUnmount)
3513
3594
  return;
3514
3595
  unregisterKeyHandler(key);
3596
+ if (algoOrderKeyFn) {
3597
+ unregisterKeyHandler(key.replace("orders", "algoOrders"));
3598
+ }
3515
3599
  };
3516
- }, [status, symbol, side, size, page, dateRange, options?.keeplive]);
3517
- const ordersResponse = usePrivateInfiniteQuery(
3518
- generateKeyFun({ status, symbol, side, size, page, dateRange }),
3519
- {
3520
- initialSize: 1,
3521
- // revalidateFirstPage: false,
3522
- // onError: (err) => {
3523
- // console.error("fetch failed::::", err);
3524
- // },
3525
- formatter: (data) => data,
3526
- revalidateOnFocus: false
3527
- }
3528
- );
3600
+ }, [normalOrderKeyFn, options?.keeplive]);
3601
+ const normalOrdersResponse = usePrivateInfiniteQuery(normalOrderKeyFn, {
3602
+ initialSize: 1,
3603
+ formatter: (data) => data,
3604
+ revalidateOnFocus: false
3605
+ });
3606
+ const algoOrdersResponse = usePrivateInfiniteQuery(algoOrderKeyFn, {
3607
+ formatter: (data) => data,
3608
+ revalidateOnFocus: false
3609
+ });
3529
3610
  const flattenOrders = React.useMemo(() => {
3530
- if (!ordersResponse.data) {
3611
+ if (!normalOrdersResponse.data || !algoOrdersResponse.data && !sourceTypeAll) {
3531
3612
  return null;
3532
3613
  }
3533
- let orders2 = ordersResponse.data?.map((item) => item.rows)?.flat();
3614
+ let orders2 = normalOrdersResponse.data?.map((item) => item.rows)?.flat();
3615
+ if (algoOrdersResponse.data) {
3616
+ const algoOrders = algoOrdersResponse.data?.map((item) => item.rows)?.flat();
3617
+ orders2 = [...orders2, ...algoOrders];
3618
+ }
3534
3619
  if (includes2.includes("ALL") && excludes.length === 0) {
3535
3620
  return orders2;
3536
3621
  }
@@ -3546,7 +3631,7 @@ var useOrderStream = (params, options) => {
3546
3631
  );
3547
3632
  }
3548
3633
  return orders2;
3549
- }, [ordersResponse.data, includes2, excludes]);
3634
+ }, [normalOrdersResponse.data, algoOrdersResponse.data, includes2, excludes]);
3550
3635
  const orders = React.useMemo(() => {
3551
3636
  if (!flattenOrders) {
3552
3637
  return null;
@@ -3586,13 +3671,13 @@ var useOrderStream = (params, options) => {
3586
3671
  doCancelAllOrders(null),
3587
3672
  doCancelAllAlgoOrders(null, { algo_type: "STOP" })
3588
3673
  ]);
3589
- }, [ordersResponse.data]);
3674
+ }, [normalOrdersResponse.data, algoOrdersResponse.data]);
3590
3675
  const cancelAllTPSLOrders = React.useCallback(() => {
3591
3676
  return cancelAlgoOrdersByTypes([
3592
3677
  types.AlgoOrderRootType.POSITIONAL_TP_SL,
3593
3678
  types.AlgoOrderRootType.TP_SL
3594
3679
  ]);
3595
- }, [ordersResponse.data]);
3680
+ }, [algoOrdersResponse.data]);
3596
3681
  const _updateOrder = React.useCallback(
3597
3682
  (orderId, order, type) => {
3598
3683
  switch (type) {
@@ -3626,7 +3711,8 @@ var useOrderStream = (params, options) => {
3626
3711
  source: `SDK${version_default}`
3627
3712
  }).then((res) => {
3628
3713
  if (res.success) {
3629
- ordersResponse.mutate();
3714
+ normalOrdersResponse.mutate();
3715
+ algoOrdersResponse.mutate();
3630
3716
  return res;
3631
3717
  } else {
3632
3718
  throw new Error(res.message);
@@ -3655,7 +3741,6 @@ var useOrderStream = (params, options) => {
3655
3741
  return _cancelOrder(orderId, "algoOrder", symbol2);
3656
3742
  }, []);
3657
3743
  const loadMore = () => {
3658
- ordersResponse.setSize(ordersResponse.size + 1);
3659
3744
  };
3660
3745
  const cancelTPSLChildOrder = React.useCallback(
3661
3746
  (orderId, rootAlgoOrderId) => {
@@ -3684,14 +3769,18 @@ var useOrderStream = (params, options) => {
3684
3769
  []
3685
3770
  );
3686
3771
  const meta = React.useMemo(() => {
3687
- return ordersResponse.data?.[0]?.meta;
3688
- }, [ordersResponse.data?.[0]]);
3772
+ return normalOrdersResponse.data?.[0]?.meta;
3773
+ }, [normalOrdersResponse.data?.[0]]);
3774
+ const refresh = React.useCallback(() => {
3775
+ normalOrdersResponse.mutate();
3776
+ algoOrdersResponse.mutate();
3777
+ }, []);
3689
3778
  return [
3690
3779
  orders,
3691
3780
  {
3692
3781
  total,
3693
- isLoading: ordersResponse.isLoading,
3694
- refresh: ordersResponse.mutate,
3782
+ isLoading: normalOrdersResponse.isLoading || algoOrdersResponse.isLoading,
3783
+ refresh,
3695
3784
  loadMore,
3696
3785
  cancelAllOrders,
3697
3786
  cancelAllTPSLOrders,
@@ -3782,7 +3871,8 @@ var useCollateral = (options = { dp: 6 }) => {
3782
3871
  totalValue,
3783
3872
  freeCollateral,
3784
3873
  availableBalance,
3785
- unsettledPnL
3874
+ unsettledPnL,
3875
+ holding
3786
3876
  } = useAppStore((state) => state.portfolio);
3787
3877
  const accountInfo = useAppStore((state) => state.accountInfo);
3788
3878
  return {
@@ -3791,14 +3881,14 @@ var useCollateral = (options = { dp: 6 }) => {
3791
3881
  totalValue: totalValue?.toDecimalPlaces(dp).toNumber() ?? null,
3792
3882
  availableBalance,
3793
3883
  unsettledPnL,
3794
- accountInfo
3884
+ accountInfo,
3885
+ holding
3795
3886
  // @hidden
3796
3887
  // positions: positionsPath(positions),
3797
3888
  };
3798
3889
  };
3799
3890
  var useMaxQty = (symbol, side, reduceOnly = false) => {
3800
- const positions2 = usePositions();
3801
- const [orders] = useOrderStream({ status: types.OrderStatus.NEW, size: 500 });
3891
+ const positions3 = usePositions();
3802
3892
  const accountInfo = useAccountInfo();
3803
3893
  const symbolInfo = useSymbolsInfo();
3804
3894
  const { totalCollateral } = useCollateral();
@@ -3807,7 +3897,7 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
3807
3897
  if (!symbol)
3808
3898
  return 0;
3809
3899
  const positionQty = perp.account.getQtyFromPositions(
3810
- positions2 === null ? [] : positions2,
3900
+ positions3 === null ? [] : positions3,
3811
3901
  symbol
3812
3902
  );
3813
3903
  if (reduceOnly) {
@@ -3827,28 +3917,16 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
3827
3917
  }
3828
3918
  return 0;
3829
3919
  }
3830
- if (!markPrices || !markPrices[symbol] || !orders || !accountInfo)
3920
+ if (!markPrices || !markPrices[symbol] || !accountInfo || !positions3)
3831
3921
  return 0;
3832
3922
  const getSymbolInfo = symbolInfo[symbol];
3833
- const filterAlgoOrders = orders.filter(
3834
- (item) => item.algo_order_id === void 0 || item.algo_type === "BRACKET"
3835
- );
3836
- const buyOrdersQty = perp.account.getQtyFromOrdersBySide(
3837
- filterAlgoOrders,
3838
- symbol,
3839
- types.OrderSide.BUY
3840
- );
3841
- const sellOrdersQty = perp.account.getQtyFromOrdersBySide(
3842
- filterAlgoOrders,
3843
- symbol,
3844
- types.OrderSide.SELL
3845
- );
3846
- const otherPositions = !Array.isArray(positions2) ? [] : positions2.filter((item) => item.symbol !== symbol);
3847
- const otherOrders = filterAlgoOrders.filter(
3848
- (item) => item.symbol !== symbol
3923
+ const currentSymbolPosition = positions3.find(
3924
+ (item) => item.symbol === symbol
3849
3925
  );
3926
+ const buyOrdersQty = currentSymbolPosition?.pending_long_qty ?? 0;
3927
+ const sellOrdersQty = currentSymbolPosition?.pending_short_qty ?? 0;
3928
+ const otherPositions = !Array.isArray(positions3) ? [] : positions3.filter((item) => item.symbol !== symbol);
3850
3929
  const otherIMs = perp.account.otherIMs({
3851
- orders: otherOrders,
3852
3930
  positions: otherPositions,
3853
3931
  symbolInfo,
3854
3932
  markPrices,
@@ -3871,10 +3949,9 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
3871
3949
  });
3872
3950
  }, [
3873
3951
  symbol,
3874
- positions2,
3952
+ positions3,
3875
3953
  reduceOnly,
3876
3954
  markPrices,
3877
- orders,
3878
3955
  accountInfo,
3879
3956
  symbolInfo,
3880
3957
  side,
@@ -3883,9 +3960,8 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
3883
3960
  return Math.max(maxQty, 0);
3884
3961
  };
3885
3962
  var useMarginRatio = () => {
3886
- const positions2 = usePositionStore((state2) => state2.positions.all);
3887
- const { rows } = positions2;
3888
- const { notional } = positions2;
3963
+ const positions3 = usePositionStore((state2) => state2.positions.all);
3964
+ const { rows, notional } = positions3;
3889
3965
  const { state } = useAccount();
3890
3966
  const { data: markPrices } = useMarkPricesStream();
3891
3967
  const { totalCollateral } = useCollateral();
@@ -3906,8 +3982,9 @@ var useMarginRatio = () => {
3906
3982
  return null;
3907
3983
  }, [marginRatio, state.status]);
3908
3984
  const mmr = React.useMemo(() => {
3909
- if (!rows || rows.length <= 0 || notional == null)
3985
+ if (!rows || rows.length <= 0 || notional == null) {
3910
3986
  return null;
3987
+ }
3911
3988
  let positionsMM = utils.zero;
3912
3989
  for (let index = 0; index < rows.length; index++) {
3913
3990
  const item = rows[index];
@@ -3926,7 +4003,8 @@ var TestNetWhiteList = [
3926
4003
  types.ARBITRUM_TESTNET_CHAINID,
3927
4004
  types.SOLANA_TESTNET_CHAINID,
3928
4005
  types.MONAD_TESTNET_CHAINID,
3929
- types.ABSTRACT_TESTNET_CHAINID
4006
+ types.ABSTRACT_TESTNET_CHAINID,
4007
+ types.BSC_TESTNET_CHAINID
3930
4008
  ];
3931
4009
  var testnetTokenFallback = types.TesntTokenFallback([
3932
4010
  types.ArbitrumSepoliaTokenInfo,
@@ -4192,7 +4270,7 @@ var useChain = (token) => {
4192
4270
  };
4193
4271
  var useHoldingStream = () => {
4194
4272
  const ws = useWS();
4195
- const { data, isLoading, mutate: mutate3 } = usePrivateQuery(
4273
+ const { data, isLoading, mutate: mutate5 } = usePrivateQuery(
4196
4274
  "/v1/client/holding",
4197
4275
  {
4198
4276
  formatter: (data2) => {
@@ -4216,14 +4294,17 @@ var useHoldingStream = () => {
4216
4294
  onMessage: (data2) => {
4217
4295
  const holding = data2?.balances ?? {};
4218
4296
  if (holding) {
4219
- mutate3((prevData) => {
4297
+ mutate5((prevData) => {
4220
4298
  return prevData?.map((item) => {
4221
4299
  const token = holding[item.token];
4222
- return {
4223
- ...item,
4224
- frozen: token.frozen,
4225
- holding: token.holding
4226
- };
4300
+ if (token) {
4301
+ return {
4302
+ ...item,
4303
+ frozen: token.frozen,
4304
+ holding: token.holding
4305
+ };
4306
+ }
4307
+ return item;
4227
4308
  });
4228
4309
  });
4229
4310
  next(holding);
@@ -4242,7 +4323,7 @@ var useHoldingStream = () => {
4242
4323
 
4243
4324
  // src/orderly/useWithdraw.ts
4244
4325
  var useWithdraw = (options) => {
4245
- const { account: account5, state } = useAccount();
4326
+ const { account: account7, state } = useAccount();
4246
4327
  const [isLoading, setIsLoading] = React.useState(false);
4247
4328
  const { unsettledPnL, availableBalance, freeCollateral } = useCollateral();
4248
4329
  const networkId = useConfig("networkId");
@@ -4288,10 +4369,11 @@ var useWithdraw = (options) => {
4288
4369
  }, [targetChain]);
4289
4370
  const withdraw = React.useCallback(
4290
4371
  (inputs) => {
4291
- return account5.assetsManager.withdraw(inputs).then((res) => {
4372
+ return account7.assetsManager.withdraw({ ...inputs, decimals: 6 }).then((res) => {
4292
4373
  if (res.success) {
4293
4374
  track2(types.TrackerEventName.withdrawSuccess, {
4294
4375
  wallet: state?.connectWallet?.name,
4376
+ // TODO: fix network name, befault is not pass srcChainId
4295
4377
  network: targetChain?.network_infos.name,
4296
4378
  quantity: inputs.amount
4297
4379
  });
@@ -4306,7 +4388,7 @@ var useWithdraw = (options) => {
4306
4388
  throw err;
4307
4389
  });
4308
4390
  },
4309
- [state, targetChain, state]
4391
+ [state, targetChain, state, options?.decimals]
4310
4392
  );
4311
4393
  return {
4312
4394
  dst,
@@ -4322,14 +4404,13 @@ var useDeposit = (options) => {
4322
4404
  const networkId = useConfig("networkId");
4323
4405
  const [balanceRevalidating, setBalanceRevalidating] = React.useState(false);
4324
4406
  const [allowanceRevalidating, setAllowanceRevalidating] = React.useState(false);
4325
- useEventEmitter();
4326
4407
  const [_, { findByChainId }] = useChains(void 0);
4327
4408
  const [quantity, setQuantity] = React.useState("");
4328
4409
  const [depositFee, setDepositFee] = React.useState(0n);
4329
4410
  const [depositFeeRevalidating, setDepositFeeRevalidating] = React.useState(false);
4330
4411
  const [balance, setBalance] = React.useState("0");
4331
4412
  const [allowance, setAllowance] = React.useState("0");
4332
- const { account: account5, state } = useAccount();
4413
+ const { account: account7, state } = useAccount();
4333
4414
  const { track: track2 } = useTrack();
4334
4415
  const prevAddress = React.useRef();
4335
4416
  const getBalanceListener = React.useRef();
@@ -4337,16 +4418,16 @@ var useDeposit = (options) => {
4337
4418
  let chain;
4338
4419
  if (networkId === "testnet") {
4339
4420
  chain = findByChainId(
4340
- utils.isTestnet(options?.srcChainId) ? options?.srcChainId : types.ARBITRUM_TESTNET_CHAINID
4421
+ utils.isTestnet(options.srcChainId) ? options.srcChainId : types.ARBITRUM_TESTNET_CHAINID
4341
4422
  );
4342
4423
  } else {
4343
- chain = findByChainId(options?.srcChainId);
4424
+ chain = findByChainId(options.srcChainId);
4344
4425
  if (!chain?.network_infos?.bridgeless) {
4345
4426
  chain = findByChainId(types.ARBITRUM_MAINNET_CHAINID);
4346
4427
  }
4347
4428
  }
4348
4429
  return chain;
4349
- }, [networkId, findByChainId, options?.srcChainId]);
4430
+ }, [networkId, findByChainId, options.srcChainId]);
4350
4431
  const dst = React.useMemo(() => {
4351
4432
  const USDC = targetChain?.token_infos.find(
4352
4433
  (token) => token.symbol === "USDC"
@@ -4360,18 +4441,18 @@ var useDeposit = (options) => {
4360
4441
  };
4361
4442
  }, [targetChain]);
4362
4443
  const isNativeToken = React.useMemo(
4363
- () => types.isNativeTokenChecker(options?.address || ""),
4364
- [options?.address]
4444
+ () => types.isNativeTokenChecker(options.address || ""),
4445
+ [options.address]
4365
4446
  );
4366
4447
  const fetchBalanceHandler = React.useCallback(
4367
4448
  async (address, decimals) => {
4368
4449
  let balance2;
4369
4450
  if (!!address && types.isNativeTokenChecker(address)) {
4370
- balance2 = await account5.assetsManager.getNativeBalance({
4451
+ balance2 = await account7.assetsManager.getNativeBalance({
4371
4452
  decimals
4372
4453
  });
4373
4454
  } else {
4374
- balance2 = await account5.assetsManager.getBalance(address, { decimals });
4455
+ balance2 = await account7.assetsManager.getBalance(address, { decimals });
4375
4456
  }
4376
4457
  return balance2;
4377
4458
  },
@@ -4397,7 +4478,7 @@ var useDeposit = (options) => {
4397
4478
  continue;
4398
4479
  }
4399
4480
  tasks.push(
4400
- account5.assetsManager.getBalanceByAddress(token.address, {
4481
+ account7.assetsManager.getBalanceByAddress(token.address, {
4401
4482
  decimals: token?.decimals
4402
4483
  })
4403
4484
  );
@@ -4414,7 +4495,7 @@ var useDeposit = (options) => {
4414
4495
  if (address && types.isNativeTokenChecker(address))
4415
4496
  return;
4416
4497
  prevAddress.current = key;
4417
- const allowance2 = await account5.assetsManager.getAllowance({
4498
+ const allowance2 = await account7.assetsManager.getAllowance({
4418
4499
  address,
4419
4500
  vaultAddress,
4420
4501
  decimals
@@ -4429,7 +4510,7 @@ var useDeposit = (options) => {
4429
4510
  if (!address || types.isNativeTokenChecker(address))
4430
4511
  return;
4431
4512
  prevAddress.current = address;
4432
- const allowance2 = await account5.assetsManager.getAllowance({
4513
+ const allowance2 = await account7.assetsManager.getAllowance({
4433
4514
  address,
4434
4515
  decimals
4435
4516
  });
@@ -4453,19 +4534,21 @@ var useDeposit = (options) => {
4453
4534
  if (state.status < types.AccountStatusEnum.Connected)
4454
4535
  return;
4455
4536
  setBalanceRevalidating(true);
4456
- queryBalance(options?.address, options?.decimals);
4537
+ queryBalance(options.address, options.decimals);
4457
4538
  const params = {
4458
- address: options?.address,
4459
- decimals: options?.decimals
4539
+ address: options.address,
4540
+ decimals: options.decimals
4460
4541
  };
4461
- if (account5.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4462
- setAllowance(account5.walletAdapter.formatUnits(types.MaxUint256));
4542
+ if (account7.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4543
+ setAllowance(
4544
+ account7.walletAdapter.formatUnits(types.MaxUint256, options.decimals)
4545
+ );
4463
4546
  return;
4464
4547
  }
4465
- if (dst.chainId !== options?.srcChainId) {
4548
+ if (dst.chainId !== options.srcChainId) {
4466
4549
  queryAllowance(params);
4467
4550
  } else {
4468
- if (dst.symbol !== options?.srcToken) {
4551
+ if (dst.symbol !== options.srcToken) {
4469
4552
  queryAllowance(params);
4470
4553
  } else {
4471
4554
  getAllowanceByDefaultAddress(params);
@@ -4473,54 +4556,60 @@ var useDeposit = (options) => {
4473
4556
  }
4474
4557
  }, [
4475
4558
  state.status,
4476
- options?.address,
4477
- options?.srcChainId,
4478
- options?.srcToken,
4479
- options?.decimals,
4480
- account5.address,
4559
+ options.address,
4560
+ options.srcChainId,
4561
+ options.srcToken,
4562
+ options.decimals,
4563
+ account7.address,
4481
4564
  dst.chainId,
4482
4565
  dst.symbol
4483
4566
  ]);
4484
4567
  const updateAllowanceWhenTxSuccess = React.useCallback(
4485
4568
  (txHash) => {
4486
- return account5.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4569
+ return account7.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4487
4570
  if (receipt.status === 1) {
4488
- account5.assetsManager.getAllowance({ address: options?.address }).then((allowance2) => {
4571
+ account7.assetsManager.getAllowance({ address: options.address }).then((allowance2) => {
4489
4572
  setAllowance(() => allowance2);
4490
4573
  });
4491
4574
  }
4492
4575
  });
4493
4576
  },
4494
- [account5, options?.address]
4577
+ [account7, options.address]
4495
4578
  );
4496
4579
  const approve = React.useCallback(
4497
4580
  async (amount) => {
4498
- if (!options?.address) {
4581
+ if (!options.address) {
4499
4582
  throw new types.SDKError("Address is required");
4500
4583
  }
4501
- return account5.assetsManager.approve({
4584
+ return account7.assetsManager.approve({
4502
4585
  address: options.address,
4503
- amount
4586
+ amount,
4587
+ decimals: options.decimals
4504
4588
  }).then((res) => {
4505
4589
  return updateAllowanceWhenTxSuccess(res.hash);
4506
4590
  }).catch((e) => {
4507
4591
  throw e;
4508
4592
  });
4509
4593
  },
4510
- [account5, getAllowance, options?.address, dst]
4594
+ [account7, getAllowance, options.address, options.decimals, dst]
4511
4595
  );
4512
4596
  const deposit = React.useCallback(async () => {
4513
- if (!options?.address) {
4597
+ if (!options.address) {
4514
4598
  throw new types.SDKError("Address is required");
4515
4599
  }
4516
- const _allowance = await account5.assetsManager.getAllowance({
4517
- address: options?.address
4600
+ const _allowance = await account7.assetsManager.getAllowance({
4601
+ address: options.address,
4602
+ decimals: options.decimals
4518
4603
  });
4519
4604
  setAllowance(() => _allowance);
4520
4605
  if (new utils.Decimal(quantity).greaterThan(_allowance)) {
4521
4606
  throw new types.SDKError("Insufficient allowance");
4522
4607
  }
4523
- return account5.assetsManager.deposit(quantity, depositFee).then((res) => {
4608
+ return account7.assetsManager.deposit({
4609
+ amount: quantity,
4610
+ fee: depositFee,
4611
+ decimals: options.decimals
4612
+ }).then((res) => {
4524
4613
  track2(types.TrackerEventName.depositSuccess, {
4525
4614
  wallet: state?.connectWallet?.name,
4526
4615
  network: targetChain?.network_infos.name,
@@ -4537,15 +4626,22 @@ var useDeposit = (options) => {
4537
4626
  });
4538
4627
  throw e;
4539
4628
  });
4540
- }, [account5, fetchBalance, quantity, depositFee, options?.address]);
4629
+ }, [
4630
+ account7,
4631
+ fetchBalance,
4632
+ quantity,
4633
+ depositFee,
4634
+ options.address,
4635
+ options.decimals
4636
+ ]);
4541
4637
  const loopGetBalance = async () => {
4542
4638
  getBalanceListener.current && clearTimeout(getBalanceListener.current);
4543
- const time = account5.walletAdapter?.chainNamespace === types.ChainNamespace.solana ? 1e4 : 3e3;
4639
+ const time = account7.walletAdapter?.chainNamespace === types.ChainNamespace.solana ? 1e4 : 3e3;
4544
4640
  getBalanceListener.current = setTimeout(async () => {
4545
4641
  try {
4546
4642
  const balance2 = await fetchBalanceHandler(
4547
- options?.address,
4548
- options?.decimals
4643
+ options.address,
4644
+ options.decimals
4549
4645
  );
4550
4646
  setBalance(balance2);
4551
4647
  loopGetBalance();
@@ -4555,12 +4651,13 @@ var useDeposit = (options) => {
4555
4651
  };
4556
4652
  const getDepositFee = React.useCallback(
4557
4653
  async (quantity2) => {
4558
- return account5.assetsManager.getDepositFee(
4559
- quantity2,
4560
- targetChain?.network_infos
4561
- );
4654
+ return account7.assetsManager.getDepositFee({
4655
+ amount: quantity2,
4656
+ chain: targetChain?.network_infos,
4657
+ decimals: options.decimals
4658
+ });
4562
4659
  },
4563
- [account5, targetChain]
4660
+ [account7, targetChain, options.decimals]
4564
4661
  );
4565
4662
  const enquiryDepositFee = React.useCallback(() => {
4566
4663
  if (isNaN(Number(quantity)) || !quantity || Number(quantity) === 0) {
@@ -4583,14 +4680,14 @@ var useDeposit = (options) => {
4583
4680
  enquiryDepositFee();
4584
4681
  }, [quantity]);
4585
4682
  React.useEffect(() => {
4586
- if (!options?.address) {
4683
+ if (!options.address) {
4587
4684
  return;
4588
4685
  }
4589
4686
  loopGetBalance();
4590
4687
  return () => {
4591
4688
  getBalanceListener.current && clearTimeout(getBalanceListener.current);
4592
4689
  };
4593
- }, [options?.address, options?.decimals]);
4690
+ }, [options.address, options.decimals]);
4594
4691
  return {
4595
4692
  /** orderly support chain dst */
4596
4693
  dst,
@@ -4613,62 +4710,188 @@ var useDeposit = (options) => {
4613
4710
  setQuantity
4614
4711
  };
4615
4712
  };
4616
- var useWalletSubscription = (options) => {
4617
- const ws = useWS();
4618
- return useSWRSubscription__default.default("wallet", (_, { next }) => {
4619
- const unsubscribe = ws.privateSubscribe(
4620
- {
4621
- id: "wallet",
4622
- event: "subscribe",
4623
- topic: "wallet",
4624
- ts: Date.now()
4625
- },
4626
- {
4627
- onMessage: (data) => {
4628
- options?.onMessage?.(data);
4629
- next(null, data);
4630
- }
4631
- }
4632
- );
4633
- return () => unsubscribe();
4634
- });
4635
- };
4636
- var useSettleSubscription = (options) => {
4637
- const ws = useWS();
4638
- return useSWRSubscription__default.default("settle", (_, { next }) => {
4639
- const unsubscribe = ws.privateSubscribe(
4640
- {
4641
- id: "settle",
4642
- event: "subscribe",
4643
- topic: "settle",
4644
- ts: utils.getTimestamp()
4645
- },
4646
- {
4647
- onMessage: (data) => {
4648
- options?.onMessage?.(data);
4649
- next(data);
4650
- }
4651
- }
4652
- );
4653
- return () => unsubscribe();
4654
- });
4655
- };
4656
- var useSymbolPriceRange = (symbol, side, price) => {
4657
- const config = useSymbolsInfo();
4658
- const priceRange = config?.[symbol]("price_range");
4659
- const priceScrope = config?.[symbol]("price_scope");
4660
- const { data: prices } = useMarkPricesStream();
4661
- const markPrice = price || prices?.[symbol];
4662
- const range = React.useMemo(() => {
4663
- if (config === void 0 || markPrice === void 0) {
4664
- return void 0;
4665
- }
4666
- if (priceRange === void 0 || Number.isNaN(markPrice)) {
4667
- return void 0;
4713
+ var fetcher3 = (url, options) => {
4714
+ const init2 = {
4715
+ method: options.arg.method,
4716
+ headers: {
4717
+ ...options.arg.signature
4668
4718
  }
4669
- if (side === "BUY") {
4670
- return {
4671
- max: new utils.Decimal(markPrice).mul(1 + priceRange).toNumber(),
4719
+ };
4720
+ if (options.arg.data) {
4721
+ init2.body = JSON.stringify(options.arg.data);
4722
+ }
4723
+ if (typeof options.arg.params === "object" && Object.keys(options.arg.params).length) {
4724
+ const search = new URLSearchParams(options.arg.params);
4725
+ url = `${url}?${search.toString()}`;
4726
+ }
4727
+ return net.mutate(url, init2);
4728
+ };
4729
+ var useSubAccountMutation = (url, method = "POST", options) => {
4730
+ const { accountId, ...restOptions } = options || {};
4731
+ const apiBaseUrl = useConfig("apiBaseUrl");
4732
+ let fullUrl = url;
4733
+ if (!url.startsWith("http")) {
4734
+ fullUrl = `${apiBaseUrl}${url}`;
4735
+ }
4736
+ const account7 = useAccountInstance();
4737
+ const { trigger, reset, data, error, isMutating } = useSWRMutation__default.default(
4738
+ fullUrl,
4739
+ // method === "POST" ? fetcher : deleteFetcher,
4740
+ fetcher3,
4741
+ restOptions
4742
+ );
4743
+ const mutation = React.useCallback(
4744
+ async (data2, params, options2) => {
4745
+ const { accountId: _accountId, ...restOptions2 } = options2 || {};
4746
+ let newUrl = url;
4747
+ if (typeof params === "object" && Object.keys(params).length) {
4748
+ const search = new URLSearchParams(params);
4749
+ newUrl = `${url}?${search.toString()}`;
4750
+ }
4751
+ const payload = {
4752
+ method,
4753
+ url: newUrl,
4754
+ data: data2
4755
+ };
4756
+ const signer = account7.signer;
4757
+ const signature = await signer.sign(payload, utils.getTimestamp());
4758
+ return trigger(
4759
+ {
4760
+ data: data2,
4761
+ params,
4762
+ method,
4763
+ signature: {
4764
+ ...signature,
4765
+ "orderly-account-id": accountId || _accountId || account7.accountId
4766
+ }
4767
+ },
4768
+ restOptions2
4769
+ );
4770
+ },
4771
+ [trigger, account7, accountId]
4772
+ );
4773
+ return [
4774
+ mutation,
4775
+ {
4776
+ data,
4777
+ error,
4778
+ reset,
4779
+ isMutating
4780
+ }
4781
+ ];
4782
+ };
4783
+
4784
+ // src/orderly/useTransfer.ts
4785
+ var useTransfer = (options) => {
4786
+ const { fromAccountId } = options || {};
4787
+ const { unsettledPnL, availableBalance, freeCollateral, holding } = useCollateral();
4788
+ const [doTransfer, { isMutating: submitting }] = useSubAccountMutation(
4789
+ "/v1/internal_transfer",
4790
+ "POST",
4791
+ {
4792
+ accountId: fromAccountId
4793
+ }
4794
+ );
4795
+ const transfer = React.useCallback(
4796
+ async (token, receivers) => {
4797
+ return doTransfer({
4798
+ token,
4799
+ receiver_list: Array.isArray(receivers) ? receivers : [receivers]
4800
+ }).then((res) => {
4801
+ if (res.success) {
4802
+ return res;
4803
+ }
4804
+ throw res;
4805
+ }).catch((err) => {
4806
+ throw err;
4807
+ });
4808
+ },
4809
+ [doTransfer]
4810
+ );
4811
+ const maxAmount = React.useMemo(() => {
4812
+ return freeCollateral;
4813
+ }, [freeCollateral]);
4814
+ const availableTransfer = React.useMemo(() => {
4815
+ if (unsettledPnL < 0) {
4816
+ return freeCollateral;
4817
+ } else {
4818
+ return freeCollateral - unsettledPnL;
4819
+ }
4820
+ }, [freeCollateral, unsettledPnL]);
4821
+ return {
4822
+ submitting,
4823
+ transfer,
4824
+ maxAmount,
4825
+ unsettledPnL,
4826
+ availableBalance,
4827
+ availableTransfer,
4828
+ holding
4829
+ };
4830
+ };
4831
+ var useWalletSubscription = (options) => {
4832
+ const ws = useWS();
4833
+ const { state } = useAccount();
4834
+ return useSWRSubscription__default.default(
4835
+ state.accountId ? ["wallet", state.accountId] : null,
4836
+ (_, { next }) => {
4837
+ const unsubscribe = ws.privateSubscribe(
4838
+ {
4839
+ id: "wallet",
4840
+ event: "subscribe",
4841
+ topic: "wallet",
4842
+ ts: Date.now()
4843
+ },
4844
+ {
4845
+ onMessage: (data) => {
4846
+ options?.onMessage?.(data);
4847
+ next(null, data);
4848
+ }
4849
+ }
4850
+ );
4851
+ return () => unsubscribe();
4852
+ }
4853
+ );
4854
+ };
4855
+ var useSettleSubscription = (options) => {
4856
+ const ws = useWS();
4857
+ const { state } = useAccount();
4858
+ return useSWRSubscription__default.default(
4859
+ state.accountId ? ["settle", state.accountId] : null,
4860
+ (_, { next }) => {
4861
+ const unsubscribe = ws.privateSubscribe(
4862
+ {
4863
+ id: "settle",
4864
+ event: "subscribe",
4865
+ topic: "settle",
4866
+ ts: utils.getTimestamp()
4867
+ },
4868
+ {
4869
+ onMessage: (data) => {
4870
+ options?.onMessage?.(data);
4871
+ next(data);
4872
+ }
4873
+ }
4874
+ );
4875
+ return () => unsubscribe();
4876
+ }
4877
+ );
4878
+ };
4879
+ var useSymbolPriceRange = (symbol, side, price) => {
4880
+ const config = useSymbolsInfo();
4881
+ const priceRange = config?.[symbol]("price_range");
4882
+ const priceScrope = config?.[symbol]("price_scope");
4883
+ const { data: prices } = useMarkPricesStream();
4884
+ const markPrice = price || prices?.[symbol];
4885
+ const range = React.useMemo(() => {
4886
+ if (config === void 0 || markPrice === void 0) {
4887
+ return void 0;
4888
+ }
4889
+ if (priceRange === void 0 || Number.isNaN(markPrice)) {
4890
+ return void 0;
4891
+ }
4892
+ if (side === "BUY") {
4893
+ return {
4894
+ max: new utils.Decimal(markPrice).mul(1 + priceRange).toNumber(),
4672
4895
  min: new utils.Decimal(markPrice).mul(1 - priceScrope).toNumber()
4673
4896
  };
4674
4897
  }
@@ -4679,341 +4902,94 @@ var useSymbolPriceRange = (symbol, side, price) => {
4679
4902
  }, [symbol, side, priceRange, markPrice]);
4680
4903
  return range;
4681
4904
  };
4682
- function offsetToPrice(inputs) {
4683
- const { offset, entryPrice, orderType, orderSide } = inputs;
4684
- if (!offset)
4685
- return;
4686
- if (orderSide === types.OrderSide.BUY) {
4687
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4688
- return new utils.Decimal(entryPrice).add(new utils.Decimal(offset)).toNumber();
4689
- }
4690
- return new utils.Decimal(entryPrice).minus(new utils.Decimal(offset)).toNumber();
4691
- }
4692
- if (orderSide === types.OrderSide.SELL) {
4693
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4694
- return new utils.Decimal(entryPrice).minus(new utils.Decimal(offset)).toNumber();
4905
+ function getMinNotional(props) {
4906
+ const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4907
+ if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
4908
+ try {
4909
+ const calcNotional = new utils.Decimal(price).mul(new utils.Decimal(qty)).toNumber();
4910
+ const notional = Number.parseFloat(`${min_notional}`);
4911
+ if (calcNotional < notional) {
4912
+ let minQty = new utils.Decimal(notional).div(price).toDecimalPlaces(base_dp, utils.Decimal.ROUND_DOWN).add(base_tick ?? 0);
4913
+ if (base_tick && base_tick > 0) {
4914
+ minQty = new utils.Decimal(
4915
+ getRoundedDownDivision(minQty.toNumber(), base_tick)
4916
+ );
4917
+ }
4918
+ const newMinNotional = minQty.mul(price).add(quote_tick ?? 0).toFixed(quote_dp);
4919
+ return newMinNotional;
4920
+ }
4921
+ } catch (e) {
4695
4922
  }
4696
- return new utils.Decimal(entryPrice).add(new utils.Decimal(offset)).toNumber();
4697
4923
  }
4698
4924
  }
4699
- function priceToOffset(inputs, options = {}) {
4700
- const { price, entryPrice, orderType, orderSide } = inputs;
4701
- const { symbol } = options;
4702
- let decimal;
4703
- if (orderSide === types.OrderSide.BUY) {
4704
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4705
- decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
4706
- }
4707
- decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
4708
- }
4709
- if (orderSide === types.OrderSide.SELL) {
4710
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4711
- decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
4925
+ function checkNotional(props) {
4926
+ const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4927
+ if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
4928
+ try {
4929
+ const calcNotional = new utils.Decimal(price).mul(new utils.Decimal(qty)).toNumber();
4930
+ const notional = Number.parseFloat(`${min_notional}`);
4931
+ if (calcNotional < notional) {
4932
+ let minQty = new utils.Decimal(notional).div(price).toDecimalPlaces(base_dp, utils.Decimal.ROUND_DOWN).add(base_tick ?? 0);
4933
+ if (base_tick && base_tick > 0) {
4934
+ minQty = new utils.Decimal(
4935
+ getRoundedDownDivision(minQty.toNumber(), base_tick)
4936
+ );
4937
+ }
4938
+ const newMinNotional = minQty.mul(price).add(quote_tick ?? 0).toFixed(quote_dp);
4939
+ return `The order value should be greater or equal to ${newMinNotional} USDC`;
4940
+ }
4941
+ return void 0;
4942
+ } catch (e) {
4943
+ return void 0;
4712
4944
  }
4713
- decimal = new utils.Decimal(entryPrice).minus(new utils.Decimal(price));
4714
- }
4715
- if (symbol) {
4716
- return decimal.abs().todp(symbol.quote_dp, utils.Decimal.ROUND_UP).toNumber();
4717
4945
  }
4718
- return decimal.abs().toNumber();
4946
+ return void 0;
4719
4947
  }
4720
- function offsetPercentageToPrice(inputs) {
4721
- const { percentage, entryPrice, orderType, orderSide } = inputs;
4722
- if (!percentage)
4723
- return;
4724
- if (orderSide === types.OrderSide.BUY) {
4725
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4726
- return new utils.Decimal(1).add(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
4727
- }
4728
- return new utils.Decimal(1).minus(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
4729
- }
4730
- if (orderSide === types.OrderSide.SELL) {
4731
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4732
- return new utils.Decimal(1).minus(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
4733
- }
4734
- return new utils.Decimal(1).add(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
4735
- }
4948
+ function getRoundedDownDivision(value, tick) {
4949
+ const decimalValue = new utils.Decimal(value);
4950
+ const decimalTick = new utils.Decimal(tick);
4951
+ const quotient = decimalValue.dividedToIntegerBy(decimalTick);
4952
+ return quotient.mul(decimalTick).toNumber();
4736
4953
  }
4737
- function priceToOffsetPercentage(inputs) {
4738
- const { price, entryPrice, orderType, orderSide } = inputs;
4739
- if (orderSide === types.OrderSide.BUY) {
4740
- if (entryPrice === 0)
4741
- return 0;
4742
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4743
- return new utils.Decimal(price).div(new utils.Decimal(entryPrice)).minus(1).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
4954
+
4955
+ // src/services/orderCreator/orderValidation.ts
4956
+ var OrderValidation = class {
4957
+ static getLabel(key) {
4958
+ switch (key) {
4959
+ case "quantity":
4960
+ case "order_quantity":
4961
+ return "Quantity";
4962
+ case "order_price":
4963
+ return "Price";
4964
+ case "trigger_price":
4965
+ return "Trigger price";
4966
+ case "tp_trigger_price":
4967
+ return "TP price";
4968
+ case "sl_trigger_price":
4969
+ return "SL price";
4970
+ default:
4971
+ return key;
4744
4972
  }
4745
- return new utils.Decimal(1).minus(new utils.Decimal(price).div(new utils.Decimal(entryPrice))).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
4746
4973
  }
4747
- if (orderSide === types.OrderSide.SELL) {
4748
- if (entryPrice === 0)
4749
- return 0;
4750
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4751
- return new utils.Decimal(1).minus(new utils.Decimal(price).div(new utils.Decimal(entryPrice))).abs().toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
4752
- }
4753
- return new utils.Decimal(price).div(new utils.Decimal(entryPrice)).minus(1).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
4974
+ static required(key) {
4975
+ return {
4976
+ type: "required",
4977
+ message: `${this.getLabel(key)} is required`
4978
+ };
4754
4979
  }
4755
- }
4756
- function pnlToPrice(inputs) {
4757
- const { qty, pnl, entryPrice, orderType, orderSide } = inputs;
4758
- if (!pnl) {
4759
- return;
4980
+ static min(key, value) {
4981
+ return {
4982
+ type: "min",
4983
+ message: `${this.getLabel(key)} must be greater than ${value}`,
4984
+ value
4985
+ };
4760
4986
  }
4761
- if (qty === 0)
4762
- return;
4763
- if (orderSide === types.OrderSide.BUY) {
4764
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4765
- return new utils.Decimal(entryPrice).plus(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
4766
- }
4767
- return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
4768
- }
4769
- if (orderSide === types.OrderSide.SELL) {
4770
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4771
- return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
4772
- }
4773
- return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
4774
- }
4775
- }
4776
- function priceToPnl(inputs, options = {}) {
4777
- const { qty, price, entryPrice, orderType, orderSide } = inputs;
4778
- const { symbol } = options;
4779
- let decimal = utils.zero;
4780
- if (orderSide === types.OrderSide.BUY) {
4781
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4782
- decimal = new utils.Decimal(qty).mul(
4783
- new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
4784
- );
4785
- }
4786
- decimal = new utils.Decimal(qty).mul(
4787
- new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
4788
- );
4789
- }
4790
- if (orderSide === types.OrderSide.SELL) {
4791
- if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
4792
- decimal = new utils.Decimal(qty).mul(
4793
- new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
4794
- );
4795
- }
4796
- decimal = new utils.Decimal(qty).mul(
4797
- new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
4798
- );
4799
- }
4800
- if (symbol) {
4801
- return decimal.todp(2, utils.Decimal.ROUND_DOWN).toNumber();
4802
- }
4803
- return decimal.toNumber();
4804
- }
4805
- function calcTPSL_ROI(inputs) {
4806
- const qtyNum = Number(inputs.qty);
4807
- const priceNum = Number(inputs.price);
4808
- if (qtyNum === 0 || priceNum === 0)
4809
- return "0";
4810
- return new utils.Decimal(inputs.pnl).div(new utils.Decimal(qtyNum).abs().mul(new utils.Decimal(priceNum))).toString();
4811
- }
4812
- function tpslCalculateHelper(key, inputs, options = {}) {
4813
- const { symbol } = options;
4814
- if (key !== "quantity" && key !== "tp_trigger_price" && key !== "sl_trigger_price" && key !== "tp_pnl" && key !== "sl_pnl" && key !== "tp_offset" && key !== "sl_offset" && key !== "tp_offset_percentage" && key !== "sl_offset_percentage") {
4815
- return {
4816
- [key]: inputs.value
4817
- };
4818
- }
4819
- const orderType = key.startsWith("tp_") ? types.AlgoOrderType.TAKE_PROFIT : types.AlgoOrderType.STOP_LOSS;
4820
- const keyPrefix = key.slice(0, 3);
4821
- let qty = Number(key === "quantity" ? inputs.value : inputs.qty);
4822
- if (qty === 0 && (key === "tp_pnl" || key === "sl_pnl" || key === "tp_trigger_price" || key === "sl_trigger_price")) {
4823
- return {
4824
- [`${keyPrefix}trigger_price`]: "",
4825
- // [`${keyPrefix}offset`]: "",
4826
- // [`${keyPrefix}offset_percentage`]: "",
4827
- [`${keyPrefix}pnl`]: "",
4828
- [key]: inputs.value
4829
- };
4830
- }
4831
- let trigger_price, offset, offset_percentage, pnl;
4832
- const entryPrice = new utils.Decimal(inputs.entryPrice).todp(options.symbol?.quote_dp ?? 2, utils.Decimal.ROUND_UP).toNumber();
4833
- switch (key) {
4834
- case "tp_trigger_price":
4835
- case "sl_trigger_price": {
4836
- trigger_price = inputs.value;
4837
- if (inputs.value === "") {
4838
- return {
4839
- [`${keyPrefix}trigger_price`]: trigger_price,
4840
- [`${keyPrefix}offset`]: "",
4841
- [`${keyPrefix}offset_percentage`]: "",
4842
- [`${keyPrefix}pnl`]: "",
4843
- [`${keyPrefix}ROI`]: ""
4844
- };
4845
- }
4846
- break;
4847
- }
4848
- case "tp_pnl":
4849
- case "sl_pnl": {
4850
- pnl = inputs.value;
4851
- trigger_price = pnlToPrice({
4852
- qty,
4853
- pnl: Number(inputs.value),
4854
- entryPrice,
4855
- orderSide: inputs.orderSide,
4856
- orderType
4857
- });
4858
- break;
4859
- }
4860
- case "tp_offset":
4861
- case "sl_offset": {
4862
- offset = inputs.value;
4863
- trigger_price = offsetToPrice({
4864
- offset: Number(inputs.value),
4865
- entryPrice,
4866
- orderSide: inputs.orderSide,
4867
- orderType: key === "tp_offset" ? types.AlgoOrderType.TAKE_PROFIT : types.AlgoOrderType.STOP_LOSS
4868
- });
4869
- break;
4870
- }
4871
- case "tp_offset_percentage":
4872
- case "sl_offset_percentage": {
4873
- offset_percentage = inputs.value;
4874
- trigger_price = offsetPercentageToPrice({
4875
- percentage: Number(`${inputs.value}`.replace(/\.0{0,2}$/, "")),
4876
- entryPrice,
4877
- orderSide: inputs.orderSide,
4878
- orderType
4879
- });
4880
- break;
4881
- }
4882
- }
4883
- if (!trigger_price)
4884
- return {
4885
- [`${keyPrefix}trigger_price`]: "",
4886
- [`${keyPrefix}offset`]: "",
4887
- [`${keyPrefix}offset_percentage`]: "",
4888
- [`${keyPrefix}pnl`]: "",
4889
- [`${keyPrefix}ROI`]: "",
4890
- [key]: inputs.value
4891
- };
4892
- return {
4893
- [`${keyPrefix}trigger_price`]: utils.todpIfNeed(
4894
- trigger_price,
4895
- symbol?.quote_dp ?? 2
4896
- ),
4897
- [`${keyPrefix}offset`]: offset ?? priceToOffset(
4898
- {
4899
- price: Number(trigger_price),
4900
- entryPrice,
4901
- orderSide: inputs.orderSide,
4902
- orderType
4903
- },
4904
- options
4905
- ),
4906
- [`${keyPrefix}offset_percentage`]: offset_percentage ?? priceToOffsetPercentage({
4907
- price: Number(trigger_price),
4908
- entryPrice,
4909
- orderSide: inputs.orderSide,
4910
- orderType
4911
- }),
4912
- [`${keyPrefix}pnl`]: pnl ?? priceToPnl(
4913
- {
4914
- qty,
4915
- price: Number(trigger_price),
4916
- entryPrice,
4917
- orderSide: inputs.orderSide,
4918
- orderType
4919
- },
4920
- options
4921
- )
4922
- // [`${keyPrefix}ROI`]: calcROI({
4923
- // pnl: Number(pnl ?? 0),
4924
- // qty,
4925
- // price: Number(trigger_price!),
4926
- // }),
4927
- };
4928
- }
4929
- function getMinNotional(props) {
4930
- const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4931
- if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
4932
- try {
4933
- const calcNotional = new utils.Decimal(price).mul(new utils.Decimal(qty)).toNumber();
4934
- const notional = Number.parseFloat(`${min_notional}`);
4935
- if (calcNotional < notional) {
4936
- let minQty = new utils.Decimal(notional).div(price).toDecimalPlaces(base_dp, utils.Decimal.ROUND_DOWN).add(base_tick ?? 0);
4937
- if (base_tick && base_tick > 0) {
4938
- minQty = new utils.Decimal(
4939
- getRoundedDownDivision(minQty.toNumber(), base_tick)
4940
- );
4941
- }
4942
- const newMinNotional = minQty.mul(price).add(quote_tick ?? 0).toFixed(quote_dp);
4943
- return newMinNotional;
4944
- }
4945
- } catch (e) {
4946
- }
4947
- }
4948
- }
4949
- function checkNotional(props) {
4950
- const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4951
- if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
4952
- try {
4953
- const calcNotional = new utils.Decimal(price).mul(new utils.Decimal(qty)).toNumber();
4954
- const notional = Number.parseFloat(`${min_notional}`);
4955
- if (calcNotional < notional) {
4956
- let minQty = new utils.Decimal(notional).div(price).toDecimalPlaces(base_dp, utils.Decimal.ROUND_DOWN).add(base_tick ?? 0);
4957
- if (base_tick && base_tick > 0) {
4958
- minQty = new utils.Decimal(
4959
- getRoundedDownDivision(minQty.toNumber(), base_tick)
4960
- );
4961
- }
4962
- const newMinNotional = minQty.mul(price).add(quote_tick ?? 0).toFixed(quote_dp);
4963
- return `The order value should be greater or equal to ${newMinNotional} USDC`;
4964
- }
4965
- return void 0;
4966
- } catch (e) {
4967
- return void 0;
4968
- }
4969
- }
4970
- return void 0;
4971
- }
4972
- function getRoundedDownDivision(value, tick) {
4973
- const decimalValue = new utils.Decimal(value);
4974
- const decimalTick = new utils.Decimal(tick);
4975
- const quotient = decimalValue.dividedToIntegerBy(decimalTick);
4976
- return quotient.mul(decimalTick).toNumber();
4977
- }
4978
-
4979
- // src/services/orderCreator/orderValidation.ts
4980
- var OrderValidation = class {
4981
- static getLabel(key) {
4982
- switch (key) {
4983
- case "quantity":
4984
- case "order_quantity":
4985
- return "Quantity";
4986
- case "order_price":
4987
- return "Price";
4988
- case "trigger_price":
4989
- return "Trigger price";
4990
- case "tp_trigger_price":
4991
- return "TP price";
4992
- case "sl_trigger_price":
4993
- return "SL price";
4994
- default:
4995
- return key;
4996
- }
4997
- }
4998
- static required(key) {
4999
- return {
5000
- type: "required",
5001
- message: `${this.getLabel(key)} is required`
5002
- };
5003
- }
5004
- static min(key, value) {
5005
- return {
5006
- type: "min",
5007
- message: `${this.getLabel(key)} must be greater than ${value}`,
5008
- value
5009
- };
5010
- }
5011
- static max(key, value) {
5012
- return {
5013
- type: "max",
5014
- message: `${this.getLabel(key)} must be less than ${value}`,
5015
- value
5016
- };
4987
+ static max(key, value) {
4988
+ return {
4989
+ type: "max",
4990
+ message: `${this.getLabel(key)} must be less than ${value}`,
4991
+ value
4992
+ };
5017
4993
  }
5018
4994
  };
5019
4995
 
@@ -5027,7 +5003,11 @@ var BaseOrderCreator = class {
5027
5003
  reduce_only: data.reduce_only,
5028
5004
  order_quantity: data.order_quantity,
5029
5005
  total: data.total
5006
+ // slippage: data.slippage,
5030
5007
  };
5008
+ if (data.order_type === types.OrderType.MARKET && !!data.slippage) {
5009
+ order.slippage = new utils.Decimal(data.slippage).div(100).toNumber();
5010
+ }
5031
5011
  if (data.visible_quantity === 0) {
5032
5012
  order.visible_quantity = data.visible_quantity;
5033
5013
  }
@@ -5226,7 +5206,21 @@ var MarketOrderCreator = class extends BaseOrderCreator {
5226
5206
  };
5227
5207
  }
5228
5208
  validate(values2, configs) {
5229
- return this.baseValidate(values2, configs);
5209
+ return this.baseValidate(values2, configs).then((result) => {
5210
+ const slippage = Number(values2.slippage);
5211
+ const estSlippage = Number.isNaN(configs.estSlippage) ? 0 : Number(configs.estSlippage) * 100;
5212
+ if (!isNaN(slippage) && estSlippage > slippage) {
5213
+ return {
5214
+ ...result,
5215
+ slippage: {
5216
+ type: "max",
5217
+ message: "Estimated slippage exceeds your maximum allowed slippage.",
5218
+ value: estSlippage
5219
+ }
5220
+ };
5221
+ }
5222
+ return result;
5223
+ });
5230
5224
  }
5231
5225
  };
5232
5226
  var { maxPrice, minPrice, scopePrice } = perp.order;
@@ -5915,7 +5909,634 @@ var OrderFactory = class {
5915
5909
  return new GeneralOrderCreator();
5916
5910
  }
5917
5911
  }
5918
- };
5912
+ };
5913
+ function useSubAccountQuery(query, options) {
5914
+ const { formatter, accountId, ...swrOptions } = options || {};
5915
+ const { state, account: account7 } = useAccount();
5916
+ const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
5917
+ return useSWR__namespace.default(
5918
+ () => accountId && (state.status >= types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected) ? [query, accountId] : null,
5919
+ (url, init2) => {
5920
+ return fetcher(url, init2, { formatter });
5921
+ },
5922
+ {
5923
+ ...swrOptions,
5924
+ use: [...middleware, signatureMiddleware2(account7, accountId)],
5925
+ onError: () => {
5926
+ }
5927
+ }
5928
+ );
5929
+ }
5930
+ function signatureMiddleware2(account7, accountId) {
5931
+ const apiBaseUrl = useConfig("apiBaseUrl");
5932
+ return (useSWRNext) => {
5933
+ return (key, fetcher4, config) => {
5934
+ try {
5935
+ const extendedFetcher = async (args) => {
5936
+ const url = Array.isArray(args) ? args[0] : args;
5937
+ const fullUrl = `${apiBaseUrl}${url}`;
5938
+ const signer = account7.signer;
5939
+ const payload = {
5940
+ method: "GET",
5941
+ url
5942
+ };
5943
+ const signature = await signer.sign(payload, utils.getTimestamp());
5944
+ return fetcher4(fullUrl, {
5945
+ headers: {
5946
+ ...signature,
5947
+ "orderly-account-id": accountId
5948
+ }
5949
+ });
5950
+ };
5951
+ return useSWRNext(key, extendedFetcher, config);
5952
+ } catch (e) {
5953
+ throw e;
5954
+ }
5955
+ };
5956
+ };
5957
+ }
5958
+ function formatPortfolio(inputs) {
5959
+ const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
5960
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo || symbolsInfo?.isNil) {
5961
+ return null;
5962
+ }
5963
+ const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
5964
+ const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
5965
+ const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
5966
+ const usdc = holding.find((item) => item.token === "USDC");
5967
+ const totalCollateral = perp.account.totalCollateral({
5968
+ USDCHolding: USDC_holding,
5969
+ nonUSDCHolding: nonUSDC,
5970
+ unsettlementPnL: unsettledPnL
5971
+ });
5972
+ const totalValue = perp.account.totalValue({
5973
+ totalUnsettlementPnL: unsettledPnL,
5974
+ USDCHolding: USDC_holding,
5975
+ nonUSDCHolding: nonUSDC
5976
+ });
5977
+ const totalUnrealizedROI = perp.account.totalUnrealizedROI({
5978
+ totalUnrealizedPnL: unrealizedPnL,
5979
+ totalValue: totalValue.toNumber()
5980
+ });
5981
+ const totalInitialMarginWithOrders = perp.account.totalInitialMarginWithQty({
5982
+ positions: positions3.rows,
5983
+ markPrices,
5984
+ IMR_Factors: accountInfo.imr_factor,
5985
+ maxLeverage: accountInfo.max_leverage,
5986
+ symbolInfo: symbolsInfo
5987
+ });
5988
+ const freeCollateral = perp.account.freeCollateral({
5989
+ totalCollateral,
5990
+ totalInitialMarginWithOrders
5991
+ });
5992
+ const availableBalance = perp.account.availableBalance({
5993
+ USDCHolding: usdc?.holding ?? 0,
5994
+ unsettlementPnL: positions3.total_unsettled_pnl ?? 0
5995
+ });
5996
+ return {
5997
+ totalCollateral,
5998
+ totalValue,
5999
+ totalUnrealizedROI,
6000
+ freeCollateral,
6001
+ availableBalance,
6002
+ unsettledPnL,
6003
+ holding
6004
+ };
6005
+ }
6006
+ function formatPositions(data, accountInfo, symbolsInfo, fundingRates) {
6007
+ if (!accountInfo || !fundingRates || !symbolsInfo) {
6008
+ return data;
6009
+ }
6010
+ let unrealPnL_total = utils.zero, unrealPnL_total_index = utils.zero, notional_total = utils.zero, unsettlementPnL_total = utils.zero;
6011
+ const rows = data.rows.map((item) => {
6012
+ const info = symbolsInfo[item.symbol];
6013
+ const notional = perp.positions.notional(item.position_qty, item.mark_price);
6014
+ const unrealPnl = perp.positions.unrealizedPnL({
6015
+ qty: item.position_qty,
6016
+ openPrice: item?.average_open_price,
6017
+ // markPrice: unRealizedPrice,
6018
+ markPrice: item.mark_price
6019
+ });
6020
+ let unrealPnl_index = 0, unrealPnlROI_index = 0;
6021
+ const imr = perp.account.IMR({
6022
+ maxLeverage: accountInfo.max_leverage,
6023
+ baseIMR: info?.("base_imr"),
6024
+ IMR_Factor: accountInfo.imr_factor[item.symbol],
6025
+ positionNotional: notional,
6026
+ ordersNotional: 0,
6027
+ IMR_factor_power: 4 / 5
6028
+ });
6029
+ const unrealPnlROI = perp.positions.unrealizedPnLROI({
6030
+ positionQty: item.position_qty,
6031
+ openPrice: item.average_open_price,
6032
+ IMR: imr,
6033
+ unrealizedPnL: unrealPnl
6034
+ });
6035
+ if (item.index_price) {
6036
+ unrealPnl_index = perp.positions.unrealizedPnL({
6037
+ qty: item.position_qty,
6038
+ openPrice: item?.average_open_price,
6039
+ // markPrice: unRealizedPrice,
6040
+ markPrice: item.index_price
6041
+ });
6042
+ unrealPnlROI_index = perp.positions.unrealizedPnLROI({
6043
+ positionQty: item.position_qty,
6044
+ openPrice: item.average_open_price,
6045
+ IMR: imr,
6046
+ unrealizedPnL: unrealPnl_index
6047
+ });
6048
+ }
6049
+ const unsettlementPnL2 = perp.positions.unsettlementPnL({
6050
+ positionQty: item.position_qty,
6051
+ markPrice: item.mark_price,
6052
+ costPosition: item.cost_position,
6053
+ sumUnitaryFunding: ramda.propOr(
6054
+ 0,
6055
+ "sum_unitary_funding",
6056
+ fundingRates?.[item.symbol]
6057
+ ),
6058
+ lastSumUnitaryFunding: item.last_sum_unitary_funding
6059
+ });
6060
+ const MMR = perp.positions.MMR({
6061
+ baseMMR: info?.("base_mmr"),
6062
+ baseIMR: info?.("base_imr"),
6063
+ IMRFactor: accountInfo.imr_factor[item.symbol],
6064
+ positionNotional: notional,
6065
+ IMR_factor_power: 4 / 5
6066
+ });
6067
+ unrealPnL_total = unrealPnL_total.add(unrealPnl);
6068
+ unrealPnL_total_index = unrealPnL_total_index.add(unrealPnl_index);
6069
+ notional_total = notional_total.add(notional);
6070
+ unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL2);
6071
+ return {
6072
+ ...item,
6073
+ mm: perp.positions.maintenanceMargin({
6074
+ positionQty: item.position_qty,
6075
+ markPrice: item.mark_price,
6076
+ MMR
6077
+ }),
6078
+ mmr: MMR,
6079
+ notional,
6080
+ unsettlement_pnl: unsettlementPnL2,
6081
+ unrealized_pnl: unrealPnl,
6082
+ unrealized_pnl_index: unrealPnl_index,
6083
+ unrealized_pnl_ROI: unrealPnlROI,
6084
+ unrealized_pnl_ROI_index: unrealPnlROI_index
6085
+ };
6086
+ });
6087
+ const totalUnrealPnl = unrealPnL_total.toNumber();
6088
+ const totalUnrealPnl_index = unrealPnL_total_index.toNumber();
6089
+ const unsettlementPnL = unsettlementPnL_total.toNumber();
6090
+ return {
6091
+ ...data,
6092
+ unrealPnL: totalUnrealPnl,
6093
+ total_unreal_pnl: totalUnrealPnl,
6094
+ total_unreal_pnl_index: totalUnrealPnl_index,
6095
+ notional: notional_total.toNumber(),
6096
+ unsettledPnL: unsettlementPnL,
6097
+ total_unsettled_pnl: unsettlementPnL,
6098
+ rows
6099
+ };
6100
+ }
6101
+ function calcByPrice(positions3, markPrice, indexPrice) {
6102
+ if (!positions3 || !Array.isArray(positions3.rows) || !positions3.rows.length) {
6103
+ return positions3;
6104
+ }
6105
+ return {
6106
+ ...positions3,
6107
+ rows: positions3.rows.map((item) => ({
6108
+ ...item,
6109
+ mark_price: markPrice?.[item.symbol] || item.mark_price,
6110
+ index_price: indexPrice?.[item.symbol] || item.index_price || item.mark_price
6111
+ }))
6112
+ };
6113
+ }
6114
+ var useSubAccountWS = (options) => {
6115
+ const { accountId } = options;
6116
+ const { configStore } = React.useContext(OrderlyContext);
6117
+ const { state, account: account7 } = useAccount();
6118
+ const websocketClient = React.useRef(
6119
+ new net.WS({
6120
+ networkId: configStore.get("networkId"),
6121
+ // not need to subscribe public socket
6122
+ // publicUrl: configStore.get("publicWsUrl"),
6123
+ privateUrl: configStore.get("privateWsUrl"),
6124
+ onSigntureRequest: async () => {
6125
+ const signer = account7.signer;
6126
+ const timestamp = utils.getTimestamp();
6127
+ const result = await signer.signText(timestamp.toString());
6128
+ return { ...result, timestamp };
6129
+ }
6130
+ })
6131
+ );
6132
+ React.useEffect(() => {
6133
+ if (accountId && (state.status === types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected)) {
6134
+ websocketClient.current.openPrivate(accountId);
6135
+ }
6136
+ return () => {
6137
+ websocketClient.current.closePrivate(1e3, "switch account");
6138
+ };
6139
+ }, [accountId, state.status]);
6140
+ return websocketClient.current;
6141
+ };
6142
+
6143
+ // src/subAccount/useSubAccountDataObserver.ts
6144
+ var useSubAccountDataObserver = (accountId) => {
6145
+ const ws = useSubAccountWS({ accountId });
6146
+ const { data: markPrices } = useMarkPricesStream();
6147
+ const { data: indexPrices } = useIndexPricesStream();
6148
+ const symbolsInfo = useSymbolsInfo();
6149
+ const fundingRates = useFundingRatesStore();
6150
+ const [holding, setHolding] = React.useState([]);
6151
+ const [positions3, setPositions] = React.useState(
6152
+ POSITION_EMPTY
6153
+ );
6154
+ const [portfolio, setportfolio] = React.useState();
6155
+ const { data: accountInfo } = useSubAccountQuery(
6156
+ "/v1/client/info",
6157
+ { accountId, revalidateOnFocus: false }
6158
+ );
6159
+ const { data: positionsInfo } = useSubAccountQuery(
6160
+ "/v1/positions",
6161
+ {
6162
+ accountId,
6163
+ formatter: (data) => data
6164
+ }
6165
+ );
6166
+ const { data: holdingRes } = useSubAccountQuery(
6167
+ "/v1/client/holding",
6168
+ {
6169
+ accountId,
6170
+ formatter: (data) => data.holding
6171
+ }
6172
+ );
6173
+ React.useEffect(() => {
6174
+ const portfolio2 = formatPortfolio({
6175
+ holding,
6176
+ positions: positions3,
6177
+ markPrices,
6178
+ accountInfo,
6179
+ symbolsInfo
6180
+ });
6181
+ setportfolio(portfolio2);
6182
+ }, [holding, positions3, markPrices, accountInfo, symbolsInfo]);
6183
+ React.useEffect(() => {
6184
+ if (!positionsInfo)
6185
+ return;
6186
+ if (positionsInfo.rows?.length === 0) {
6187
+ setPositions(positionsInfo);
6188
+ return;
6189
+ }
6190
+ const _positionsInfo = calcByPrice(positionsInfo, markPrices, indexPrices);
6191
+ const _positions = formatPositions(
6192
+ _positionsInfo,
6193
+ accountInfo,
6194
+ symbolsInfo,
6195
+ fundingRates
6196
+ );
6197
+ setPositions({
6198
+ ..._positions,
6199
+ rows: _positions.rows.filter(
6200
+ (item) => item.position_qty !== 0 || item.pending_long_qty !== 0 || item.pending_short_qty !== 0
6201
+ )
6202
+ });
6203
+ }, [
6204
+ positionsInfo,
6205
+ accountInfo,
6206
+ symbolsInfo,
6207
+ fundingRates,
6208
+ markPrices,
6209
+ indexPrices
6210
+ ]);
6211
+ React.useEffect(() => {
6212
+ if (holdingRes) {
6213
+ setHolding(holdingRes);
6214
+ }
6215
+ }, [holdingRes]);
6216
+ React.useEffect(() => {
6217
+ if (!accountId)
6218
+ return;
6219
+ const unsubscribe = ws.privateSubscribe(
6220
+ {
6221
+ id: "balance",
6222
+ event: "subscribe",
6223
+ topic: "balance",
6224
+ ts: Date.now()
6225
+ },
6226
+ {
6227
+ onMessage: (data) => {
6228
+ const holding2 = data?.balances ?? {};
6229
+ setHolding((prev) => {
6230
+ return prev.map((item) => {
6231
+ if (holding2[item.token]) {
6232
+ return { ...item, holding: holding2[item.token].holding };
6233
+ }
6234
+ return item;
6235
+ });
6236
+ });
6237
+ }
6238
+ }
6239
+ );
6240
+ return () => unsubscribe?.();
6241
+ }, [accountId]);
6242
+ React.useEffect(() => {
6243
+ if (!accountId)
6244
+ return;
6245
+ const key = ["/v1/positions", accountId];
6246
+ const unsubscribe = ws.privateSubscribe("position", {
6247
+ onMessage: (data) => {
6248
+ const { positions: nextPositions } = data;
6249
+ useSWR.mutate(
6250
+ key,
6251
+ (prevPositions) => {
6252
+ if (!!prevPositions) {
6253
+ const newPositions = {
6254
+ ...prevPositions,
6255
+ rows: prevPositions.rows.map((row) => {
6256
+ const itemIndex = nextPositions.findIndex(
6257
+ (item) => item.symbol === row.symbol
6258
+ );
6259
+ if (itemIndex >= 0) {
6260
+ const itemArr = nextPositions.splice(itemIndex, 1);
6261
+ const item = itemArr[0];
6262
+ if (item.averageOpenPrice === 0 && item.positionQty !== 0) {
6263
+ return row;
6264
+ }
6265
+ return object2underscore(item);
6266
+ }
6267
+ return row;
6268
+ })
6269
+ };
6270
+ if (nextPositions.length > 0) {
6271
+ newPositions.rows = [
6272
+ ...newPositions.rows,
6273
+ ...nextPositions.map((item) => {
6274
+ return object2underscore(item);
6275
+ })
6276
+ ];
6277
+ }
6278
+ return newPositions;
6279
+ }
6280
+ },
6281
+ {
6282
+ revalidate: false
6283
+ }
6284
+ );
6285
+ }
6286
+ });
6287
+ return () => unsubscribe?.();
6288
+ }, [accountId]);
6289
+ return { portfolio, positions: positions3 };
6290
+ };
6291
+ function offsetToPrice(inputs) {
6292
+ const { offset, entryPrice, orderType, orderSide } = inputs;
6293
+ if (!offset)
6294
+ return;
6295
+ if (orderSide === types.OrderSide.BUY) {
6296
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6297
+ return new utils.Decimal(entryPrice).add(new utils.Decimal(offset)).toNumber();
6298
+ }
6299
+ return new utils.Decimal(entryPrice).minus(new utils.Decimal(offset)).toNumber();
6300
+ }
6301
+ if (orderSide === types.OrderSide.SELL) {
6302
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6303
+ return new utils.Decimal(entryPrice).minus(new utils.Decimal(offset)).toNumber();
6304
+ }
6305
+ return new utils.Decimal(entryPrice).add(new utils.Decimal(offset)).toNumber();
6306
+ }
6307
+ }
6308
+ function priceToOffset(inputs, options = {}) {
6309
+ const { price, entryPrice, orderType, orderSide } = inputs;
6310
+ const { symbol } = options;
6311
+ let decimal;
6312
+ if (orderSide === types.OrderSide.BUY) {
6313
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6314
+ decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
6315
+ }
6316
+ decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
6317
+ }
6318
+ if (orderSide === types.OrderSide.SELL) {
6319
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6320
+ decimal = new utils.Decimal(price).minus(new utils.Decimal(entryPrice));
6321
+ }
6322
+ decimal = new utils.Decimal(entryPrice).minus(new utils.Decimal(price));
6323
+ }
6324
+ if (symbol) {
6325
+ return decimal.abs().todp(symbol.quote_dp, utils.Decimal.ROUND_UP).toNumber();
6326
+ }
6327
+ return decimal.abs().toNumber();
6328
+ }
6329
+ function offsetPercentageToPrice(inputs) {
6330
+ const { percentage, entryPrice, orderType, orderSide } = inputs;
6331
+ if (!percentage)
6332
+ return;
6333
+ if (orderSide === types.OrderSide.BUY) {
6334
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6335
+ return new utils.Decimal(1).add(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
6336
+ }
6337
+ return new utils.Decimal(1).minus(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
6338
+ }
6339
+ if (orderSide === types.OrderSide.SELL) {
6340
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6341
+ return new utils.Decimal(1).minus(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
6342
+ }
6343
+ return new utils.Decimal(1).add(new utils.Decimal(percentage)).mul(new utils.Decimal(entryPrice)).toNumber();
6344
+ }
6345
+ }
6346
+ function priceToOffsetPercentage(inputs) {
6347
+ const { price, entryPrice, orderType, orderSide } = inputs;
6348
+ if (orderSide === types.OrderSide.BUY) {
6349
+ if (entryPrice === 0)
6350
+ return 0;
6351
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6352
+ return new utils.Decimal(price).div(new utils.Decimal(entryPrice)).minus(1).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
6353
+ }
6354
+ return new utils.Decimal(1).minus(new utils.Decimal(price).div(new utils.Decimal(entryPrice))).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
6355
+ }
6356
+ if (orderSide === types.OrderSide.SELL) {
6357
+ if (entryPrice === 0)
6358
+ return 0;
6359
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6360
+ return new utils.Decimal(1).minus(new utils.Decimal(price).div(new utils.Decimal(entryPrice))).abs().toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
6361
+ }
6362
+ return new utils.Decimal(price).div(new utils.Decimal(entryPrice)).minus(1).toDecimalPlaces(4, utils.Decimal.ROUND_DOWN).toNumber();
6363
+ }
6364
+ }
6365
+ function pnlToPrice(inputs) {
6366
+ const { qty, pnl, entryPrice, orderType, orderSide } = inputs;
6367
+ if (!pnl) {
6368
+ return;
6369
+ }
6370
+ if (qty === 0)
6371
+ return;
6372
+ if (orderSide === types.OrderSide.BUY) {
6373
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6374
+ return new utils.Decimal(entryPrice).plus(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
6375
+ }
6376
+ return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
6377
+ }
6378
+ if (orderSide === types.OrderSide.SELL) {
6379
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6380
+ return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
6381
+ }
6382
+ return new utils.Decimal(entryPrice).add(new utils.Decimal(pnl).div(new utils.Decimal(qty))).toNumber();
6383
+ }
6384
+ }
6385
+ function priceToPnl(inputs, options = {}) {
6386
+ const { qty, price, entryPrice, orderType, orderSide } = inputs;
6387
+ const { symbol } = options;
6388
+ let decimal = utils.zero;
6389
+ if (orderSide === types.OrderSide.BUY) {
6390
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6391
+ decimal = new utils.Decimal(qty).mul(
6392
+ new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
6393
+ );
6394
+ }
6395
+ decimal = new utils.Decimal(qty).mul(
6396
+ new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
6397
+ );
6398
+ }
6399
+ if (orderSide === types.OrderSide.SELL) {
6400
+ if (orderType === types.AlgoOrderType.TAKE_PROFIT) {
6401
+ decimal = new utils.Decimal(qty).mul(
6402
+ new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
6403
+ );
6404
+ }
6405
+ decimal = new utils.Decimal(qty).mul(
6406
+ new utils.Decimal(price).minus(new utils.Decimal(entryPrice))
6407
+ );
6408
+ }
6409
+ if (symbol) {
6410
+ return decimal.todp(2, utils.Decimal.ROUND_DOWN).toNumber();
6411
+ }
6412
+ return decimal.toNumber();
6413
+ }
6414
+ function calcTPSL_ROI(inputs) {
6415
+ const qtyNum = Number(inputs.qty);
6416
+ const priceNum = Number(inputs.price);
6417
+ if (qtyNum === 0 || priceNum === 0)
6418
+ return "0";
6419
+ return new utils.Decimal(inputs.pnl).div(new utils.Decimal(qtyNum).abs().mul(new utils.Decimal(priceNum))).toString();
6420
+ }
6421
+ function tpslCalculateHelper(key, inputs, options = {}) {
6422
+ const { symbol } = options;
6423
+ if (key !== "quantity" && key !== "tp_trigger_price" && key !== "sl_trigger_price" && key !== "tp_pnl" && key !== "sl_pnl" && key !== "tp_offset" && key !== "sl_offset" && key !== "tp_offset_percentage" && key !== "sl_offset_percentage") {
6424
+ return {
6425
+ [key]: inputs.value
6426
+ };
6427
+ }
6428
+ const orderType = key.startsWith("tp_") ? types.AlgoOrderType.TAKE_PROFIT : types.AlgoOrderType.STOP_LOSS;
6429
+ const keyPrefix = key.slice(0, 3);
6430
+ let qty = Number(key === "quantity" ? inputs.value : inputs.qty);
6431
+ if (qty === 0 && (key === "tp_pnl" || key === "sl_pnl" || key === "tp_trigger_price" || key === "sl_trigger_price")) {
6432
+ return {
6433
+ [`${keyPrefix}trigger_price`]: "",
6434
+ // [`${keyPrefix}offset`]: "",
6435
+ // [`${keyPrefix}offset_percentage`]: "",
6436
+ [`${keyPrefix}pnl`]: "",
6437
+ [key]: inputs.value
6438
+ };
6439
+ }
6440
+ let trigger_price, offset, offset_percentage, pnl;
6441
+ const entryPrice = new utils.Decimal(inputs.entryPrice).todp(options.symbol?.quote_dp ?? 2, utils.Decimal.ROUND_UP).toNumber();
6442
+ switch (key) {
6443
+ case "tp_trigger_price":
6444
+ case "sl_trigger_price": {
6445
+ trigger_price = inputs.value;
6446
+ if (inputs.value === "") {
6447
+ return {
6448
+ [`${keyPrefix}trigger_price`]: trigger_price,
6449
+ [`${keyPrefix}offset`]: "",
6450
+ [`${keyPrefix}offset_percentage`]: "",
6451
+ [`${keyPrefix}pnl`]: "",
6452
+ [`${keyPrefix}ROI`]: ""
6453
+ };
6454
+ }
6455
+ break;
6456
+ }
6457
+ case "tp_pnl":
6458
+ case "sl_pnl": {
6459
+ pnl = inputs.value;
6460
+ trigger_price = pnlToPrice({
6461
+ qty,
6462
+ pnl: Number(inputs.value),
6463
+ entryPrice,
6464
+ orderSide: inputs.orderSide,
6465
+ orderType
6466
+ });
6467
+ break;
6468
+ }
6469
+ case "tp_offset":
6470
+ case "sl_offset": {
6471
+ offset = inputs.value;
6472
+ trigger_price = offsetToPrice({
6473
+ offset: Number(inputs.value),
6474
+ entryPrice,
6475
+ orderSide: inputs.orderSide,
6476
+ orderType: key === "tp_offset" ? types.AlgoOrderType.TAKE_PROFIT : types.AlgoOrderType.STOP_LOSS
6477
+ });
6478
+ break;
6479
+ }
6480
+ case "tp_offset_percentage":
6481
+ case "sl_offset_percentage": {
6482
+ offset_percentage = inputs.value;
6483
+ trigger_price = offsetPercentageToPrice({
6484
+ percentage: Number(`${inputs.value}`.replace(/\.0{0,2}$/, "")),
6485
+ entryPrice,
6486
+ orderSide: inputs.orderSide,
6487
+ orderType
6488
+ });
6489
+ break;
6490
+ }
6491
+ }
6492
+ if (!trigger_price)
6493
+ return {
6494
+ [`${keyPrefix}trigger_price`]: "",
6495
+ [`${keyPrefix}offset`]: "",
6496
+ [`${keyPrefix}offset_percentage`]: "",
6497
+ [`${keyPrefix}pnl`]: "",
6498
+ [`${keyPrefix}ROI`]: "",
6499
+ [key]: inputs.value
6500
+ };
6501
+ return {
6502
+ [`${keyPrefix}trigger_price`]: utils.todpIfNeed(
6503
+ trigger_price,
6504
+ symbol?.quote_dp ?? 2
6505
+ ),
6506
+ [`${keyPrefix}offset`]: offset ?? priceToOffset(
6507
+ {
6508
+ price: Number(trigger_price),
6509
+ entryPrice,
6510
+ orderSide: inputs.orderSide,
6511
+ orderType
6512
+ },
6513
+ options
6514
+ ),
6515
+ [`${keyPrefix}offset_percentage`]: offset_percentage ?? priceToOffsetPercentage({
6516
+ price: Number(trigger_price),
6517
+ entryPrice,
6518
+ orderSide: inputs.orderSide,
6519
+ orderType
6520
+ }),
6521
+ [`${keyPrefix}pnl`]: pnl ?? priceToPnl(
6522
+ {
6523
+ qty,
6524
+ price: Number(trigger_price),
6525
+ entryPrice,
6526
+ orderSide: inputs.orderSide,
6527
+ orderType
6528
+ },
6529
+ options
6530
+ )
6531
+ // [`${keyPrefix}ROI`]: calcROI({
6532
+ // pnl: Number(pnl ?? 0),
6533
+ // qty,
6534
+ // price: Number(trigger_price!),
6535
+ // }),
6536
+ };
6537
+ }
6538
+
6539
+ // src/orderly/useTakeProfitAndStopLoss/useTPSL.ts
5919
6540
  var useTaskProfitAndStopLossInternal = (position, options) => {
5920
6541
  const isEditing = typeof options?.isEditing !== "undefined" ? options.isEditing : !!options?.defaultOrder;
5921
6542
  const [order, setOrder] = React.useState({
@@ -5929,11 +6550,8 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
5929
6550
  });
5930
6551
  const symbolInfo = useSymbolsInfo()[position.symbol]();
5931
6552
  const { data: markPrice } = useMarkPrice(order.symbol);
5932
- const [doCreateOrder, { isMutating: isCreateMutating }] = useMutation("/v1/algo/order");
5933
- const [doUpdateOrder, { isMutating: isUpdateMutating }] = useMutation(
5934
- "/v1/algo/order",
5935
- "PUT"
5936
- );
6553
+ const [doCreateOrder, { isMutating: isCreateMutating }] = useSubAccountMutation("/v1/algo/order");
6554
+ const [doUpdateOrder, { isMutating: isUpdateMutating }] = useSubAccountMutation("/v1/algo/order", "PUT");
5937
6555
  const [doDeleteOrder] = useMutation("/v1/algo/order", "DELETE");
5938
6556
  const [errors, setErrors] = React.useState(null);
5939
6557
  React.useEffect(() => {
@@ -6049,22 +6667,22 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
6049
6667
  compare() ? types.AlgoOrderRootType.POSITIONAL_TP_SL : types.AlgoOrderRootType.TP_SL
6050
6668
  );
6051
6669
  };
6052
- const submit = async () => {
6670
+ const submit = async (params) => {
6053
6671
  const defaultOrder = options?.defaultOrder;
6054
6672
  const orderId = defaultOrder?.algo_order_id;
6055
6673
  const algoType = defaultOrder?.algo_type;
6056
6674
  if (!orderId) {
6057
- return createOrder();
6675
+ return createOrder(params);
6058
6676
  }
6059
6677
  if (algoType === types.AlgoOrderRootType.POSITIONAL_TP_SL) {
6060
6678
  if (compare()) {
6061
- return updateOrder(orderId);
6679
+ return updateOrder(orderId, params);
6062
6680
  }
6063
- return createOrder();
6681
+ return createOrder(params);
6064
6682
  }
6065
- return updateOrder(orderId);
6683
+ return updateOrder(orderId, params);
6066
6684
  };
6067
- const createOrder = () => {
6685
+ const createOrder = (params) => {
6068
6686
  const orderCreator = getOrderCreator2();
6069
6687
  const orderBody = orderCreator.create(
6070
6688
  order,
@@ -6076,7 +6694,7 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
6076
6694
  orderBody.child_orders = orderBody.child_orders.filter(
6077
6695
  (order2) => order2.is_activated
6078
6696
  );
6079
- return doCreateOrder(orderBody);
6697
+ return doCreateOrder(orderBody, {}, params);
6080
6698
  };
6081
6699
  const deleteOrder = (orderId, symbol) => {
6082
6700
  return doDeleteOrder(null, {
@@ -6084,7 +6702,7 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
6084
6702
  symbol
6085
6703
  });
6086
6704
  };
6087
- const updateOrder = (orderId) => {
6705
+ const updateOrder = (orderId, params) => {
6088
6706
  const orderCreator = getOrderCreator2();
6089
6707
  const [updatedOrderEntity, orderEntity] = orderCreator.crateUpdateOrder(
6090
6708
  // @ts-ignore
@@ -6101,10 +6719,14 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
6101
6719
  if (needDelete) {
6102
6720
  return deleteOrder(orderId, order.symbol);
6103
6721
  }
6104
- return doUpdateOrder({
6105
- order_id: orderId,
6106
- ...updatedOrderEntity
6107
- });
6722
+ return doUpdateOrder(
6723
+ {
6724
+ order_id: orderId,
6725
+ ...updatedOrderEntity
6726
+ },
6727
+ {},
6728
+ params
6729
+ );
6108
6730
  };
6109
6731
  return [
6110
6732
  ramda.omit(["ignoreValidate"], order),
@@ -6147,6 +6769,7 @@ var useSymbolLeverage = (symbol) => {
6147
6769
  const maxAccountLeverage = info?.max_leverage;
6148
6770
  const res = useQuery(`/v1/public/info/${symbol}`, {
6149
6771
  dedupingInterval: 1e3 * 60 * 60 * 24,
6772
+ // 24 hours
6150
6773
  revalidateOnFocus: false,
6151
6774
  errorRetryCount: 2,
6152
6775
  errorRetryInterval: 200
@@ -6188,7 +6811,7 @@ var useAssetsHistory = (options) => {
6188
6811
  searchParams.set("end_t", options.endTime);
6189
6812
  return `/v1/asset/history?${searchParams.toString()}`;
6190
6813
  };
6191
- const { data, isLoading, mutate: mutate3 } = usePrivateQuery(
6814
+ const { data, isLoading, mutate: mutate5 } = usePrivateQuery(
6192
6815
  getKey(),
6193
6816
  {
6194
6817
  formatter: (data2) => data2,
@@ -6198,7 +6821,7 @@ var useAssetsHistory = (options) => {
6198
6821
  );
6199
6822
  const updateList = useDebounce.useDebouncedCallback(
6200
6823
  (data2) => {
6201
- mutate3();
6824
+ mutate5();
6202
6825
  },
6203
6826
  // delay in ms
6204
6827
  300
@@ -6320,7 +6943,7 @@ var useFundingFeeHistory = (params, options) => {
6320
6943
  ];
6321
6944
  };
6322
6945
  var useDistributionHistory = (parmas) => {
6323
- let { type, dataRange, page, pageSize } = parmas;
6946
+ const { type, dataRange, page, pageSize } = parmas;
6324
6947
  const infos = useSymbolsInfo();
6325
6948
  const getKey = () => {
6326
6949
  const search = new URLSearchParams();
@@ -6353,14 +6976,39 @@ var useDistributionHistory = (parmas) => {
6353
6976
  };
6354
6977
  });
6355
6978
  }, [data, infos]);
6356
- return [
6357
- parsedData,
6979
+ return [parsedData, { meta: data?.meta, isLoading, isValidating }];
6980
+ };
6981
+ var useTransferHistory = (parmas) => {
6982
+ const { dataRange, page, size, side, fromId, toId } = parmas;
6983
+ const infos = useSymbolsInfo();
6984
+ const memoizedQueryKey = React__default.default.useMemo(() => {
6985
+ const search = new URLSearchParams();
6986
+ search.set("page", page.toString());
6987
+ search.set("size", size.toString());
6988
+ search.set("side", side);
6989
+ search.set("main_sub_only", `${true}`);
6990
+ if (dataRange) {
6991
+ search.set("start_t", dataRange[0].toString());
6992
+ search.set("end_t", dataRange[1].toString());
6993
+ }
6994
+ return `/v1/internal_transfer_history?${search.toString()}`;
6995
+ }, [page, size, fromId, toId, dataRange]);
6996
+ const { data, isLoading } = usePrivateQuery(
6997
+ memoizedQueryKey,
6358
6998
  {
6359
- meta: data?.meta,
6360
- isLoading,
6361
- isValidating
6999
+ // initialSize: 1,
7000
+ formatter: (data2) => data2,
7001
+ revalidateOnFocus: false,
7002
+ errorRetryCount: 3
6362
7003
  }
6363
- ];
7004
+ );
7005
+ const parsedData = React__default.default.useMemo(() => {
7006
+ if (!Array.isArray(data?.rows) || !data?.rows.length || infos.isNil) {
7007
+ return [];
7008
+ }
7009
+ return data.rows;
7010
+ }, [data, infos]);
7011
+ return [parsedData, { meta: data?.meta, isLoading }];
6364
7012
  };
6365
7013
  var MaintenanceStatus = /* @__PURE__ */ ((MaintenanceStatus2) => {
6366
7014
  MaintenanceStatus2[MaintenanceStatus2["None"] = 0] = "None";
@@ -6372,7 +7020,7 @@ function useMaintenanceStatus() {
6372
7020
  const [startTime, setStartTime] = React.useState();
6373
7021
  const [endTime, setEndTime] = React.useState();
6374
7022
  const [brokerName, setBrokerName] = React.useState("Orderly network");
6375
- const { data: systemInfo, mutate: mutate3 } = useQuery(
7023
+ const { data: systemInfo, mutate: mutate5 } = useQuery(
6376
7024
  `/v1/public/system_info?source=maintenance`,
6377
7025
  {
6378
7026
  revalidateOnFocus: false,
@@ -6432,23 +7080,30 @@ var useStorageLedgerAddress = () => {
6432
7080
  ledgerWallet
6433
7081
  };
6434
7082
  };
7083
+
7084
+ // src/orderly/usePrivateDataObserver.ts
6435
7085
  var usePrivateDataObserver = (options) => {
6436
7086
  const ws = useWS();
6437
7087
  const ee = useEventEmitter();
6438
- const { state, account: account5 } = useAccount();
7088
+ const { state, account: account7 } = useAccount();
6439
7089
  const { setAccountInfo, restoreHolding, cleanAll } = useAppStore(
6440
7090
  (state2) => state2.actions
6441
7091
  );
6442
7092
  const statusActions = useApiStatusActions();
6443
7093
  const calculatorService = useCalculatorService();
6444
7094
  const positionsActions = usePositionActions();
6445
- const { data: clientInfo } = usePrivateQuery("/v1/client/info");
7095
+ const { data: clientInfo } = usePrivateQuery(
7096
+ "/v1/client/info",
7097
+ {
7098
+ revalidateOnFocus: false
7099
+ }
7100
+ );
6446
7101
  React.useEffect(() => {
6447
7102
  if (clientInfo) {
6448
7103
  setAccountInfo(clientInfo);
6449
7104
  }
6450
7105
  }, [clientInfo, setAccountInfo]);
6451
- const { data: positions2, isLoading: isPositionLoading } = usePrivateQuery("/v1/positions", {
7106
+ const { data: positions3, isLoading: isPositionLoading } = usePrivateQuery("/v1/positions", {
6452
7107
  formatter: (data) => data,
6453
7108
  onError: (error) => {
6454
7109
  statusActions.updateApiError("positions", error.message);
@@ -6463,9 +7118,9 @@ var usePrivateDataObserver = (options) => {
6463
7118
  positionsActions.clearAll();
6464
7119
  }
6465
7120
  };
6466
- account5.on(core.EVENT_NAMES.statusChanged, handler);
7121
+ account7.on(core.EVENT_NAMES.statusChanged, handler);
6467
7122
  return () => {
6468
- account5.off(core.EVENT_NAMES.statusChanged, handler);
7123
+ account7.off(core.EVENT_NAMES.statusChanged, handler);
6469
7124
  };
6470
7125
  }, []);
6471
7126
  React.useEffect(() => {
@@ -6474,10 +7129,10 @@ var usePrivateDataObserver = (options) => {
6474
7129
  }
6475
7130
  }, [isPositionLoading, statusActions]);
6476
7131
  React.useEffect(() => {
6477
- if (positions2 && Array.isArray(positions2.rows)) {
6478
- calculatorService.calc("position" /* POSITION */, positions2);
7132
+ if (positions3 && Array.isArray(positions3.rows)) {
7133
+ calculatorService.calc("position" /* POSITION */, positions3);
6479
7134
  }
6480
- }, [calculatorService, positions2]);
7135
+ }, [calculatorService, positions3]);
6481
7136
  const { data: holding } = usePrivateQuery(
6482
7137
  "/v1/client/holding",
6483
7138
  {
@@ -6486,6 +7141,8 @@ var usePrivateDataObserver = (options) => {
6486
7141
  }
6487
7142
  );
6488
7143
  React.useEffect(() => {
7144
+ if (!account7.accountId)
7145
+ return;
6489
7146
  const unsubscribe = ws.privateSubscribe(
6490
7147
  {
6491
7148
  id: "balance",
@@ -6502,20 +7159,32 @@ var usePrivateDataObserver = (options) => {
6502
7159
  }
6503
7160
  }
6504
7161
  );
6505
- return () => unsubscribe();
6506
- }, []);
7162
+ return () => unsubscribe?.();
7163
+ }, [account7.accountId]);
7164
+ const isHoldingInit = React.useRef(false);
6507
7165
  React.useEffect(() => {
6508
- if (holding) {
7166
+ if (!holding) {
7167
+ return;
7168
+ }
7169
+ if (isHoldingInit.current) {
7170
+ calculatorService.calc("portfolio" /* PORTFOLIO */, { holding });
7171
+ } else {
6509
7172
  restoreHolding(holding);
6510
7173
  }
7174
+ isHoldingInit.current = true;
6511
7175
  }, [holding]);
6512
- const [subOrder, setSubOrder] = useLocalStorage(
6513
- "orderly_subscribe_order",
6514
- true
6515
- );
7176
+ const [subOrder] = useLocalStorage("orderly_subscribe_order", true);
6516
7177
  const updateOrders = (data, isAlgoOrder) => {
6517
7178
  const keysMap = options.getKeysMap("orders");
6518
- keysMap.forEach((getKey, key) => {
7179
+ const filteredKeys = /* @__PURE__ */ new Map();
7180
+ const keyStartWith = isAlgoOrder ? "algoOrders" : "orders";
7181
+ const keys = keysMap.keys();
7182
+ for (const key of keys) {
7183
+ if (key.startsWith(keyStartWith)) {
7184
+ filteredKeys.set(key, keysMap.get(key));
7185
+ }
7186
+ }
7187
+ filteredKeys.forEach((getKey, key) => {
6519
7188
  useSWR.mutate(
6520
7189
  useSWRInfinite.unstable_serialize((index, prevData) => [
6521
7190
  getKey(index, prevData),
@@ -6548,10 +7217,12 @@ var usePrivateDataObserver = (options) => {
6548
7217
  });
6549
7218
  };
6550
7219
  React.useEffect(() => {
6551
- if (!state.accountId)
7220
+ if (!state.accountId) {
6552
7221
  return;
6553
- if (subOrder !== true)
7222
+ }
7223
+ if (subOrder !== true) {
6554
7224
  return;
7225
+ }
6555
7226
  const unsubscribe = ws.privateSubscribe("executionreport", {
6556
7227
  onMessage: (data) => {
6557
7228
  updateOrders(data, false);
@@ -6572,8 +7243,9 @@ var usePrivateDataObserver = (options) => {
6572
7243
  return () => unsubscribe?.();
6573
7244
  }, [state.accountId, subOrder]);
6574
7245
  React.useEffect(() => {
6575
- if (!state.accountId)
7246
+ if (!state.accountId) {
6576
7247
  return;
7248
+ }
6577
7249
  const key = ["/v1/positions", state.accountId];
6578
7250
  const unsubscribe = ws.privateSubscribe("position", {
6579
7251
  onMessage: (data) => {
@@ -6602,9 +7274,7 @@ var usePrivateDataObserver = (options) => {
6602
7274
  if (nextPositions.length > 0) {
6603
7275
  newPositions.rows = [
6604
7276
  ...newPositions.rows,
6605
- ...nextPositions.map((item) => {
6606
- return object2underscore(item);
6607
- })
7277
+ ...nextPositions.map(object2underscore)
6608
7278
  ];
6609
7279
  }
6610
7280
  return newPositions;
@@ -6621,43 +7291,6 @@ var usePrivateDataObserver = (options) => {
6621
7291
  };
6622
7292
  }, [state.accountId]);
6623
7293
  };
6624
- var useWSObserver = (calculatorService) => {
6625
- const ws = useWS();
6626
- React.useEffect(() => {
6627
- const markPriceSubscription = ws.subscribe("markprices", {
6628
- onMessage: (message) => {
6629
- const data = /* @__PURE__ */ Object.create(null);
6630
- for (let index = 0; index < message.length; index++) {
6631
- const element = message[index];
6632
- data[element.symbol] = element.price;
6633
- }
6634
- calculatorService.calc("markPrice" /* MARK_PRICE */, data, {
6635
- skipWhenOnPause: true
6636
- });
6637
- },
6638
- onError: (error) => {
6639
- }
6640
- });
6641
- const indexPriceSubscription = ws.subscribe("indexprices", {
6642
- onMessage: (message) => {
6643
- if (!Array.isArray(message))
6644
- return;
6645
- const prices = /* @__PURE__ */ Object.create(null);
6646
- for (let index = 0; index < message.length; index++) {
6647
- const element = message[index];
6648
- prices[element.symbol.replace("SPOT", "PERP")] = element.price;
6649
- }
6650
- calculatorService.calc("indexPrice" /* INDEX_PRICE */, prices, {
6651
- skipWhenOnPause: true
6652
- });
6653
- }
6654
- });
6655
- return () => {
6656
- markPriceSubscription?.();
6657
- indexPriceSubscription?.();
6658
- };
6659
- }, []);
6660
- };
6661
7294
  var useMarketStore = zustand.create(
6662
7295
  (set, get3) => ({
6663
7296
  market: [],
@@ -6763,7 +7396,9 @@ var DataCenterContext = React.createContext(
6763
7396
  {}
6764
7397
  );
6765
7398
  var useDataCenterContext = () => React.useContext(DataCenterContext);
6766
- var DataCenterProvider = ({ children }) => {
7399
+ var DataCenterProvider = ({
7400
+ children
7401
+ }) => {
6767
7402
  const { error, done } = usePreLoadData();
6768
7403
  const calculatorService = useCalculatorService();
6769
7404
  usePublicDataObserver();
@@ -6777,8 +7412,9 @@ var DataCenterProvider = ({ children }) => {
6777
7412
  if (error) {
6778
7413
  return /* @__PURE__ */ jsxRuntime.jsx("div", { children: "Data load failed" });
6779
7414
  }
6780
- if (!done)
7415
+ if (!done) {
6781
7416
  return null;
7417
+ }
6782
7418
  return /* @__PURE__ */ jsxRuntime.jsx(
6783
7419
  DataCenterContext.Provider,
6784
7420
  {
@@ -6860,7 +7496,7 @@ var ExtendedConfigStore = class extends core.DefaultConfigStore {
6860
7496
  }
6861
7497
  };
6862
7498
  var OrderlyConfigProvider = (props) => {
6863
- const [account5, setAccount] = React__default.default.useState(null);
7499
+ const [account7, setAccount] = React__default.default.useState(null);
6864
7500
  const {
6865
7501
  configStore,
6866
7502
  keyStore,
@@ -6898,9 +7534,9 @@ var OrderlyConfigProvider = (props) => {
6898
7534
  ];
6899
7535
  }, [walletAdapters]);
6900
7536
  React.useLayoutEffect(() => {
6901
- let account6 = core.SimpleDI.get(core.Account.instanceName);
6902
- if (!account6) {
6903
- account6 = new core.Account(
7537
+ let account8 = core.SimpleDI.get(core.Account.instanceName);
7538
+ if (!account8) {
7539
+ account8 = new core.Account(
6904
7540
  innerConfigStore,
6905
7541
  innerKeyStore,
6906
7542
  // innerGetWalletAdapter,
@@ -6909,9 +7545,9 @@ var OrderlyConfigProvider = (props) => {
6909
7545
  contracts
6910
7546
  }
6911
7547
  );
6912
- core.SimpleDI.registerByName(core.Account.instanceName, account6);
7548
+ core.SimpleDI.registerByName(core.Account.instanceName, account8);
6913
7549
  }
6914
- setAccount(account6);
7550
+ setAccount(account8);
6915
7551
  }, []);
6916
7552
  const filteredChains = React.useMemo(() => {
6917
7553
  if (typeof chainFilter === "function") {
@@ -6919,7 +7555,7 @@ var OrderlyConfigProvider = (props) => {
6919
7555
  }
6920
7556
  return chainFilter;
6921
7557
  }, [props.chainFilter, innerConfigStore]);
6922
- if (!account5) {
7558
+ if (!account7) {
6923
7559
  return null;
6924
7560
  }
6925
7561
  return /* @__PURE__ */ jsxRuntime.jsx(
@@ -7176,6 +7812,16 @@ function formatNumber(qty, dp) {
7176
7812
  return void 0;
7177
7813
  }
7178
7814
  }
7815
+ function calculate(values2, fieldName, value, markPrice, config) {
7816
+ const fieldHandler = getCalculateHandler(fieldName);
7817
+ const newValues = ramda.compose(
7818
+ ramda.head,
7819
+ // orderEntityFormatHandle(baseDP, quoteDP),
7820
+ fieldHandler,
7821
+ baseInputHandle
7822
+ )([values2, fieldName, value, markPrice, config]);
7823
+ return newValues;
7824
+ }
7179
7825
  function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7180
7826
  let isNewVersion = false;
7181
7827
  if (typeof symbolOrOrder === "object") {
@@ -7195,7 +7841,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7195
7841
  const notSupportData = React.useRef({});
7196
7842
  const [errors, setErrors] = React.useState(null);
7197
7843
  const ee = useEventEmitter();
7198
- const positions2 = usePositions();
7844
+ const positions3 = usePositions();
7199
7845
  const fieldDirty = React.useRef({});
7200
7846
  const submitted = React.useRef(false);
7201
7847
  const askAndBid = React.useRef([]);
@@ -7418,7 +8064,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7418
8064
  }
7419
8065
  return createOrder(parsedData);
7420
8066
  }, [parsedData]);
7421
- const calculate = React.useCallback(
8067
+ const calculate2 = React.useCallback(
7422
8068
  (values2, field, value) => {
7423
8069
  const fieldHandler = getCalculateHandler(field);
7424
8070
  const newValues = ramda.compose(
@@ -7468,7 +8114,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7468
8114
  if (typeof parsedData.order_quantity !== "undefined") {
7469
8115
  fieldDirty.current.order_quantity = true;
7470
8116
  }
7471
- const values2 = calculate(parsedData, item.key, item.value);
8117
+ const values2 = calculate2(parsedData, item.key, item.value);
7472
8118
  values2.isStopOrder = values2.order_type?.startsWith("STOP") || false;
7473
8119
  values2.total = values2.total || "";
7474
8120
  prevOrderData.current = parsedData;
@@ -7569,7 +8215,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7569
8215
  baseIMR,
7570
8216
  baseMMR,
7571
8217
  totalCollateral,
7572
- positions: positions2 == null ? [] : positions2,
8218
+ positions: positions3 == null ? [] : positions3,
7573
8219
  IMR_Factor: accountInfo["imr_factor"][symbol],
7574
8220
  orderFee,
7575
8221
  newOrder: {
@@ -7600,7 +8246,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7600
8246
  return null;
7601
8247
  const leverage = perp.order.estLeverage({
7602
8248
  totalCollateral,
7603
- positions: positions2 === null ? [] : positions2,
8249
+ positions: positions3 === null ? [] : positions3,
7604
8250
  newOrder: {
7605
8251
  symbol: parsedData.symbol,
7606
8252
  qty: result.quantity,
@@ -7612,7 +8258,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7612
8258
  baseIMR,
7613
8259
  baseMMR,
7614
8260
  totalCollateral,
7615
- positions2,
8261
+ positions3,
7616
8262
  formattedOrder?.order_price,
7617
8263
  formattedOrder?.order_quantity,
7618
8264
  formattedOrder?.total,
@@ -7631,7 +8277,7 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7631
8277
  estLeverage,
7632
8278
  helper: {
7633
8279
  //@ts-ignore
7634
- calculate,
8280
+ calculate: calculate2,
7635
8281
  validator
7636
8282
  // clearErrors,
7637
8283
  },
@@ -8466,12 +9112,12 @@ var useDaily = (options) => {
8466
9112
  start_date,
8467
9113
  end_date
8468
9114
  )}`;
8469
- const { data: dailyVolume, mutate: mutate3 } = usePrivateQuery(url, {
9115
+ const { data: dailyVolume, mutate: mutate5 } = usePrivateQuery(url, {
8470
9116
  revalidateOnFocus: true
8471
9117
  });
8472
9118
  return {
8473
9119
  data: dailyVolume,
8474
- mutate: mutate3
9120
+ mutate: mutate5
8475
9121
  };
8476
9122
  };
8477
9123
  var useReferralRebateSummary = (params) => {
@@ -8583,14 +9229,14 @@ var useRefereeRebateSummary = (params) => {
8583
9229
  }
8584
9230
  const {
8585
9231
  data,
8586
- mutate: mutate3,
9232
+ mutate: mutate5,
8587
9233
  isLoading
8588
9234
  } = usePrivateQuery(url, {
8589
9235
  revalidateOnFocus: true
8590
9236
  });
8591
9237
  return {
8592
9238
  data,
8593
- mutate: mutate3,
9239
+ mutate: mutate5,
8594
9240
  isLoading
8595
9241
  };
8596
9242
  };
@@ -8639,12 +9285,9 @@ var useGetReferralCode = (accountId) => {
8639
9285
  };
8640
9286
  };
8641
9287
  var useReferralInfo = () => {
8642
- const {
8643
- data,
8644
- mutate: mutate3,
8645
- isLoading,
8646
- error
8647
- } = usePrivateQuery("/v1/referral/info", {
9288
+ const { state } = useAccount();
9289
+ const { data, isLoading, error } = useSubAccountQuery("/v1/referral/info", {
9290
+ accountId: state?.mainAccountId,
8648
9291
  revalidateOnFocus: true
8649
9292
  });
8650
9293
  const isTrader = React.useMemo(() => {
@@ -8657,7 +9300,10 @@ var useReferralInfo = () => {
8657
9300
  return void 0;
8658
9301
  return (data?.referrer_info?.referral_codes?.length || 0) > 0;
8659
9302
  }, [data?.referrer_info]);
8660
- const [pinCodes] = useLocalStorage("orderly_referral_codes", []);
9303
+ const [pinCodes] = useLocalStorage(
9304
+ "orderly_referral_codes",
9305
+ []
9306
+ );
8661
9307
  const getFirstRefCode = React.useCallback(() => {
8662
9308
  if (!data?.referrer_info.referral_codes)
8663
9309
  return void 0;
@@ -8748,9 +9394,9 @@ var useAllBrokers = () => {
8748
9394
  };
8749
9395
  var useCurEpochEstimate = (type) => {
8750
9396
  const [data, setData] = React.useState(void 0);
8751
- const { account: account5 } = useAccount();
9397
+ const { account: account7 } = useAccount();
8752
9398
  const brokers = useAllBrokers();
8753
- const address = account5.address;
9399
+ const address = account7.address;
8754
9400
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/current_epoch_estimate?address=${address}` : `/v1/public/market_making_rewards/current_epoch_estimate?address=${address}`;
8755
9401
  const { data: estimateData } = useQuery(address !== void 0 ? path2 : "", {
8756
9402
  formatter: (res) => {
@@ -13710,14 +14356,14 @@ var DistributionId = /* @__PURE__ */ ((DistributionId2) => {
13710
14356
  })(DistributionId || {});
13711
14357
  var useGetClaimed = (id) => {
13712
14358
  const [data, setData] = React.useState(0);
13713
- const { account: account5 } = useAccount();
13714
- const address = account5.address;
14359
+ const { account: account7 } = useAccount();
14360
+ const address = account7.address;
13715
14361
  const env = useGetEnv();
13716
14362
  const refresh = React.useCallback(() => {
13717
14363
  const params = getContractByEnv(env);
13718
14364
  if (typeof address === "undefined")
13719
14365
  return;
13720
- account5.walletAdapter?.callOnChain(
14366
+ account7.walletAdapter?.callOnChain(
13721
14367
  // @ts-ignore
13722
14368
  { public_rpc_url: params.orderlyChainRpcUrl },
13723
14369
  params.orderlyContract,
@@ -13742,8 +14388,8 @@ var useGetClaimed = (id) => {
13742
14388
 
13743
14389
  // src/trading-rewards/useWalletRewardsHistory.ts
13744
14390
  var useWalletRewardsHistory = (type) => {
13745
- const { account: account5 } = useAccount();
13746
- const address = account5.address;
14391
+ const { account: account7 } = useAccount();
14392
+ const address = account7.address;
13747
14393
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/wallet_rewards_history?address=${address}` : `/v1/public/market_making_rewards/group_rewards_history?address=${address}`;
13748
14394
  const {
13749
14395
  data,
@@ -13765,11 +14411,36 @@ var useWalletRewardsHistory = (type) => {
13765
14411
  });
13766
14412
  return [data, { refresh, error }];
13767
14413
  };
14414
+
14415
+ // src/trading-rewards/useTradingRwardsStatus.tsx
14416
+ var EpochStatus = /* @__PURE__ */ ((EpochStatus2) => {
14417
+ EpochStatus2["active"] = "Active";
14418
+ EpochStatus2["paused"] = "Paused";
14419
+ EpochStatus2["ended"] = "Ended";
14420
+ return EpochStatus2;
14421
+ })(EpochStatus || {});
14422
+ function useTradingRewardsStatus(isMMRewards) {
14423
+ const path2 = isMMRewards ? "/v1/public/market_making_rewards/status" : "/v1/public/trading_rewards/status";
14424
+ const { data: statusInfo } = useQuery(path2, {
14425
+ formatter: (res) => {
14426
+ const data = {
14427
+ ...res,
14428
+ epochStatus: res.epoch_status,
14429
+ currentEpoch: res.current_epoch,
14430
+ lastCompletedEpoch: res.last_completed_epoch
14431
+ };
14432
+ return data;
14433
+ }
14434
+ });
14435
+ return {
14436
+ statusInfo
14437
+ };
14438
+ }
13768
14439
  var useApiKeyManager = (queryParams) => {
13769
- const { account: account5 } = useAccount();
14440
+ const { account: account7, state, isSubAccount } = useAccount();
13770
14441
  const { keyInfo } = queryParams || {};
13771
14442
  const keyInfoPrams = getQueryParamsFromObject(keyInfo);
13772
- const { data, mutate: mutate3, error, isLoading } = usePrivateQuery(
14443
+ const { data, mutate: mutate5, error, isLoading } = usePrivateQuery(
13773
14444
  `/v1/client/key_info${keyInfoPrams.length > 0 ? `?${keyInfoPrams}` : ""}`,
13774
14445
  {
13775
14446
  formatter: (data2) => data2?.rows
@@ -13802,7 +14473,14 @@ var useApiKeyManager = (queryParams) => {
13802
14473
  });
13803
14474
  }, []);
13804
14475
  const generateOrderlyKey = (scope) => {
13805
- return account5?.createApiKey(365, {
14476
+ if (isSubAccount) {
14477
+ return account7?.createSubAccountApiKey(365, {
14478
+ tag: "manualCreated",
14479
+ scope,
14480
+ subAccountId: state.accountId
14481
+ });
14482
+ }
14483
+ return account7?.createApiKey(365, {
13806
14484
  tag: "manualCreated",
13807
14485
  scope
13808
14486
  });
@@ -13816,7 +14494,7 @@ var useApiKeyManager = (queryParams) => {
13816
14494
  return [
13817
14495
  data,
13818
14496
  {
13819
- refresh: mutate3,
14497
+ refresh: mutate5,
13820
14498
  error,
13821
14499
  isLoading,
13822
14500
  generateOrderlyKey,
@@ -13927,7 +14605,7 @@ var calcEstLiqPrice = (order, askAndBid, inputs) => {
13927
14605
  markPrice,
13928
14606
  totalCollateral,
13929
14607
  futures_taker_fee_rate,
13930
- positions: positions2
14608
+ positions: positions3
13931
14609
  } = inputs;
13932
14610
  const orderFee = perp.order.orderFee({
13933
14611
  qty: quantity,
@@ -13939,7 +14617,7 @@ var calcEstLiqPrice = (order, askAndBid, inputs) => {
13939
14617
  baseIMR,
13940
14618
  baseMMR,
13941
14619
  totalCollateral,
13942
- positions: positions2 == null ? [] : positions2,
14620
+ positions: positions3 == null ? [] : positions3,
13943
14621
  IMR_Factor: imr_factor,
13944
14622
  orderFee,
13945
14623
  newOrder: {
@@ -13954,7 +14632,7 @@ var calcEstLiqPrice = (order, askAndBid, inputs) => {
13954
14632
  };
13955
14633
  var calcEstLeverage = (order, askAndBid, inputs) => {
13956
14634
  const result = getPriceAndQty(order, askAndBid);
13957
- const { totalCollateral, positions: positions2, symbol } = inputs;
14635
+ const { totalCollateral, positions: positions3, symbol } = inputs;
13958
14636
  if (!result)
13959
14637
  return null;
13960
14638
  const { price, quantity } = result;
@@ -13962,7 +14640,7 @@ var calcEstLeverage = (order, askAndBid, inputs) => {
13962
14640
  return null;
13963
14641
  return perp.order.estLeverage({
13964
14642
  totalCollateral,
13965
- positions: positions2,
14643
+ positions: positions3,
13966
14644
  newOrder: {
13967
14645
  symbol,
13968
14646
  qty: result.quantity,
@@ -14056,7 +14734,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14056
14734
  ...options.initialOrder
14057
14735
  };
14058
14736
  const { actions: orderEntryActions, entry: orderEntity } = useOrderStore(initialOrder);
14059
- const calculate = React.useCallback(
14737
+ const calculate2 = React.useCallback(
14060
14738
  (values2, fieldName, value, markPrice, config) => {
14061
14739
  const fieldHandler = getCalculateHandler(fieldName);
14062
14740
  const newValues = ramda.compose(
@@ -14078,7 +14756,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14078
14756
  return;
14079
14757
  }
14080
14758
  const { markPrice } = additional ?? { markPrice: 0 };
14081
- let newValues = calculate(
14759
+ let newValues = calculate2(
14082
14760
  { ...orderEntity },
14083
14761
  key,
14084
14762
  value,
@@ -14087,7 +14765,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14087
14765
  );
14088
14766
  if (key === "order_type") {
14089
14767
  if (value === types.OrderType.MARKET || value === types.OrderType.STOP_MARKET) {
14090
- newValues = calculate(
14768
+ newValues = calculate2(
14091
14769
  newValues,
14092
14770
  "order_price",
14093
14771
  markPrice,
@@ -14121,7 +14799,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14121
14799
  const calculateTPSL = (key, newValues, markPrice, symbolInfo2) => {
14122
14800
  if (key === "order_price") {
14123
14801
  if (typeof newValues.tp_pnl !== "undefined") {
14124
- newValues = calculate(
14802
+ newValues = calculate2(
14125
14803
  newValues,
14126
14804
  "tp_pnl",
14127
14805
  newValues.tp_pnl,
@@ -14130,7 +14808,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14130
14808
  );
14131
14809
  }
14132
14810
  if (typeof newValues.sl_pnl !== "undefined") {
14133
- newValues = calculate(
14811
+ newValues = calculate2(
14134
14812
  newValues,
14135
14813
  "sl_pnl",
14136
14814
  newValues.sl_pnl,
@@ -14140,7 +14818,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14140
14818
  }
14141
14819
  } else {
14142
14820
  if (typeof newValues.tp_trigger_price !== "undefined") {
14143
- newValues = calculate(
14821
+ newValues = calculate2(
14144
14822
  newValues,
14145
14823
  "tp_trigger_price",
14146
14824
  newValues.tp_trigger_price,
@@ -14149,7 +14827,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14149
14827
  );
14150
14828
  }
14151
14829
  if (typeof newValues.sl_trigger_price !== "undefined") {
14152
- newValues = calculate(
14830
+ newValues = calculate2(
14153
14831
  newValues,
14154
14832
  "sl_trigger_price",
14155
14833
  newValues.sl_trigger_price,
@@ -14167,7 +14845,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14167
14845
  }
14168
14846
  let newValues = { ...orderEntity };
14169
14847
  Object.keys(values2).forEach((key) => {
14170
- newValues = calculate(
14848
+ newValues = calculate2(
14171
14849
  newValues,
14172
14850
  key,
14173
14851
  values2[key],
@@ -14184,7 +14862,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14184
14862
  return;
14185
14863
  let newValues = { ...orderEntity };
14186
14864
  if (baseOn.length === 0) {
14187
- newValues = calculate(
14865
+ newValues = calculate2(
14188
14866
  { ...orderEntity },
14189
14867
  "order_price",
14190
14868
  markPrice,
@@ -14193,7 +14871,7 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14193
14871
  );
14194
14872
  } else {
14195
14873
  baseOn.forEach((key) => {
14196
- newValues = calculate(
14874
+ newValues = calculate2(
14197
14875
  { ...newValues },
14198
14876
  key,
14199
14877
  orderEntity[key],
@@ -14220,14 +14898,15 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14220
14898
  }
14221
14899
  orderEntryActions.updateOrder(newValues);
14222
14900
  },
14223
- [calculate, options.symbolInfo, orderEntity, orderEntryActions]
14901
+ [calculate2, options.symbolInfo, orderEntity, orderEntryActions]
14224
14902
  );
14225
14903
  const validate = (order, creator, options2) => {
14226
- const { markPrice, maxQty } = options2;
14904
+ const { markPrice, maxQty, estSlippage } = options2;
14227
14905
  return creator?.validate(order, {
14228
14906
  symbol: symbolInfo,
14229
14907
  maxQty,
14230
- markPrice
14908
+ markPrice,
14909
+ estSlippage
14231
14910
  });
14232
14911
  };
14233
14912
  const generateOrder = (creator, options2) => {
@@ -14278,7 +14957,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
14278
14957
  const actions = useMarkPriceActions();
14279
14958
  const symbolConfig = useSymbolsInfo();
14280
14959
  const accountInfo = useAccountInfo();
14281
- const positions2 = usePositions();
14960
+ const positions3 = usePositions();
14282
14961
  const symbolInfo = symbolConfig[symbol]();
14283
14962
  const markPrice = actions.getMarkPriceBySymbol(symbol);
14284
14963
  const {
@@ -14294,6 +14973,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
14294
14973
  ...options,
14295
14974
  symbolInfo
14296
14975
  });
14976
+ const [estSlippage, setEstSlippage] = React.useState(null);
14297
14977
  const [doCreateOrder, { isMutating }] = useMutation(
14298
14978
  getCreateOrderUrl(formattedOrder)
14299
14979
  );
@@ -14327,12 +15007,61 @@ var useOrderEntry2 = (symbol, options = {}) => {
14327
15007
  updateOrderPrice();
14328
15008
  }
14329
15009
  };
15010
+ const updateEstSlippage = (orderBook) => {
15011
+ if (formattedOrder.order_type !== types.OrderType.MARKET || !formattedOrder.order_quantity) {
15012
+ setEstSlippage(null);
15013
+ return;
15014
+ }
15015
+ const { order_quantity, side } = formattedOrder;
15016
+ let avgExecutionPrice;
15017
+ let book;
15018
+ const filledBorders = [];
15019
+ let orderQuantity = new utils.Decimal(order_quantity);
15020
+ if (side === types.OrderSide.BUY) {
15021
+ book = orderBook.asks.reverse();
15022
+ } else {
15023
+ book = orderBook.bids;
15024
+ }
15025
+ for (let i = 0; i < book.length; i++) {
15026
+ const price = book[i][0];
15027
+ const quantity = book[i][1];
15028
+ if (isNaN(price) || isNaN(quantity)) {
15029
+ continue;
15030
+ }
15031
+ if (orderQuantity.gt(quantity)) {
15032
+ orderQuantity = orderQuantity.minus(quantity);
15033
+ filledBorders.push([price, quantity]);
15034
+ } else {
15035
+ filledBorders.push([price, orderQuantity.toNumber()]);
15036
+ break;
15037
+ }
15038
+ }
15039
+ if (filledBorders.length > 0) {
15040
+ const sumPrice = filledBorders.reduce((acc, curr) => {
15041
+ return acc.plus(new utils.Decimal(curr[0]).mul(curr[1]));
15042
+ }, utils.zero);
15043
+ avgExecutionPrice = sumPrice.div(order_quantity);
15044
+ }
15045
+ if (avgExecutionPrice) {
15046
+ const bestPrice = book[0][0];
15047
+ const estSlippage2 = avgExecutionPrice.minus(bestPrice).abs().div(bestPrice).toNumber();
15048
+ setEstSlippage(estSlippage2);
15049
+ }
15050
+ };
14330
15051
  React.useEffect(() => {
14331
15052
  updateOrderPrice();
14332
15053
  }, [formattedOrder.order_type_ext, formattedOrder.level]);
14333
15054
  const onOrderBookUpdate = useDebounce.useDebouncedCallback((data) => {
14334
- askAndBid.current = data;
15055
+ const parsedData = [
15056
+ [data.asks?.[data.asks.length - 1]?.[0], data.bids?.[0]?.[0]],
15057
+ [data.asks?.[data.asks.length - 2]?.[0], data.bids?.[1]?.[0]],
15058
+ [data.asks?.[data.asks.length - 3]?.[0], data.bids?.[2]?.[0]],
15059
+ [data.asks?.[data.asks.length - 4]?.[0], data.bids?.[3]?.[0]],
15060
+ [data.asks?.[data.asks.length - 5]?.[0], data.bids?.[4]?.[0]]
15061
+ ];
15062
+ askAndBid.current = parsedData;
14335
15063
  updateOrderPriceByOrderBook();
15064
+ updateEstSlippage(data);
14336
15065
  }, 200);
14337
15066
  React.useEffect(() => {
14338
15067
  ee.on("orderbook:update", onOrderBookUpdate);
@@ -14358,9 +15087,10 @@ var useOrderEntry2 = (symbol, options = {}) => {
14358
15087
  const prepareData = React.useCallback(() => {
14359
15088
  return {
14360
15089
  markPrice: actions.getMarkPriceBySymbol(symbol),
14361
- maxQty
15090
+ maxQty,
15091
+ estSlippage
14362
15092
  };
14363
- }, [maxQty, symbol]);
15093
+ }, [maxQty, symbol, estSlippage]);
14364
15094
  const interactiveValidate = (order) => {
14365
15095
  validateFunc(order).then((errors) => {
14366
15096
  const keys = Object.keys(errors);
@@ -14472,10 +15202,10 @@ var useOrderEntry2 = (symbol, options = {}) => {
14472
15202
  futures_taker_fee_rate: accountInfo.futures_taker_fee_rate,
14473
15203
  imr_factor: accountInfo.imr_factor[symbol],
14474
15204
  symbol,
14475
- positions: positions2
15205
+ positions: positions3
14476
15206
  });
14477
15207
  return estLiqPrice2;
14478
- }, [formattedOrder, accountInfo, positions2, totalCollateral, symbol, maxQty]);
15208
+ }, [formattedOrder, accountInfo, positions3, totalCollateral, symbol, maxQty]);
14479
15209
  const estLeverage = React.useMemo(() => {
14480
15210
  const orderQuantity = Number(formattedOrder.order_quantity);
14481
15211
  if (orderQuantity === 0 || orderQuantity > maxQty) {
@@ -14483,10 +15213,10 @@ var useOrderEntry2 = (symbol, options = {}) => {
14483
15213
  }
14484
15214
  return calcEstLeverage(formattedOrder, askAndBid.current[0], {
14485
15215
  totalCollateral,
14486
- positions: positions2,
15216
+ positions: positions3,
14487
15217
  symbol
14488
15218
  });
14489
- }, [formattedOrder, accountInfo, positions2, totalCollateral, symbol, maxQty]);
15219
+ }, [formattedOrder, accountInfo, positions3, totalCollateral, symbol, maxQty]);
14490
15220
  const resetErrors = () => {
14491
15221
  setMeta(
14492
15222
  immer$1.produce((draft) => {
@@ -14548,6 +15278,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
14548
15278
  maxQty,
14549
15279
  estLiqPrice,
14550
15280
  estLeverage,
15281
+ estSlippage,
14551
15282
  helper: {
14552
15283
  /**
14553
15284
  * @deprecated use validate instead
@@ -14778,14 +15509,104 @@ var useRestrictedInfo = (options) => {
14778
15509
  content
14779
15510
  };
14780
15511
  };
15512
+ var usePositionClose = (options) => {
15513
+ const { position, order: initialOrder } = options;
15514
+ const { type, quantity, price } = initialOrder;
15515
+ const symbol = position.symbol;
15516
+ const [errors, setErrors] = React.useState(null);
15517
+ const symbolsInfo = useSymbolsInfo();
15518
+ const { data: markPrices } = useMarkPricesStream();
15519
+ const [doCreateOrder, { isMutating }] = useSubAccountMutation(
15520
+ "/v1/order",
15521
+ "POST",
15522
+ {
15523
+ accountId: position.account_id
15524
+ }
15525
+ );
15526
+ const side = position.position_qty > 0 ? types.OrderSide.SELL : types.OrderSide.BUY;
15527
+ const closeOrderData = React.useMemo(() => {
15528
+ const data = {
15529
+ order_quantity: quantity,
15530
+ symbol,
15531
+ order_type: type,
15532
+ side,
15533
+ reduce_only: true
15534
+ };
15535
+ if (type === types.OrderType.LIMIT) {
15536
+ data.order_price = price;
15537
+ }
15538
+ return data;
15539
+ }, [symbol, price, type, quantity]);
15540
+ const maxQty = React.useMemo(() => {
15541
+ if (!position) {
15542
+ return 0;
15543
+ }
15544
+ const positionQty = position.position_qty;
15545
+ if (positionQty > 0) {
15546
+ if (side === types.OrderSide.BUY) {
15547
+ return 0;
15548
+ } else {
15549
+ return Math.abs(positionQty);
15550
+ }
15551
+ }
15552
+ if (positionQty < 0) {
15553
+ if (side === types.OrderSide.BUY) {
15554
+ return Math.abs(positionQty);
15555
+ } else {
15556
+ return 0;
15557
+ }
15558
+ }
15559
+ return 0;
15560
+ }, [position, side]);
15561
+ const validate = React.useCallback(
15562
+ async (data) => {
15563
+ const creator = getOrderCreator(data);
15564
+ const errors2 = await creator.validate(data, {
15565
+ symbol: symbolsInfo[symbol](),
15566
+ maxQty,
15567
+ markPrice: markPrices[symbol]
15568
+ });
15569
+ return errors2;
15570
+ },
15571
+ [markPrices, maxQty, symbol, symbolsInfo]
15572
+ );
15573
+ React.useEffect(() => {
15574
+ validate(closeOrderData).then((errors2) => {
15575
+ setErrors(errors2);
15576
+ });
15577
+ }, [validate, closeOrderData]);
15578
+ const submit = React.useCallback(async () => {
15579
+ const errors2 = await validate(closeOrderData);
15580
+ if (Object.keys(errors2).length > 0) {
15581
+ throw errors2;
15582
+ }
15583
+ return doCreateOrder(closeOrderData).then((res) => {
15584
+ if (res.success) {
15585
+ return res;
15586
+ }
15587
+ throw res;
15588
+ }).catch((err) => {
15589
+ throw err;
15590
+ });
15591
+ }, [validate, doCreateOrder, closeOrderData]);
15592
+ return {
15593
+ submit,
15594
+ isMutating,
15595
+ side,
15596
+ closeOrderData,
15597
+ errors,
15598
+ calculate
15599
+ };
15600
+ };
14781
15601
 
15602
+ exports.swr = useSWR__namespace;
14782
15603
  Object.defineProperty(exports, "unstable_serialize", {
14783
15604
  enumerable: true,
14784
15605
  get: function () { return useSWR.unstable_serialize; }
14785
15606
  });
14786
15607
  Object.defineProperty(exports, "useSWR", {
14787
15608
  enumerable: true,
14788
- get: function () { return useSWR__default.default; }
15609
+ get: function () { return useSWR__namespace.default; }
14789
15610
  });
14790
15611
  Object.defineProperty(exports, "useSWRConfig", {
14791
15612
  enumerable: true,
@@ -14799,6 +15620,7 @@ exports.AssetHistoryStatusEnum = AssetHistoryStatusEnum;
14799
15620
  exports.DefaultLayoutConfig = DefaultLayoutConfig;
14800
15621
  exports.DistributionId = DistributionId;
14801
15622
  exports.ENVType = ENVType2;
15623
+ exports.EpochStatus = EpochStatus;
14802
15624
  exports.ExtendedConfigStore = ExtendedConfigStore;
14803
15625
  exports.MaintenanceStatus = MaintenanceStatus;
14804
15626
  exports.MarketsStorageKey = MarketsStorageKey;
@@ -14813,6 +15635,7 @@ exports.WalletConnectorContext = WalletConnectorContext;
14813
15635
  exports.WsNetworkStatus = WsNetworkStatus;
14814
15636
  exports.checkNotional = checkNotional;
14815
15637
  exports.cleanStringStyle = cleanStringStyle;
15638
+ exports.fetcher = fetcher;
14816
15639
  exports.getMinNotional = getMinNotional;
14817
15640
  exports.parseJSON = parseJSON;
14818
15641
  exports.useAccount = useAccount;
@@ -14840,11 +15663,13 @@ exports.useFundingFeeHistory = useFundingFeeHistory;
14840
15663
  exports.useFundingRate = useFundingRate;
14841
15664
  exports.useFundingRateHistory = useFundingRateHistory;
14842
15665
  exports.useFundingRates = useFundingRates;
15666
+ exports.useFundingRatesStore = useFundingRatesStore;
14843
15667
  exports.useGetClaimed = useGetClaimed;
14844
15668
  exports.useGetEnv = useGetEnv;
14845
15669
  exports.useGetReferralCode = useGetReferralCode;
14846
15670
  exports.useHoldingStream = useHoldingStream;
14847
15671
  exports.useIndexPrice = useIndexPrice;
15672
+ exports.useIndexPricesStream = useIndexPricesStream;
14848
15673
  exports.useInfiniteQuery = useInfiniteQuery;
14849
15674
  exports.useKeyStore = useKeyStore;
14850
15675
  exports.useLazyQuery = useLazyQuery;
@@ -14871,6 +15696,7 @@ exports.useOrderStore = useOrderStore2;
14871
15696
  exports.useOrderStream = useOrderStream;
14872
15697
  exports.useOrderbookStream = useOrderbookStream;
14873
15698
  exports.usePositionActions = usePositionActions;
15699
+ exports.usePositionClose = usePositionClose;
14874
15700
  exports.usePositionStream = usePositionStream;
14875
15701
  exports.usePoster = usePoster;
14876
15702
  exports.usePreLoadData = usePreLoadData;
@@ -14890,13 +15716,21 @@ exports.useSimpleDI = useSimpleDI;
14890
15716
  exports.useStatisticsDaily = useStatisticsDaily;
14891
15717
  exports.useStorageChain = useStorageChain;
14892
15718
  exports.useStorageLedgerAddress = useStorageLedgerAddress;
15719
+ exports.useSubAccountDataObserver = useSubAccountDataObserver;
15720
+ exports.useSubAccountMutation = useSubAccountMutation;
15721
+ exports.useSubAccountQuery = useSubAccountQuery;
15722
+ exports.useSubAccountWS = useSubAccountWS;
14893
15723
  exports.useSymbolLeverage = useSymbolLeverage;
14894
15724
  exports.useSymbolPriceRange = useSymbolPriceRange;
14895
15725
  exports.useSymbolsInfo = useSymbolsInfo;
15726
+ exports.useSymbolsInfoStore = useSymbolsInfoStore;
14896
15727
  exports.useTPSLOrder = useTPSLOrder;
14897
15728
  exports.useTickerStream = useTickerStream;
14898
15729
  exports.useTrack = useTrack;
14899
15730
  exports.useTrackingInstance = useTrackingInstance;
15731
+ exports.useTradingRewardsStatus = useTradingRewardsStatus;
15732
+ exports.useTransfer = useTransfer;
15733
+ exports.useTransferHistory = useTransferHistory;
14900
15734
  exports.useWS = useWS;
14901
15735
  exports.useWalletConnector = useWalletConnector;
14902
15736
  exports.useWalletRewardsHistory = useWalletRewardsHistory;