@orderly.network/hooks 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,19 +1,16 @@
1
1
  import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
2
2
  import useSWR, { useSWRConfig } from 'swr';
3
3
  export { default as useSWR } from 'swr';
4
- import { WS, get, mutate, WebSocketClient } from '@orderly.network/net';
4
+ import { WS, get, mutate } from '@orderly.network/net';
5
5
  import useSWRMutation from 'swr/mutation';
6
6
  import useConstant from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
- import { SimpleDI, Account, getMockSigner } from '@orderly.network/core';
8
+ import { SimpleDI, Account, EventEmitter } from '@orderly.network/core';
9
9
  import { AccountStatusEnum, SystemStateEnum, ExchangeStatusEnum, OrderSide, OrderType } from '@orderly.network/types';
10
- import { BehaviorSubject, merge } from 'rxjs';
11
- import { map } from 'rxjs/operators';
12
- import { useObservable } from 'rxjs-hooks';
13
- export { useEventCallback, useObservable } from 'rxjs-hooks';
14
- import { compose, defaultTo, head, last, pathOr, propOr } from 'ramda';
10
+ import { BehaviorSubject } from 'rxjs';
15
11
  import useSWRSubscription from 'swr/subscription';
16
12
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
13
+ import { pathOr, propOr, compose, head, prop } from 'ramda';
17
14
  import { positions, account, order } from '@orderly.network/futures';
18
15
  import useSWRInfinite from 'swr/infinite';
19
16
 
@@ -25,26 +22,26 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
22
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
26
23
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
27
24
  var __spreadValues = (a, b) => {
28
- for (var prop in b || (b = {}))
29
- if (__hasOwnProp.call(b, prop))
30
- __defNormalProp(a, prop, b[prop]);
25
+ for (var prop2 in b || (b = {}))
26
+ if (__hasOwnProp.call(b, prop2))
27
+ __defNormalProp(a, prop2, b[prop2]);
31
28
  if (__getOwnPropSymbols)
32
- for (var prop of __getOwnPropSymbols(b)) {
33
- if (__propIsEnum.call(b, prop))
34
- __defNormalProp(a, prop, b[prop]);
29
+ for (var prop2 of __getOwnPropSymbols(b)) {
30
+ if (__propIsEnum.call(b, prop2))
31
+ __defNormalProp(a, prop2, b[prop2]);
35
32
  }
36
33
  return a;
37
34
  };
38
35
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
39
36
  var __objRest = (source, exclude) => {
40
37
  var target = {};
41
- for (var prop in source)
42
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
43
- target[prop] = source[prop];
38
+ for (var prop2 in source)
39
+ if (__hasOwnProp.call(source, prop2) && exclude.indexOf(prop2) < 0)
40
+ target[prop2] = source[prop2];
44
41
  if (source != null && __getOwnPropSymbols)
45
- for (var prop of __getOwnPropSymbols(source)) {
46
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
47
- target[prop] = source[prop];
42
+ for (var prop2 of __getOwnPropSymbols(source)) {
43
+ if (exclude.indexOf(prop2) < 0 && __propIsEnum.call(source, prop2))
44
+ target[prop2] = source[prop2];
48
45
  }
49
46
  return target;
50
47
  };
@@ -251,9 +248,9 @@ var useAccount = () => {
251
248
  const connect = useCallback(() => __async(void 0, null, function* () {
252
249
  return onWalletConnect == null ? void 0 : onWalletConnect();
253
250
  }), [account4]);
254
- const disconnect = useCallback(() => __async(void 0, null, function* () {
251
+ const disconnect = () => __async(void 0, null, function* () {
255
252
  return onWalletDisconnect == null ? void 0 : onWalletDisconnect();
256
- }), [account4]);
253
+ });
257
254
  return {
258
255
  // account: state!,
259
256
  account: account4,
@@ -337,21 +334,18 @@ function getAppState() {
337
334
 
338
335
  // src/useAppState.ts
339
336
  var useAppState = () => {
340
- const appState = getAppState();
341
- return useObservable(
342
- () => merge(appState.exchangeState$, appState.systemState$).pipe(
343
- map((data) => {
344
- return {
345
- systemState: SystemStateEnum.Ready,
346
- exchangeState: ExchangeStatusEnum.Normal
347
- };
348
- })
349
- ),
350
- {
351
- systemState: appState.systemState$.value,
352
- exchangeState: appState.exchangeState$.value
337
+ getAppState();
338
+ return {};
339
+ };
340
+ var useEventEmitter = (channel) => {
341
+ return useConstant(() => {
342
+ let ee = SimpleDI.get("EE");
343
+ if (!ee) {
344
+ ee = new EventEmitter();
345
+ SimpleDI.registerByName("EE", ee);
353
346
  }
354
- );
347
+ return ee;
348
+ });
355
349
  };
356
350
  var DataSourceContext = createContext({});
357
351
  var DataSourceProvider = (props) => {
@@ -381,6 +375,11 @@ var useWS = () => {
381
375
  return __spreadProps(__spreadValues({}, result), { timestamp });
382
376
  })
383
377
  });
378
+ account4.on("change:status", (nextState) => {
379
+ if (nextState.status === AccountStatusEnum.EnableTrading && nextState.accountId) {
380
+ websocketClient.openPrivate(nextState.accountId);
381
+ }
382
+ });
384
383
  SimpleDI.registerByName(WS_NAME, websocketClient);
385
384
  }
386
385
  return websocketClient;
@@ -460,8 +459,6 @@ var useMarkPrice = (symbol) => {
460
459
  };
461
460
 
462
461
  // src/orderly/useOrderbookStream.ts
463
- compose(defaultTo(0), head, last, pathOr([], ["asks"]));
464
- pathOr(0, ["bids", 0, 0]);
465
462
  var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN]);
466
463
  var asksSortFn = (a, b) => a[0] - b[0];
467
464
  var bidsSortFn = (a, b) => b[0] - a[0];
@@ -538,6 +535,7 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
538
535
  });
