@orderly.network/hooks 0.0.91 → 0.0.93

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
@@ -709,15 +709,10 @@ var mergeItems = (data, update) => {
709
709
  return data;
710
710
  };
711
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);
719
- }
720
- }
712
+ let asks = [...data.asks];
713
+ let bids = [...data.bids];
714
+ asks = mergeItems(asks, update.asks).sort(asksSortFn);
715
+ bids = mergeItems(bids, update.bids).sort(bidsSortFn);
721
716
  return {
722
717
  asks,
723
718
  bids
@@ -761,9 +756,12 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
761
756
  if (ignore)
762
757
  return;
763
758
  if (!!message) {
764
- const reduceOrderbookData = reduceOrderbook(depth, level, message);
765
- setRequestData(reduceOrderbookData);
766
- setData(reduceOrderbookData);
759
+ let bids = [...message.bids.sort(bidsSortFn)];
760
+ bids = bids.filter((item) => !isNaN(item[0]) && item[1] > 0);
761
+ let asks = [...message.asks.sort(asksSortFn)];
762
+ asks = asks.filter((item) => !isNaN(item[0]) && item[1] > 0);
763
+ setRequestData({ bids, asks });
764
+ setData({ bids: [...bids], asks: [...asks] });
767
765
  }
768
766
  setIsLoading(false);
769
767
  }
@@ -779,6 +777,7 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
779
777
  useEffect(() => {
780
778
  if (!requestData)
781
779
  return;
780
+ let ignore = false;
782
781
  const subscription = ws.subscribe(
783
782
  {
784
783
  event: "subscribe",
@@ -786,15 +785,17 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
786
785
  },
787
786
  {
788
787
  onMessage: (message) => {
788
+ if (ignore)
789
+ return;
789
790
  setData((data2) => {
790
791
  const mergedData = !message.asks && !message.bids ? data2 : mergeOrderbook(data2, message);
791
- const reducedData = reduceOrderbook(depth, level, mergedData);
792
- return reducedData;
792
+ return mergedData;
793
793
  });
794
794
  }
795
795
  }
796
796
  );
797
797
  return () => {
798
+ ignore = true;
798
799
  subscription?.();
799
800
  };
800
801
  }, [symbol, requestData]);
@@ -820,10 +821,11 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
820
821
  useEffect(() => {
821
822
  prevMiddlePrice.current = middlePrice;
822
823
  }, [middlePrice]);
824
+ const reducedData = reduceOrderbook(depth, level, data);
823
825
  return [
824
826
  {
825
- asks: data.asks.slice(-level),
826
- bids: data.bids.slice(0, level),
827
+ asks: reducedData.asks.slice(-level),
828
+ bids: reducedData.bids.slice(0, level),
827
829
  markPrice,
828
830
  middlePrice: [prevMiddlePrice.current, middlePrice]
829
831
  },
@@ -1254,6 +1256,197 @@ var useHoldingStream = () => {
1254
1256
  isLoading
1255
1257
  };
1256
1258
  };
