@orderly.network/hooks 0.0.91 → 0.0.92

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
@@ -6,7 +6,7 @@ import useSWRMutation from 'swr/mutation';
6
6
  import useConstant from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
8
  import { SimpleDI, Account, EventEmitter, utils } from '@orderly.network/core';
9
- import { AccountStatusEnum, OrderSide, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, WS_WalletStatusEnum, OrderType } from '@orderly.network/types';
9
+ import { AccountStatusEnum, OrderStatus, OrderSide, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, WS_WalletStatusEnum, OrderType } from '@orderly.network/types';
10
10
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
11
11
  import useSWRSubscription from 'swr/subscription';
12
12
  import { pathOr, propOr, compose, head, prop, mergeDeepRight, pick } from 'ramda';
@@ -156,7 +156,7 @@ var useMutation = (url, method = "POST", options) => {
156
156
  };
157
157
  var signatureMiddleware = (useSWRNext) => {
158
158
  const { apiBaseUrl } = useContext(OrderlyContext);
159
- return (key, fetcher4, config) => {
159
+ return (key, fetcher3, config) => {
160
160
  try {
161
161
  const extendedFetcher = async (args) => {
162
162
  let url = Array.isArray(args) ? args[0] : args;
@@ -168,7 +168,7 @@ var signatureMiddleware = (useSWRNext) => {
168
168
  url
169
169
  };
170
170
  const signature = await signer.sign(payload);
171
- return fetcher4(fullUrl, {
171
+ return fetcher3(fullUrl, {
172
172
  headers: {
173
173
  ...signature,
174
174
  "orderly-account-id": account5.accountId
@@ -684,40 +684,41 @@ var reduceOrderbook = (depth, level, data) => {
684
684
  bids: bids.length < level ? bids.concat(paddingFn(level - bids.length)) : bids
685
685
  };
686
686
  };
687
- var mergeItems = (data, update) => {
688
- if (data.length === 0)
689
- return update;
690
- data = data.filter(([price]) => !isNaN(price));
691
- while (update.length > 0) {
692
- const item = update.shift();
693
- if (item) {
694
- const [price, quantity] = item;
695
- const index = data.findIndex(([p], index2) => p === price);
696
- if (index === -1) {
697
- if (quantity === 0)
698
- continue;
699
- data.push(item);
700
- } else {
701
- if (quantity === 0) {
702
- data.splice(index, 1);
703
- } else {
704
- data[index] = item;
687
+ var mergeOrderbook = (data, update) => {
688
+ const asks = [...data.asks];
689
+ const bids = [...data.bids];
690
+ update.asks.forEach((element) => {
691
+ for (let index = 0; index < asks.length; index++) {
692
+ if (element[1] === 0) {
693
+ if (element[0] === asks[index][0]) {
694
+ asks.splice(index, 1);
695
+ break;
705
696
  }
697
+ } else if (element[0] === asks[index][0]) {
698
+ asks[index] = element;
699
+ break;
700
+ } else if (element[0] < asks[index][0]) {
701
+ asks.splice(index, 0, element);
702
+ break;
706
703
  }
707
704
  }
708
- }
709
- return data;
710
- };
711
- var mergeOrderbook = (data, update) => {
712
- const asks = mergeItems(data.asks, update.asks).sort(asksSortFn);
713
- const bids = mergeItems(data.bids, update.bids).sort(bidsSortFn);
714
- if (asks.length > 0) {
715
- const firstPrice = asks[0][0];
716
- const index = bids.findIndex((item) => item[0] < firstPrice);
717
- if (index > 0) {
718
- bids.splice(0, index + 1);
705
+ });
706
+ update.bids.forEach((element) => {
707
+ for (let index = 0; index < bids.length; index++) {
708
+ if (element[1] === 0) {
709
+ if (element[0] === bids[index][0]) {
710
+ bids.splice(index, 1);
711
+ break;
712
+ }
713
+ } else if (element[0] === bids[index][0]) {
714
+ bids[index] = element;
715
+ break;
716
+ } else if (element[0] > bids[index][0]) {
717
+ bids.splice(index, 0, element);
718
+ break;
719
+ }
719
720
  }
720
- }
721
+ });
721
722
  return {
722
723
  asks,
723
724
  bids
@@ -761,9 +762,14 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
761
762
  if (ignore)
762
763
  return;
763
764
  if (!!message) {
764
- const reduceOrderbookData = reduceOrderbook(depth, level, message);
765
- setRequestData(reduceOrderbookData);
766
- setData(reduceOrderbookData);
765
+ let bids = message.bids.sort(bidsSortFn);
766
+ bids = bids.filter((item) => !isNaN(item[0]));
767
+ bids = bids.filter((item) => item[1] > 0);
768
+ let asks = message.asks.sort(asksSortFn);
769
+ asks = asks.filter((item) => !isNaN(item[0]));
770
+ asks = asks.filter((item) => item[1] > 0);
771
+ setRequestData({ bids, asks });
772
+ setData({ bids, asks });
767
773
  }
768
774
  setIsLoading(false);
769
775
  }
@@ -779,6 +785,7 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
779
785
  useEffect(() => {
780
786
  if (!requestData)
781
787
  return;
788
+ let ignore = false;
782
789
  const subscription = ws.subscribe(
783
790
  {
784
791
  event: "subscribe",
@@ -786,15 +793,17 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
786
793
  },
787
794
  {
788
795
  onMessage: (message) => {
796
+ if (ignore)
797
+ return;
789
798
  setData((data2) => {
790
799
  const mergedData = !message.asks && !message.bids ? data2 : mergeOrderbook(data2, message);
791
- const reducedData = reduceOrderbook(depth, level, mergedData);
792
- return reducedData;
800
+ return mergedData;
793
801
  });
794
802
  }
795
803
  }
796
804
  );
797
805
  return () => {
806
+ ignore = true;
798
807
  subscription?.();
799
808
  };
800
809
  }, [symbol, requestData]);
@@ -820,10 +829,11 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
820
829
  useEffect(() => {
821
830
  prevMiddlePrice.current = middlePrice;
822
831
  }, [middlePrice]);
832
+ const reducedData = reduceOrderbook(depth, level, data);
823
833
  return [
824
834
  {
825
- asks: data.asks.slice(-level),
826
- bids: data.bids.slice(0, level),
835
+ asks: reducedData.asks.slice(-level),
836
+ bids: reducedData.bids.slice(0, level),
827
837
  markPrice,
828
838
  middlePrice: [prevMiddlePrice.current, middlePrice]
829
839
  },
@@ -1254,6 +1264,197 @@ var useHoldingStream = () => {
1254
1264
  isLoading
1255
1265
  };
1256
1266
  };
1267
+ var usePrivateInfiniteQuery = (getKey, options) => {
1268
+ const { formatter, ...restOptions } = options || {};
1269
+ const account5 = useAccount();
1270
+ const middleware = Array.isArray(restOptions?.use) ? restOptions?.use ?? [] : [];
1271
+ const result = useSWRInfinite(
1272
+ (pageIndex, previousPageData) => account5.state.status >= AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1273
+ (url, init) => get(url, init, formatter),
1274
+ {
1275
+ ...restOptions,
1276
+ use: [signatureMiddleware, ...middleware]
1277
+ }
1278
+ );
1279
+ return result;
1280
+ };
1281
+ var useOrderStream = ({
1282
+ status,
1283
+ symbol,
1284
+ side,
1285
+ size = 100
1286
+ } = {}) => {
1287
+ const ws = useWS();
1288
+ const { data: markPrices = {} } = useMarkPricesStream();
1289
+ const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1290
+ const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1291
+ const ordersResponse = usePrivateInfiniteQuery(
1292
+ (pageIndex, previousPageData) => {
1293
+ if (previousPageData && !previousPageData.length)
1294
+ return null;
1295
+ const search = new URLSearchParams([
1296
+ ["size", size.toString()],
1297
+ ["page", `${pageIndex + 1}`]
1298
+ ]);
1299
+ if (status) {
1300
+ search.set(`status`, status);
1301
+ }
1302
+ if (symbol) {
1303
+ search.set(`symbol`, symbol);
1304
+ }
1305
+ if (side) {
1306
+ search.set(`side`, side);
1307
+ }
1308
+ return `/v1/orders?${search.toString()}`;
1309
+ },
1310
+ {
1311
+ initialSize: 1,
1312
+ onError: (err) => {
1313
+ console.error("fetch failed::::", err);
1314
+ },
1315
+ formatter: (data) => data
1316
+ }
1317
+ );
1318
+ const orders = useMemo(() => {
1319
+ if (!ordersResponse.data) {
1320
+ return null;
1321
+ }
1322
+ return ordersResponse.data?.map((item) => item.rows)?.flat().map((item) => {
1323
+ return {
1324
+ ...item,
1325
+ mark_price: markPrices[item.symbol] ?? 0
1326
+ };
1327
+ });
1328
+ }, [ordersResponse.data, markPrices]);
1329
+ const total = useMemo(() => {
1330
+ return ordersResponse.data?.[0]?.meta?.total || 0;
1331
+ }, [ordersResponse.data]);
1332
+ useEffect(() => {
1333
+ const unsubscribe = ws.privateSubscribe(
1334
+ {
1335
+ id: "executionreport_orders",
1336
+ event: "subscribe",
1337
+ topic: "executionreport",
1338
+ ts: Date.now()
1339
+ },
1340
+ {
1341
+ onMessage: (data) => {
1342
+ const { status: status2, orderId, timestamp } = data;
1343
+ ordersResponse.mutate((prevData) => {
1344
+ const newOrder = {
1345
+ order_id: data.orderId,
1346
+ symbol: data.symbol,
1347
+ created_time: data.timestamp,
1348
+ quantity: data.quantity,
1349
+ side: data.side,
1350
+ executed: data.totalExecutedQuantity,
1351
+ price: data.price
1352
+ };
1353
+ const dataList = prevData?.map((item) => item.rows)?.flat() || [];
1354
+ if (status2 === OrderStatus.NEW) {
1355
+ if (!prevData) {
1356
+ return {
1357
+ meta: {
1358
+ total: 1,
1359
+ records_per_page: size,
1360
+ current_page: 1
1361
+ },
1362
+ rows: [newOrder]
1363
+ };
1364
+ }
1365
+ const total2 = (prevData?.[0]?.meta?.total || 0) + 1;
1366
+ const isNew = !dataList.find((item) => item.order_id === orderId);
1367
+ if (isNew) {
1368
+ const list = [newOrder, ...dataList];
1369
+ return rePageData(list, total2, size);
1370
+ }
1371
+ return prevData;
1372
+ }
1373
+ if (status2 === OrderStatus.CANCELLED || status2 === OrderStatus.FILLED) {
1374
+ const total2 = (prevData?.[0]?.meta?.total || 0) - 1;
1375
+ const list = dataList.filter(
1376
+ (order2) => order2.order_id !== orderId
1377
+ );
1378
+ return rePageData(list, total2, size);
1379
+ }
1380
+ if (status2 === OrderStatus.PARTIAL_FILLED) {
1381
+ return editPageData(dataList, newOrder);
1382
+ }
1383
+ if (status2 === OrderStatus.REPLACED) {
1384
+ return editPageData(dataList, newOrder);
1385
+ }
1386
+ return prevData;
1387
+ });
1388
+ }
1389
+ }
1390
+ );
1391
+ return () => unsubscribe();
1392
+ }, []);
1393
+ const cancelAllOrders = useCallback(() => {
1394
+ }, [ordersResponse.data]);
1395
+ const updateOrder = useCallback((orderId, order2) => {
1396
+ return doUpdateOrder({ ...order2, order_id: orderId });
1397
+ }, []);
1398
+ const cancelOrder = useCallback((orderId, symbol2) => {
1399
+ return doCancelOrder(null, {
1400
+ order_id: orderId,
1401
+ symbol: symbol2
1402
+ }).then((res) => {
1403
+ if (res.success) ; else {
1404
+ throw new Error(res.message);
1405
+ }
1406
+ });
1407
+ }, []);
1408
+ const loadMore = () => {
1409
+ ordersResponse.setSize(ordersResponse.size + 1);
1410
+ };
1411
+ return [
1412
+ orders,
1413
+ {
1414
+ total,
1415
+ isLoading: ordersResponse.isLoading,
1416
+ loadMore,
1417
+ cancelAllOrders,
1418
+ updateOrder,
1419
+ cancelOrder
1420
+ }
1421
+ ];
1422
+ };
1423
+ function rePageData(list, total, pageSize) {
1424
+ const newData = [];
1425
+ let rows = [];
1426
+ let current_page = 0;
1427
+ for (let i = 0; i < list.length; i++) {
1428
+ rows.push(list[i]);
1429
+ if ((i + 1) % pageSize === 0 || i === list.length - 1) {
1430
+ newData.push({
1431
+ meta: {
1432
+ records_per_page: pageSize,
1433
+ total,
1434
+ current_page: current_page + 1
1435
+ },
1436
+ rows: [...rows]
1437
+ });
1438
+ rows = [];
1439
+ }
1440
+ }
1441
+ console.log("rePageData", list, total, newData);
1442
+ return newData;
1443
+ }
1444
+ function editPageData(list, newOrder) {
1445
+ const newData = list.map((item) => {
1446
+ return {
1447
+ ...item,
1448
+ rows: item.rows.map((row) => {
1449
+ if (row.order_id === newOrder.order_id) {
1450
+ return { ...row, newOrder };
1451
+ }
1452
+ return row;
1453
+ })
1454
+ };
1455
+ });
1456
+ return newData;
1457
+ }
1257
1458
 
1258
1459
  // src/orderly/useCollateral.ts
1259
1460
  var positionsPath = pathOr([], [0, "rows"]);
@@ -1261,9 +1462,7 @@ pathOr(0, [0, "totalCollateral"]);
1261
1462
  var useCollateral = (options = { dp: 6 }) => {
1262
1463
  const { dp } = options;
1263
1464
  const positions2 = usePositionStream();
1264
- const { data: orders } = usePrivateQuery(
1265
- `/v1/orders?status=NEW`
1266
- );
1465
+ const [orders] = useOrderStream({ status: OrderStatus.NEW });
1267
1466
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1268
1467
  const symbolInfo = useSymbolsInfo();
1269
1468
  const { data: markPrices } = useMarkPricesStream();
@@ -1310,9 +1509,7 @@ var useCollateral = (options = { dp: 6 }) => {
1310
1509
  var positionsPath2 = pathOr([], [0, "rows"]);
1311
1510
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1312
1511
  const positionsData = usePositionStream();
1313
- const { data: orders } = usePrivateQuery(
1314
- `/v1/orders?status=NEW`
1315
- );
1512
+ const [orders] = useOrderStream({ status: OrderStatus.NEW });
1316
1513
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1317
1514
  const symbolInfo = useSymbolsInfo();
1318
1515
  const { totalCollateral } = useCollateral();
@@ -1801,119 +1998,6 @@ var useFundingRate = (symbol) => {
1801
1998
  countDown
1802
1999
  };
1803
2000
  };
1804
- var fetcher3 = (url, init) => get(url, init);
1805
- var usePrivateInfiniteQuery = (getKey, options) => {
1806
- const account5 = useAccount();
1807
- const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
1808
- const result = useSWRInfinite(
1809
- (pageIndex, previousPageData) => account5.state.status >= AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1810
- fetcher3,
1811
- {
1812
- ...options,
1813
- use: [signatureMiddleware, ...middleware]
1814
- }
1815
- );
1816
- return result;
1817
- };
1818
- var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1819
- OrderStatus2["FILLED"] = "FILLED";
1820
- OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1821
- OrderStatus2["CANCELED"] = "CANCELED";
1822
- OrderStatus2["NEW"] = "NEW";
1823
- OrderStatus2["COMPLETED"] = "COMPLETED";
1824
- OrderStatus2["INCOMPLETE"] = "INCOMPLETE";
1825
- return OrderStatus2;
1826
- })(OrderStatus || {});
1827
- var useOrderStream = ({
1828
- status,
1829
- symbol,
1830
- side,
1831
- size = 10
1832
- } = {}) => {
1833
- const ee = useEventEmitter();
1834
- const { data: markPrices = {} } = useMarkPricesStream();
1835
- const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1836
- const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1837
- const ordersResponse = usePrivateInfiniteQuery(
1838
- (pageIndex, previousPageData) => {
1839
- if (previousPageData && !previousPageData.length)
1840
- return null;
1841
- const search = new URLSearchParams([
1842
- ["size", size.toString()],
1843
- ["page", `${pageIndex + 1}`]
1844
- // [`status`, status],
1845
- ]);
1846
- if (status) {
1847
- search.set(`status`, status);
1848
- }
1849
- if (symbol) {
1850
- search.set(`symbol`, symbol);
1851
- }
1852
- if (side) {
1853
- search.set(`side`, side);
1854
- }
1855
- return `/v1/orders?${search.toString()}`;
1856
- },
1857
- {
1858
- initialSize: 1,
1859
- onError: (err) => {
1860
- console.error("fetch failed::::", err);
1861
- }
1862
- }
1863
- );
1864
- const orders = useMemo(() => {
1865
- if (!ordersResponse.data) {
1866
- return null;
1867
- }
1868
- return ordersResponse.data?.flat().map((item) => {
1869
- return {
1870
- ...item,
1871
- mark_price: markPrices[item.symbol] ?? 0
1872
- };
1873
- });
1874
- }, [ordersResponse.data, markPrices]);
1875
- useEffect(() => {
1876
- const handler = () => {
1877
- ordersResponse.mutate();
1878
- };
1879
- ee.on("orders:changed", handler);
1880
- return () => {
1881
- ee.off("orders:changed", handler);
1882
- };
1883
- }, []);
1884
- const cancelAllOrders = useCallback(() => {
1885
- }, [ordersResponse.data]);
1886
- const updateOrder = useCallback((orderId, order2) => {
1887
- return doUpdateOrder({ ...order2, order_id: orderId });
1888
- }, []);
1889
- const cancelOrder = useCallback((orderId, symbol2) => {
1890
- return doCancelOrder(null, {
1891
- order_id: orderId,
1892
- symbol: symbol2
1893
- }).then((res) => {
1894
- if (res.success) {
1895
- return ordersResponse.mutate().then(() => {
1896
- return res;
1897
- });
1898
- } else {
1899
- throw new Error(res.message);
1900
- }
1901
- });
1902
- }, []);
1903
- const loadMore = () => {
1904
- ordersResponse.setSize(ordersResponse.size + 1);
1905
- };
1906
- return [
1907
- orders,
1908
- {
1909
- isLoading: ordersResponse.isLoading,
1910
- loadMore,
1911
- cancelAllOrders,
1912
- updateOrder,
1913
- cancelOrder
1914
- }
1915
- ];
1916
- };
1917
2001
  var useMarketTradeStream = (symbol, options = {}) => {
1918
2002
  if (!symbol) {
1919
2003
  throw new Error("useTradeStream: symbol is required");
@@ -3459,16 +3543,7 @@ var useBalance = () => {
3459
3543
  var usePrivateDataObserver = () => {
3460
3544
  const ws = useWS();
3461
3545
  const { mutate: mutate2 } = useSWRConfig();
3462
- const ee = useEventEmitter();
3463
3546
  const { state } = useAccount();
3464
- useEffect(() => {
3465
- const unsubscribe = ws.privateSubscribe("executionreport", {
3466
- onMessage: (data) => {
3467
- ee.emit("orders:changed");
3468
- }
3469
- });
3470
- return () => unsubscribe?.();
3471
- }, [state.accountId]);
3472
3547
  useEffect(() => {
3473
3548
  if (!state.accountId)
3474
3549
  return;
@@ -3518,24 +3593,6 @@ var usePrivateDataObserver = () => {
3518
3593
  };
3519
3594
  }, [state.accountId]);
3520
3595
  };
3521
- var useExecutionReport = (options) => {
3522
- const ws = useWS();
3523
- const { data } = useSWRSubscription("executionreport", (_, { next }) => {
3524
- const unsubscribe = ws.privateSubscribe({
3525
- id: "executionreport",
3526
- event: "subscribe",
3527
- topic: "executionreport",
3528
- ts: Date.now()
3529
- }, {
3530
- onMessage: (data2) => {
3531
- options?.onMessage?.(data2);
3532
- next(data2);
3533
- }
3534
- });
3535
- return () => unsubscribe();
3536
- });
3537
- return data;
3538
- };
3539
3596
 
3540
3597
  // src/apis/index.ts
3541
3598
  var apis_exports = {};
@@ -4165,6 +4222,6 @@ var useSwap = () => {
4165
4222
  };
4166
4223
  };
4167
4224
 
4168
- export { DataSourceProvider, OrderStatus, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOpenInterest, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4225
+ export { DataSourceProvider, OrderlyContext, OrderlyProvider, apis_exports as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useFetures, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOpenInterest, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4169
4226
  //# sourceMappingURL=out.js.map
4170
4227
  //# sourceMappingURL=index.mjs.map