539
536
  const ws = useWS();
540
537
  const ticker = useTickerStream(symbol);
538
+ const eventEmitter = useEventEmitter();
541
539
  useEffect(() => {
542
540
  ws.onceSubscribe(
543
541
  {
@@ -586,6 +584,9 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
586
584
  subscription == null ? void 0 : subscription();
587
585
  };
588
586
  }, [symbol, requestData]);
587
+ const onItemClick = useCallback((item) => {
588
+ eventEmitter.emit("orderbook:item:click", item);
589
+ }, []);
589
590
  const onDepthChange = useCallback((depth2) => {
590
591
  console.log("Orderbook depth has changed:", depth2);
591
592
  }, []);
@@ -603,7 +604,7 @@ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) =>
603
604
  }, [ticker, data]);
604
605
  return [
605
606
  __spreadProps(__spreadValues({}, data), { markPrice, middlePrice }),
606
- { onDepthChange, depth, isLoading }
607
+ { onDepthChange, depth, isLoading, onItemClick }
607
608
  ];
608
609
  };
609
610
 
@@ -715,7 +716,6 @@ function priceInputHandle(inputs) {
715
716
  }
716
717
  const price = new Decimal(value);
717
718
  const priceDP = price.dp();
718
- console.log("priceInputHandle", priceDP, config.quoteDP);
719
719
  if (priceDP > config.quoteDP) {
720
720
  values.order_price = price.toDecimalPlaces(config.quoteDP).toString();
721
721
  }