1259
+ var usePrivateInfiniteQuery = (getKey, options) => {
1260
+ const { formatter, ...restOptions } = options || {};
1261
+ const account5 = useAccount();
1262
+ const middleware = Array.isArray(restOptions?.use) ? restOptions?.use ?? [] : [];
1263
+ const result = useSWRInfinite(
1264
+ (pageIndex, previousPageData) => account5.state.status >= AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1265
+ (url, init) => get(url, init, formatter),
1266
+ {
1267
+ ...restOptions,
1268
+ use: [signatureMiddleware, ...middleware]
1269
+ }
1270
+ );
1271
+ return result;
1272
+ };
1273
+ var useOrderStream = ({
1274
+ status,
1275
+ symbol,
1276
+ side,
1277
+ size = 100
1278
+ } = {}) => {
1279
+ const ws = useWS();
1280
+ const { data: markPrices = {} } = useMarkPricesStream();
1281
+ const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1282
+ const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1283
+ const ordersResponse = usePrivateInfiniteQuery(
1284
+ (pageIndex, previousPageData) => {
1285
+ if (previousPageData && !previousPageData.length)
1286
+ return null;
1287
+ const search = new URLSearchParams([
1288
+ ["size", size.toString()],
1289
+ ["page", `${pageIndex + 1}`]
1290
+ ]);
1291
+ if (status) {
1292
+ search.set(`status`, status);
1293
+ }
1294
+ if (symbol) {
1295
+ search.set(`symbol`, symbol);
1296
+ }
1297
+ if (side) {
1298
+ search.set(`side`, side);
1299
+ }
1300
+ return `/v1/orders?${search.toString()}`;
1301
+ },
1302
+ {
1303
+ initialSize: 1,
1304
+ onError: (err) => {
1305
+ console.error("fetch failed::::", err);
1306
+ },
1307
+ formatter: (data) => data
1308
+ }
1309
+ );
1310
+ const orders = useMemo(() => {
1311
+ if (!ordersResponse.data) {
1312
+ return null;
1313
+ }
1314
+ return ordersResponse.data?.map((item) => item.rows)?.flat().map((item) => {
1315
+ return {
1316
+ ...item,
1317
+ mark_price: markPrices[item.symbol] ?? 0
1318
+ };
1319
+ });
1320
+ }, [ordersResponse.data, markPrices]);
1321
+ const total = useMemo(() => {
1322
+ return ordersResponse.data?.[0]?.meta?.total || 0;
1323
+ }, [ordersResponse.data]);
1324
+ useEffect(() => {
1325
+ const unsubscribe = ws.privateSubscribe(
1326
+ {
1327
+ id: "executionreport_orders",
1328
+ event: "subscribe",
1329
+ topic: "executionreport",
1330
+ ts: Date.now()
1331
+ },
1332
+ {
1333
+ onMessage: (data) => {
1334
+ const { status: status2, orderId, timestamp } = data;
1335
+ ordersResponse.mutate((prevData) => {
1336
+ const newOrder = {
1337
+ order_id: data.orderId,
1338
+ symbol: data.symbol,
1339
+ created_time: data.timestamp,
1340
+ quantity: data.quantity,
1341
+ side: data.side,
1342
+ executed: data.totalExecutedQuantity,
1343
+ price: data.price
1344
+ };
1345
+ const dataList = prevData?.map((item) => item.rows)?.flat() || [];
1346
+ if (status2 === OrderStatus.NEW) {
1347
+ if (!prevData) {
1348
+ return {
1349
+ meta: {
1350
+ total: 1,
1351
+ records_per_page: size,
1352
+ current_page: 1
1353
+ },
1354
+ rows: [newOrder]
1355
+ };
1356
+ }
1357
+ const total2 = (prevData?.[0]?.meta?.total || 0) + 1;
1358
+ const isNew = !dataList.find((item) => item.order_id === orderId);
1359
+ if (isNew) {
1360
+ const list = [newOrder, ...dataList];
1361
+ return rePageData(list, total2, size);
1362
+ }
1363
+ return prevData;
1364
+ }
1365
+ if (status2 === OrderStatus.CANCELLED || status2 === OrderStatus.FILLED) {
1366
+ const total2 = (prevData?.[0]?.meta?.total || 0) - 1;
1367
+ const list = dataList.filter(
1368
+ (order2) => order2.order_id !== orderId
1369
+ );
1370
+ return rePageData(list, total2, size);
1371
+ }
1372
+ if (status2 === OrderStatus.PARTIAL_FILLED) {
1373
+ return editPageData(dataList, newOrder);
1374
+ }
1375
+ if (status2 === OrderStatus.REPLACED) {
1376
+ return editPageData(dataList, newOrder);
1377
+ }
1378
+ return prevData;
1379
+ });
1380
+ }
1381
+ }
1382
+ );
1383
+ return () => unsubscribe();
1384
+ }, []);
1385
+ const cancelAllOrders = useCallback(() => {
1386
+ }, [ordersResponse.data]);
1387
+ const updateOrder = useCallback((orderId, order2) => {
1388
+ return doUpdateOrder({ ...order2, order_id: orderId });
1389
+ }, []);
1390
+ const cancelOrder = useCallback((orderId, symbol2) => {
1391
+ return doCancelOrder(null, {
1392
+ order_id: orderId,
1393
+ symbol: symbol2
1394
+ }).then((res) => {
1395
+ if (res.success) ; else {
1396
+ throw new Error(res.message);
1397
+ }
1398
+ });
1399
+ }, []);
1400
+ const loadMore = () => {
1401
+ ordersResponse.setSize(ordersResponse.size + 1);
1402
+ };
1403
+ return [
1404
+ orders,
1405
+ {
1406
+ total,
1407
+ isLoading: ordersResponse.isLoading,
1408
+ loadMore,
1409
+ cancelAllOrders,
1410
+ updateOrder,
1411
+ cancelOrder
1412
+ }
1413
+ ];
1414
+ };
1415
+ function rePageData(list, total, pageSize) {
1416
+ const newData = [];
1417
+ let rows = [];
1418
+ let current_page = 0;
1419
+ for (let i = 0; i < list.length; i++) {
1420
+ rows.push(list[i]);
1421
+ if ((i + 1) % pageSize === 0 || i === list.length - 1) {
1422
+ newData.push({
1423
+ meta: {
1424
+ records_per_page: pageSize,
1425
+ total,
1426
+ current_page: current_page + 1
1427
+ },
1428
+ rows: [...rows]
1429
+ });
1430
+ rows = [];
1431
+ }
1432
+ }
1433
+ console.log("rePageData", list, total, newData);
1434
+ return newData;
1435
+ }
1436
+ function editPageData(list, newOrder) {
1437
+ const newData = list.map((item) => {
1438
+ return {
1439
+ ...item,
1440
+ rows: item.rows.map((row) => {
1441
+ if (row.order_id === newOrder.order_id) {
1442
+ return { ...row, newOrder };
1443
+ }
1444
+ return row;
1445
+ })
1446
+ };
1447
+ });
1448
+ return newData;
1449
+ }
1257
1450
 
