@orderly.network/hooks 1.0.14 → 1.0.15

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.d.mts CHANGED
@@ -9,8 +9,9 @@ import { AccountState, Account, EventEmitter, ConfigKey, ConfigStore, OrderlyKey
9
9
  export { default as useConstant } from 'use-constant';
10
10
  import { WS } from '@orderly.network/net';
11
11
  import * as react from 'react';
12
- import react__default, { PropsWithChildren } from 'react';
12
+ import { PropsWithChildren } from 'react';
13
13
  import { NetworkId, OrderSide, OrderEntity, API, WSMessage, OrderStatus, WS_WalletStatusEnum } from '@orderly.network/types';
14
+ import * as react_jsx_runtime from 'react/jsx-runtime';
14
15
  import * as swr_subscription from 'swr/subscription';
15
16
  import { Decimal } from '@orderly.network/utils';
16
17
  export * from 'use-debounce';
@@ -117,7 +118,7 @@ interface ConfigProviderProps {
117
118
  networkId: NetworkId;
118
119
  enableSwapDeposit?: boolean;
119
120
  }
120
- declare const OrderlyConfigProvider: (props: PropsWithChildren<RequireAtLeastOne<ConfigProviderProps, "brokerId" | "configStore">>) => react__default.JSX.Element | null;
121
+ declare const OrderlyConfigProvider: (props: PropsWithChildren<RequireAtLeastOne<ConfigProviderProps, "brokerId" | "configStore">>) => react_jsx_runtime.JSX.Element | null;
121
122
 
122
123
  type ConnectedChain = {
123
124
  id: string;
@@ -253,6 +254,10 @@ declare const useOrderStream: (params: Params) => readonly [any[] | null, {
253
254
  readonly cancelAllOrders: () => void;
254
255
  readonly updateOrder: (orderId: string, order: OrderEntity) => Promise<any>;
255
256
  readonly cancelOrder: (orderId: string, symbol?: string) => Promise<void>;
257
+ readonly errors: {
258
+ readonly cancelOrder: unknown;
259
+ readonly updateOrder: unknown;
260
+ };
256
261
  }];
257
262
 
258
263
  interface MarketTradeStreamOptions {
package/dist/index.d.ts CHANGED
@@ -9,8 +9,9 @@ import { AccountState, Account, EventEmitter, ConfigKey, ConfigStore, OrderlyKey
9
9
  export { default as useConstant } from 'use-constant';
10
10
  import { WS } from '@orderly.network/net';
11
11
  import * as react from 'react';
12
- import react__default, { PropsWithChildren } from 'react';
12
+ import { PropsWithChildren } from 'react';
13
13
  import { NetworkId, OrderSide, OrderEntity, API, WSMessage, OrderStatus, WS_WalletStatusEnum } from '@orderly.network/types';
14
+ import * as react_jsx_runtime from 'react/jsx-runtime';
14
15
  import * as swr_subscription from 'swr/subscription';
15
16
  import { Decimal } from '@orderly.network/utils';
16
17
  export * from 'use-debounce';
@@ -117,7 +118,7 @@ interface ConfigProviderProps {
117
118
  networkId: NetworkId;
118
119
  enableSwapDeposit?: boolean;
119
120
  }
120
- declare const OrderlyConfigProvider: (props: PropsWithChildren<RequireAtLeastOne<ConfigProviderProps, "brokerId" | "configStore">>) => react__default.JSX.Element | null;
121
+ declare const OrderlyConfigProvider: (props: PropsWithChildren<RequireAtLeastOne<ConfigProviderProps, "brokerId" | "configStore">>) => react_jsx_runtime.JSX.Element | null;
121
122
 
122
123
  type ConnectedChain = {
123
124
  id: string;
@@ -253,6 +254,10 @@ declare const useOrderStream: (params: Params) => readonly [any[] | null, {
253
254
  readonly cancelAllOrders: () => void;
254
255
  readonly updateOrder: (orderId: string, order: OrderEntity) => Promise<any>;
255
256
  readonly cancelOrder: (orderId: string, symbol?: string) => Promise<void>;
257
+ readonly errors: {
258
+ readonly cancelOrder: unknown;
259
+ readonly updateOrder: unknown;
260
+ };
256
261
  }];
257
262
 
258
263
  interface MarketTradeStreamOptions {
package/dist/index.js CHANGED
@@ -8,11 +8,12 @@ var useConstant4 = require('use-constant');
8
8
  var core = require('@orderly.network/core');
9
9
  var types = require('@orderly.network/types');
10
10
  var useSWRInfinite = require('swr/infinite');
11
+ var useDebounce = require('use-debounce');
12
+ var jsxRuntime = require('react/jsx-runtime');
11
13
  var utils = require('@orderly.network/utils');
12
14
  var useSWRSubscription = require('swr/subscription');
13
15
  var ramda = require('ramda');
14
16
  var perp = require('@orderly.network/perp');
15
- var useDebounce = require('use-debounce');
16
17
  var scanClient = require('@layerzerolabs/scan-client');
17
18
 
18
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -183,7 +184,6 @@ var signatureMiddleware = (useSWRNext) => {
183
184
  url
184
185
  };
185
186
  const signature = await signer.sign(payload);
186
- console.log("signature:", fullUrl);
187
187
  return fetcher3(fullUrl, {
188
188
  headers: {
189
189
  ...signature,
@@ -268,8 +268,16 @@ var usePrivateInfiniteQuery = (getKey, options) => {
268
268
  const account5 = useAccount();
269
269
  const middleware = Array.isArray(restOptions?.use) ? restOptions?.use ?? [] : [];
270
270
  const result = useSWRInfinite__default.default(
271
- (pageIndex, previousPageData) => account5.state.status >= types.AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
272
- (url, init) => net.get(url, init, formatter),
271
+ (pageIndex, previousPageData) => {
272
+ const queryKey = getKey(pageIndex, previousPageData);
273
+ if (account5.state.status < types.AccountStatusEnum.EnableTrading || !queryKey) {
274
+ return null;
275
+ }
276
+ return [queryKey, account5.state.accountId];
277
+ },
278
+ (url, init) => {
279
+ return net.get(url, init, formatter);
280
+ },
273
281
  {
274
282
  ...restOptions,
275
283
  use: [signatureMiddleware, ...middleware]
@@ -432,12 +440,113 @@ var useWS = () => {
432
440
  websocketClient.openPrivate(nextState.accountId);
433
441
  }
434
442
  });
443
+ if (typeof window !== "undefined") {
444
+ window["__Orderly_WS"] = websocketClient;
445
+ }
435
446
  core.SimpleDI.registerByName(WS_NAME, websocketClient);
436
447
  }
437
448
  return websocketClient;
438
449
  });
439
450
  return ws;
440
451
  };
452
+ var usePrivateDataObserver = () => {
453
+ const ws = useWS();
454
+ const { mutate: mutate2 } = useSWR.useSWRConfig();
455
+ const ee = useEventEmitter();
456
+ const { state } = useAccount();
457
+ const updateOrders = useDebounce.useDebouncedCallback(() => {
458
+ mutate2(
459
+ useSWRInfinite.unstable_serialize(() => [
460
+ `/v1/orders?size=100&page=1&status=${types.OrderStatus.INCOMPLETE}`,
461
+ state.accountId
462
+ ])
463
+ );
464
+ mutate2(
465
+ useSWRInfinite.unstable_serialize(() => [
466
+ `/v1/orders?size=100&page=1&status=${types.OrderStatus.NEW}`,
467
+ state.accountId
468
+ ])
469
+ );
470
+ }, 500);
471
+ React.useEffect(() => {
472
+ if (!state.accountId)
473
+ return;
474
+ const unsubscribe = ws.privateSubscribe("executionreport", {
475
+ onMessage: (data) => {
476
+ updateOrders();
477
+ ee.emit("orders:changed", data);
478
+ }
479
+ });
480
+ return () => unsubscribe?.();
481
+ }, [state.accountId]);
482
+ React.useEffect(() => {
483
+ if (!state.accountId)
484
+ return;
485
+ const key = ["/v1/positions", state.accountId];
486
+ const unsubscribe = ws.privateSubscribe("position", {
487
+ onMessage: (data) => {
488
+ const { positions: nextPostions } = data;
489
+ mutate2(
490
+ key,
491
+ (prevPositions) => {
492
+ if (!!prevPositions) {
493
+ return {
494
+ ...prevPositions,
495
+ rows: prevPositions.rows.map((row) => {
496
+ const item = nextPostions.find(
497
+ (item2) => item2.symbol === row.symbol
498
+ );
499
+ if (item) {
500
+ return {
501
+ symbol: item.symbol,
502
+ position_qty: item.positionQty,
503
+ cost_position: item.costPosition,
504
+ last_sum_unitary_funding: item.lastSumUnitaryFunding,
505
+ pending_long_qty: item.pendingLongQty,
506
+ pending_short_qty: item.pendingShortQty,
507
+ settle_price: item.settlePrice,
508
+ average_open_price: item.averageOpenPrice,
509
+ unsettled_pnl: item.unsettledPnl,
510
+ mark_price: item.markPrice,
511
+ est_liq_price: item.estLiqPrice,
512
+ timestamp: Date.now(),
513
+ imr: item.imr,
514
+ mmr: item.mmr,
515
+ IMR_withdraw_orders: item.imrwithOrders,
516
+ MMR_with_orders: item.mmrwithOrders,
517
+ pnl_24_h: item.pnl24H,
518
+ fee_24_h: item.fee24H
519
+ };
520
+ }
521
+ return row;
522
+ })
523
+ };
524
+ }
525
+ },
526
+ {
527
+ revalidate: false
528
+ }
529
+ );
530
+ }
531
+ });
532
+ return () => {
533
+ unsubscribe?.();
534
+ };
535
+ }, [state.accountId]);
536
+ };
537
+ var DataCenterContext = React.createContext(
538
+ {}
539
+ );
540
+ var DataCenterProvider = ({ children }) => {
541
+ const { error, done } = usePreLoadData();
542
+ usePrivateDataObserver();
543
+ if (error) {
544
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { children: "Data load failed" });
545
+ }
546
+ if (!done)
547
+ return null;
548
+ return /* @__PURE__ */ jsxRuntime.jsx(DataCenterContext.Provider, { value: {}, children });
549
+ };
441
550
  var OrderlyConfigProvider = (props) => {
442
551
  const [account5, setAccount] = React__default.default.useState(null);
443
552
  const {
@@ -475,7 +584,7 @@ var OrderlyConfigProvider = (props) => {
475
584
  if (!account5) {
476
585
  return null;
477
586
  }
478
- return /* @__PURE__ */ React__default.default.createElement(
587
+ return /* @__PURE__ */ jsxRuntime.jsx(
479
588
  OrderlyProvider,
480
589
  {
481
590
  value: {
@@ -485,9 +594,9 @@ var OrderlyConfigProvider = (props) => {
485
594
  networkId,
486
595
  enableSwapDeposit
487
596
  // apiBaseUrl,
488
- }
489
- },
490
- props.children
597
+ },
598
+ children: /* @__PURE__ */ jsxRuntime.jsx(DataCenterProvider, { children: props.children })
599
+ }
491
600
  );
492
601
  };
493
602
  var WalletConnectorContext = React.createContext({});
@@ -1109,7 +1218,7 @@ var usePositionStream = (symbol, options) => {
1109
1218
  } = usePrivateQuery(`/v1/positions`, {
1110
1219
  // revalidateOnFocus: false,
1111
1220
  // revalidateOnReconnect: false,
1112
- // dedupingInterval: 100,
1221
+ // dedupingInterval: 200,
1113
1222
  // keepPreviousData: false,
1114
1223
  // revalidateIfStale: true,
1115
1224
  ...options,
@@ -1117,10 +1226,6 @@ var usePositionStream = (symbol, options) => {
1117
1226
  onError: (err) => {
1118
1227
  }
1119
1228
  });
1120
- usePositionUpdateStream((positions2) => {
1121
- console.log("position message", positions2);
1122
- updatePositions();
1123
- });
1124
1229
  const { data: markPrices } = useMarkPricesStream();
1125
1230
  const formatedPositions = React.useMemo(() => {
1126
1231
  if (!data?.rows || !symbolInfo || !accountInfo)
@@ -1269,41 +1374,6 @@ var pathOr_unsettledPnLPathOr = ramda.pathOr(0, [
1269
1374
  "aggregated",
1270
1375
  "unsettledPnL"
1271
1376
  ]);
1272
- var usePositionUpdateStream = (callback) => {
1273
- const ws = useWS();
1274
- const positionList = React.useRef({});
1275
- return useSWRSubscription__default.default("positionUpdate", (key, { next }) => {
1276
- const unsubscribe = ws.privateSubscribe(
1277
- // { event: "subscribe", topic: "markprices" },
1278
- "position",
1279
- {
1280
- onMessage: (message) => {
1281
- const { positions: positions2 } = message;
1282
- let update = false;
1283
- for (const p in positions2) {
1284
- const { symbol, positionQty } = positions2[p];
1285
- if (positionList.current[symbol] !== positionQty) {
1286
- update = true;
1287
- positionList.current[symbol] = positionQty;
1288
- }
1289
- }
1290
- if (update) {
1291
- callback(positions2.current);
1292
- }
1293
- next(null, positionList);
1294
- },
1295
- // onUnsubscribe: () => {
1296
- // return "markprices";
1297
- // },
1298
- onError: (error) => {
1299
- }
1300
- }
1301
- );
1302
- return () => {
1303
- unsubscribe?.();
1304
- };
1305
- });
1306
- };
1307
1377
  var useHoldingStream = () => {
1308
1378
  const ws = useWS();
1309
1379
  const { data, isLoading, mutate: mutate2 } = usePrivateQuery(
@@ -1355,10 +1425,15 @@ var useHoldingStream = () => {
1355
1425
  };
1356
1426
  var useOrderStream = (params) => {
1357
1427
  const { status, symbol, side, size = 100 } = params;
1358
- const ws = useWS();
1359
1428
  const { data: markPrices = {} } = useMarkPricesStream();
1360
- const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1361
- const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1429
+ const [doCancelOrder, { error: cancelOrderError }] = useMutation(
1430
+ "/v1/order",
1431
+ "DELETE"
1432
+ );
1433
+ const [doUpdateOrder, { error: updateOrderError }] = useMutation(
1434
+ "/v1/order",
1435
+ "PUT"
1436
+ );
1362
1437
  const ordersResponse = usePrivateInfiniteQuery(
1363
1438
  (pageIndex, previousPageData) => {
1364
1439
  if (previousPageData && !previousPageData.rows?.length)
@@ -1381,9 +1456,9 @@ var useOrderStream = (params) => {
1381
1456
  {
1382
1457
  initialSize: 1,
1383
1458
  // revalidateFirstPage: false,
1384
- onError: (err) => {
1385
- console.error("fetch failed::::", err);
1386
- },
1459
+ // onError: (err) => {
1460
+ // console.error("fetch failed::::", err);
1461
+ // },
1387
1462
  formatter: (data) => data
1388
1463
  }
1389
1464
  );
@@ -1400,68 +1475,7 @@ var useOrderStream = (params) => {
1400
1475
  }, [ordersResponse.data, markPrices]);
1401
1476
  const total = React.useMemo(() => {
1402
1477
  return ordersResponse.data?.[0]?.meta?.total || 0;
1403
- }, [ordersResponse.data]);
1404
- React.useEffect(() => {
1405
- const unsubscribe = ws.privateSubscribe(
1406
- {
1407
- id: "executionreport_orders",
1408
- event: "subscribe",
1409
- topic: "executionreport",
1410
- ts: Date.now()
1411
- },
1412
- {
1413
- onMessage: (data) => {
1414
- const { status: status2, orderId, timestamp } = data;
1415
- ordersResponse.mutate((prevData) => {
1416
- const newOrder = {
1417
- order_id: data.orderId,
1418
- symbol: data.symbol,
1419
- created_time: data.timestamp,
1420
- quantity: data.quantity,
1421
- side: data.side,
1422
- executed: data.totalExecutedQuantity,
1423
- price: data.price
1424
- };
1425
- const dataList = prevData?.map((item) => item.rows)?.flat() || [];
1426
- if (status2 === types.OrderStatus.NEW) {
1427
- if (!prevData) {
1428
- return {
1429
- meta: {
1430
- total: 1,
1431
- records_per_page: size,
1432
- current_page: 1
1433
- },
1434
- rows: [newOrder]
1435
- };
1436
- }
1437
- const total2 = (prevData?.[0]?.meta?.total || 0) + 1;
1438
- const isNew = !dataList.find((item) => item.order_id === orderId);
1439
- if (isNew) {
1440
- const list = [newOrder, ...dataList];
1441
- return rePageData(list, total2, size);
1442
- }
1443
- return prevData;
1444
- }
1445
- if (status2 === types.OrderStatus.CANCELLED || status2 === types.OrderStatus.FILLED) {
1446
- const total2 = (prevData?.[0]?.meta?.total || 0) - 1;
1447
- const list = dataList.filter(
1448
- (order2) => order2.order_id !== orderId
1449
- );
1450
- return rePageData(list, total2, size);
1451
- }
1452
- if (status2 === types.OrderStatus.PARTIAL_FILLED) {
1453
- return editPageData(dataList, newOrder);
1454
- }
1455
- if (status2 === types.OrderStatus.REPLACED) {
1456
- return editPageData(dataList, newOrder);
1457
- }
1458
- return prevData;
1459
- });
1460
- }
1461
- }
1462
- );
1463
- return () => unsubscribe();
1464
- }, []);
1478
+ }, [ordersResponse.data?.[0]?.meta?.total]);
1465
1479
  const cancelAllOrders = React.useCallback(() => {
1466
1480
  }, [ordersResponse.data]);
1467
1481
  const updateOrder = React.useCallback((orderId, order2) => {
@@ -1488,44 +1502,14 @@ var useOrderStream = (params) => {
1488
1502
  loadMore,
1489
1503
  cancelAllOrders,
1490
1504
  updateOrder,
1491
- cancelOrder
1505
+ cancelOrder,
1506
+ errors: {
1507
+ cancelOrder: cancelOrderError,
1508
+ updateOrder: updateOrderError
1509
+ }
1492
1510
  }
1493
1511
  ];
1494
1512
  };
1495
- function rePageData(list, total, pageSize) {
1496
- const newData = [];
1497
- let rows = [];
1498
- let current_page = 0;
1499
- for (let i = 0; i < list.length; i++) {
1500
- rows.push(list[i]);
1501
- if ((i + 1) % pageSize === 0 || i === list.length - 1) {
1502
- newData.push({
1503
- meta: {
1504
- records_per_page: pageSize,
1505
- total,
1506
- current_page: current_page + 1
1507
- },
1508
- rows: [...rows]
1509
- });
1510
- rows = [];
1511
- }
1512
- }
1513
- return newData;
1514
- }
1515
- function editPageData(list, newOrder) {
1516
- const newData = list.map((item) => {
1517
- return {
1518
- ...item,
1519
- rows: item.rows.map((row) => {
1520
- if (row.order_id === newOrder.order_id) {
1521
- return { ...row, newOrder };
1522
- }
1523
- return row;
1524
- })
1525
- };
1526
- });
1527
- return newData;
1528
- }
1529
1513
 
1530
1514
  // src/orderly/useCollateral.ts
1531
1515
  var positionsPath = ramda.pathOr([], [0, "rows"]);
@@ -1584,33 +1568,7 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
1584
1568
  const symbolInfo = useSymbolsInfo();
1585
1569
  const { totalCollateral } = useCollateral();
1586
1570
  const { data: markPrices } = useMarkPricesStream();
1587
- const {
1588
- data: orders,
1589
- error,
1590
- mutate: updateOrder
1591
- } = usePrivateQuery(`/v1/orders?status=NEW&size=99`, {
1592
- formatter: (data) => data.rows,
1593
- onError: (err) => {
1594
- }
1595
- });
1596
- const ws = useWS();
1597
- React.useEffect(() => {
1598
- const unsubscribe = ws.privateSubscribe(
1599
- {
1600
- id: "executionreport_orders",
1601
- event: "subscribe",
1602
- topic: "executionreport",
1603
- ts: Date.now()
1604
- },
1605
- {
1606
- onMessage: (data) => {
1607
- console.log("refresh orders", data);
1608
- updateOrder();
1609
- }
1610
- }
1611
- );
1612
- return () => unsubscribe();
1613
- }, []);
1571
+ const [orders] = useOrderStream({ status: types.OrderStatus.NEW });
1614
1572
  const maxQty = React.useMemo(() => {
1615
1573
  if (!symbol)
1616
1574
  return 0;
@@ -3643,59 +3601,6 @@ var useSettleSubscription = (options) => {
3643
3601
  return () => unsubscribe();
3644
3602
  });
3645
3603
  };
3646
- var usePrivateDataObserver = () => {
3647
- const ws = useWS();
3648
- const { mutate: mutate2 } = useSWR.useSWRConfig();
3649
- const { state } = useAccount();
3650
- React.useEffect(() => {
3651
- if (!state.accountId)
3652
- return;
3653
- const key = ["/v1/positions", state.accountId];
3654
- const unsubscribe = ws.privateSubscribe("position", {
3655
- onMessage: (data) => {
3656
- const { positions: nextPostions } = data;
3657
- mutate2(key, (prevPositions) => {
3658
- if (!!prevPositions) {
3659
- return {
3660
- ...prevPositions,
3661
- rows: prevPositions.rows.map((row) => {
3662
- const item = nextPostions.find(
3663
- (item2) => item2.symbol === row.symbol
3664
- );
3665
- if (item) {
3666
- return {
3667
- symbol: item.symbol,
3668
- position_qty: item.positionQty,
3669
- cost_position: item.costPosition,
3670
- last_sum_unitary_funding: item.lastSumUnitaryFunding,
3671
- pending_long_qty: item.pendingLongQty,
3672
- pending_short_qty: item.pendingShortQty,
3673
- settle_price: item.settlePrice,
3674
- average_open_price: item.averageOpenPrice,
3675
- unsettled_pnl: item.unsettledPnl,
3676
- mark_price: item.markPrice,
3677
- est_liq_price: item.estLiqPrice,
3678
- timestamp: Date.now(),
3679
- imr: item.imr,
3680
- mmr: item.mmr,
3681
- IMR_withdraw_orders: item.imrwithOrders,
3682
- MMR_with_orders: item.mmrwithOrders,
3683
- pnl_24_h: item.pnl24H,
3684
- fee_24_h: item.fee24H
3685
- };
3686
- }
3687
- return row;
3688
- })
3689
- };
3690
- }
3691
- });
3692
- }
3693
- });
3694
- return () => {
3695
- unsubscribe?.();
3696
- };
3697
- }, [state.accountId]);
3698
- };
3699
3604
  var useWooSwapQuery = () => {
3700
3605
  const { configStore } = React.useContext(OrderlyContext);
3701
3606
  const account5 = useAccountInstance();