@@ -866,7 +866,11 @@ var usePositionStream = (symbol, options) => {
866
866
  const symbolInfo = useSymbolsInfo();
867
867
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
868
868
  const fundingRates = useFundingRates();
869
- const { data, error } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({}, options), {
869
+ const { data, error } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({
870
+ // revalidateOnFocus: false,
871
+ // revalidateOnReconnect: false,
872
+ dedupingInterval: 5e3
873
+ }, options), {
870
874
  formatter: (data2) => data2,
871
875
  onError: (err) => {
872
876
  console.log("usePositionStream error", err);
@@ -1125,7 +1129,7 @@ var BaseOrderCreator = class {
1125
1129
  // symbol: data.symbol,
1126
1130
  order_type: data.order_type === OrderType.LIMIT ? !!data.order_type_ext ? data.order_type_ext : data.order_type : data.order_type,
1127
1131
  side: data.side,
1128
- // reduce_only: data.reduce_only,
1132
+ reduce_only: data.reduce_only,
1129
1133
  order_quantity: data.order_quantity
1130
1134
  };
1131
1135
  if (data.visible_quantity === 0) {
@@ -1143,32 +1147,40 @@ var BaseOrderCreator = class {
1143
1147
  message: "quantity is required"
1144
1148
  };
1145
1149
  } else {
1146
- const { base_max, base_min } = configs.symbol;
1150
+ const { base_min, quote_dp, base_dp } = configs.symbol;
1147
1151
  const qty = new Decimal(order_quantity);
1148
1152
  if (qty.lt(base_min)) {
1149
1153
  errors.order_quantity = {
1150
1154
  type: "min",
1151
- message: `quantity must be greater than ${base_min}`
1155
+ message: `quantity must be greater than ${new Decimal(base_min).todp(
1156
+ base_dp
1157
+ )}`
1152
1158
  };
1153
1159
  } else if (qty.gt(maxQty)) {
1154
1160
  errors.order_quantity = {
1155
1161
  type: "max",
1156
- message: `quantity must be less than ${maxQty}`
1162
+ message: `quantity must be less than ${new Decimal(maxQty).todp(
1163
+ base_dp
1164
+ )}`
1157
1165
  };
1158
1166
  }
1159
1167
  }
1160
1168
  if (!!total) {
1161
- const { quote_max, quote_min } = configs.symbol;
1169
+ const { quote_max, quote_min, quote_dp } = configs.symbol;
1162
1170
  const totalNumber = new Decimal(total);
1163
1171
  if (totalNumber.lt(quote_min)) {
1164
1172
  errors.total = {
1165
1173
  type: "min",
1166
- message: `Quantity should be greater or equal than ${quote_min}`
1174
+ message: `Quantity should be greater or equal than ${new Decimal(
1175
+ quote_min
1176
+ ).todp(quote_dp)}`
1167
1177
  };
1168
1178
  } else if (totalNumber.gt(quote_max)) {
1169
1179
  errors.total = {
1170
1180
  type: "max",
1171
- message: `Quantity should be less or equal than ${quote_max}`
1181
+ message: `Quantity should be less or equal than ${new Decimal(
1182
+ quote_max
1183
+ ).todp(quote_dp)}`
1172
1184
  };
1173
1185
  }
1174
1186
  }
@@ -1344,29 +1356,6 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1344
1356
  symbolConfig: symbolInfo[symbol]()
1345
1357
  };
1346
1358
  };
1347
- var WS_NAME2 = "websocketClient";
1348
- var useWebSocketClient = () => {
1349
- const ws = useConstant(() => {
1350
- let websocketClient = SimpleDI.get(WS_NAME2);
1351
- if (!websocketClient) {
1352
- websocketClient = new WebSocketClient({
1353
- accountId: "OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY",
1354
- networkId: "testnet",
1355
- onSigntureRequest: (accountId) => __async(void 0, null, function* () {
1356
- const signer = getMockSigner();
1357
- const timestamp = (/* @__PURE__ */ new Date()).getTime();
1358
- const result = yield signer.signText(timestamp.toString());
1359
- return __spreadProps(__spreadValues({}, result), { timestamp });
1360
- })
1361
- });
1362
- SimpleDI.registerByName(WS_NAME2, websocketClient);
1363
- }
1364
- return websocketClient;
1365
- });
1366
- return ws;
1367
- };
1368
-
1369
- // src/orderly/useFetures.ts
1370
1359
  var useFetures = () => {
1371
1360
  const { data, isLoading, error } = useQuery(
1372
1361
  `/v1/public/futures`,
@@ -1375,14 +1364,8 @@ var useFetures = () => {
1375
1364
  }
1376
1365
  );
1377
1366
  const [sortedData, setSortedData] = useState(data);
1378
- const ws = useWebSocketClient();
1367
+ useWS();
1379
1368
  useEffect(() => {
1380
- const sub = ws.observe(`tickers`).subscribe((value) => {
1381
- console.log("useTickers", value);
1382
- });
1383
- return () => {
1384
- sub.unsubscribe();
1385
- };
1386
1369
  }, []);
1387
1370
  useEffect(() => {
1388
1371
  if (data) {
@@ -1458,6 +1441,16 @@ var useMarketsStream = () => {
1458
1441
  }, [futures, tickers]);
1459
1442
  return { data: value };
1460
1443
  };
1444
+ var useLeverage = () => {
1445
+ const { data, mutate: mutate2 } = usePrivateQuery("/v1/client/info");
1446
+ const [update] = useMutation("/v1/client/leverage");
1447
+ const updateLeverage = useCallback((data2) => {
1448
+ return update(data2).then((res) => {
1449
+ return mutate2();
1450
+ });
1451
+ }, []);
1452
+ return [prop("max_leverage", data), { update: updateLeverage }];
1453
+ };
1461
1454
  var useFundingRate = (symbol) => {
1462
1455
  if (!symbol) {
1463
1456
  throw new Error("useFuturesForSymbol requires a symbol");
@@ -1578,12 +1571,6 @@ var useOrderStream = ({
1578
1571
  }, []);
1579
1572
  return [
1580
1573
  orders,
1581
- // {
1582
- // ...res,
1583
- // data: res.data?.reduce((acc, cur) => {
1584
- // return [...acc, ...cur];
1585
- // }, []),
1586
- // },
1587
1574
  {
1588
1575
  cancelAllOrders,
1589
1576
  updateOrder,
@@ -1592,8 +1579,8 @@ var useOrderStream = ({
1592
1579
  ];
1593
1580
  };
1594
1581
 
1595
- // src/orderly/useTradeStream.ts
1596
- var useTradeStream = (symbol) => {
1582
+ // src/orderly/useMarketTradeStream.ts
1583
+ var useMarketTradeStream = (symbol) => {
1597
1584
  if (!symbol) {
1598
1585
  throw new Error("useTradeStream: symbol is required");
1599
1586
  }
@@ -1602,6 +1589,12 @@ var useTradeStream = (symbol) => {
1602
1589
  );
1603
1590
  return { data, isLoading };
1604
1591
  };
1592
+
1593
+ // src/orderly/useTrades.tsx
1594
+ var useTradeStream = () => {
1595
+ const { data, isLoading } = usePrivateQuery("/v1/trades");
1596
+ return [data, { isLoading }];
1597
+ };
1605
1598
  var useMarginRatio = () => {
1606
1599
  const [{ rows }] = usePositionStream();
1607
1600
  const { data: markPrices } = useMarkPricesStream();
@@ -1662,6 +1655,58 @@ var useChains = (networkId, options) => {
1662
1655
  );
1663
1656
  return [chains, { findByChainId }];
1664
1657
  };
1658
+ var useBalance = () => {
1659
+ const ws = useWS();
1660
+ const { data } = useSWRSubscription("balance", (_, { next }) => {
1661
+ const unsubscribe = ws.privateSubscribe("balance", {
1662
+ onMessage: (data2) => {
1663
+ console.log(data2);
1664
+ }
1665
+ });
1666
+ return () => unsubscribe();
1667
+ });
1668
+ return data;
1669
+ };
1670
+ var usePrivateDataObserver = () => {
1671
+ const ws = useWS();
1672
+ const { mutate: mutate2 } = useSWRConfig();
1673
+ useEffect(() => {
1674
+ console.log("subscribe: executionreport");
1675
+ const unsubscribe = ws.privateSubscribe("executionreport", {
1676
+ onMessage: (data) => {
1677
+ console.info("refresh orders");
1678
+ mutate2("/v1/orders");
1679
+ }
1680
+ });
1681
+ return () => unsubscribe == null ? void 0 : unsubscribe();
1682
+ }, []);
1683
+ useEffect(() => {
1684
+ console.log("subscribe: position");
1685
+ const unsubscribe = ws.privateSubscribe("position", {
1686
+ onMessage: (data) => {
1687
+ const { positions: nextPostions } = data;
1688
+ console.info("refresh positions", nextPostions);
1689
+ mutate2("/v1/positions");
1690
+ }
1691
+ });
1692
+ return () => {
1693
+ console.log("unsubscribe: private subscription position");
1694
+ unsubscribe == null ? void 0 : unsubscribe();
1695
+ };
1696
+ }, []);
1697
+ };
1698
+ var useExecutionReport = () => {
1699
+ const ws = useWS();
1700
+ const { data } = useSWRSubscription("executionreport", (_, { next }) => {
1701
+ const unsubscribe = ws.privateSubscribe("executionreport", {
1702
+ onMessage: (data2) => {
1703
+ console.log(data2);
1704
+ }
1705
+ });
1706
+ return () => unsubscribe();
1707
+ });
1708
+ return data;
1709
+ };
1665
1710
 
1666
1711
  // src/apis/index.ts
1667
1712
  var apis_exports = {};
@@ -1697,6 +1742,6 @@ var useFundingRate2 = (symbol) => {
1697
1742
  return useQuery(`/v1/public/funding_rate`);
1698
1743
  };
1699
1744
 
1700
- export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAppState, useChains, useCollateral, useFetures, useFundingRate, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradeStream, useTradingView, useWS };
1745
+ export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useLeverage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradeStream, useTradingView, useWS };
1701
1746
  //# sourceMappingURL=out.js.map
1702
1747
  //# sourceMappingURL=index.mjs.map