1258
1451
  // src/orderly/useCollateral.ts
1259
1452
  var positionsPath = pathOr([], [0, "rows"]);
@@ -1261,9 +1454,7 @@ pathOr(0, [0, "totalCollateral"]);
1261
1454
  var useCollateral = (options = { dp: 6 }) => {
1262
1455
  const { dp } = options;
1263
1456
  const positions2 = usePositionStream();
1264
- const { data: orders } = usePrivateQuery(
1265
- `/v1/orders?status=NEW`
1266
- );
1457
+ const [orders] = useOrderStream({ status: OrderStatus.NEW });
1267
1458
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1268
1459
  const symbolInfo = useSymbolsInfo();
1269
1460
  const { data: markPrices } = useMarkPricesStream();
@@ -1310,9 +1501,7 @@ var useCollateral = (options = { dp: 6 }) => {
1310
1501
  var positionsPath2 = pathOr([], [0, "rows"]);
1311
1502
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1312
1503
  const positionsData = usePositionStream();
1313
- const { data: orders } = usePrivateQuery(
1314
- `/v1/orders?status=NEW`
1315
- );
1504
+ const [orders] = useOrderStream({ status: OrderStatus.NEW });
1316
1505
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1317
1506
  const symbolInfo = useSymbolsInfo();
1318
1507
  const { totalCollateral } = useCollateral();
@@ -1801,119 +1990,6 @@ var useFundingRate = (symbol) => {
1801
1990
  countDown
1802
1991
  };
1803
1992
  };
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
1993
  var useMarketTradeStream = (symbol, options = {}) => {
1918
1994
  if (!symbol) {
1919
1995
  throw new Error("useTradeStream: symbol is required");
@@ -3459,16 +3535,7 @@ var useBalance = () => {
3459
3535
  var usePrivateDataObserver = () => {
3460
3536
  const ws = useWS();
3461
3537
  const { mutate: mutate2 } = useSWRConfig();
3462
- const ee = useEventEmitter();
3463
3538
  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
3539
  useEffect(() => {
3473
3540
  if (!state.accountId)
3474
3541
  return;
@@ -3518,24 +3585,6 @@ var usePrivateDataObserver = () => {
3518
3585
  };
3519
3586
  }, [state.accountId]);
3520
3587
  };
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
3588
 
3540
3589
  // src/apis/index.ts
3541
3590
  var apis_exports = {};
@@ -4165,6 +4214,6 @@ var useSwap = () => {
4165
4214
  };
4166
4215
  };
4167
4216
 
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 };
4217
+ 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
4218
  //# sourceMappingURL=out.js.map
4170
4219
  //# sourceMappingURL=index.mjs.map