@orderly.network/hooks 0.0.12 → 0.0.13

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,7 +1,7 @@
1
1
  import React, { createContext, useContext, useCallback, useState, useEffect, useMemo } from 'react';
2
- import useSWR from 'swr';
2
+ import useSWR, { useSWRConfig } from 'swr';
3
3
  export { default as useSWR } from 'swr';
4
- import { WebSocketClient, WS, get, post, del } from '@orderly.network/net';
4
+ import { WebSocketClient, 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';
@@ -82,9 +82,6 @@ var fetcher = (url, init = {}, queryOptions) => get(url, init, queryOptions == n
82
82
  var useQuery = (query, options) => {
83
83
  const { apiBaseUrl } = useContext(OrderlyContext);
84
84
  const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
85
- if (typeof query === "string" && !query.startsWith("/public")) {
86
- throw new Error("useQuery is only for public api");
87
- }
88
85
  if (typeof apiBaseUrl === "undefined") {
89
86
  throw new Error("please add OrderlyProvider to your app");
90
87
  }
@@ -117,36 +114,51 @@ var useAccountInstance = () => {
117
114
 
118
115
  // src/useMutation.ts
119
116
  var fetcher2 = (url, options) => {
120
- return post(url, options.arg.data, {
117
+ console.log("muation fetcher", url, options);
118
+ const init = {
119
+ method: options.arg.method,
121
120
  headers: __spreadValues({}, options.arg.signature)
122
- });
123
- };
124
- var deleteFetcher = (url, options) => {
125
- return del(url, options.arg.data, {
126
- headers: __spreadValues({}, options.arg.signature)
127
- });
121
+ };
122
+ if (options.arg.data) {
123
+ init.body = JSON.stringify(options.arg.data);
124
+ }
125
+ if (typeof options.arg.params === "object" && Object.keys(options.arg.params).length) {
126
+ let search = new URLSearchParams(options.arg.params);
127
+ url = `${url}?${search.toString()}`;
128
+ }
129
+ return mutate(url, init);
128
130
  };
129
- var useMutation = (url, options, method = "POST") => {
131
+ var useMutation = (url, method = "POST", options) => {
130
132
  const { apiBaseUrl } = useContext(OrderlyContext);
133
+ let fullUrl = url;
131
134
  if (!url.startsWith("http")) {
132
- url = `${apiBaseUrl}${url}`;
135
+ fullUrl = `${apiBaseUrl}${url}`;
133
136
  }
134
137
  const account4 = useAccountInstance();
135
138
  const signer = account4.signer;
136
139
  const { trigger, data, error, reset, isMutating } = useSWRMutation(
137
- url,
138
- method === "POST" ? fetcher2 : deleteFetcher,
140
+ fullUrl,
141
+ // method === "POST" ? fetcher : deleteFetcher,
142
+ fetcher2,
139
143
  options
140
144
  );
141
- const mutation = (data2) => __async(void 0, null, function* () {
145
+ const mutation = (data2, params) => __async(void 0, null, function* () {
146
+ let newUrl = url;
147
+ if (typeof params === "object" && Object.keys(params).length) {
148
+ let search = new URLSearchParams(params);
149
+ newUrl = `${url}?${search.toString()}`;
150
+ }
142
151
  const payload = {
143
152
  method,
144
- url,
153
+ url: newUrl,
145
154
  data: data2
146
155
  };
156
+ console.log("payload", payload);
147
157
  const signature = yield signer.sign(payload);
148
158
  return trigger({
149
159
  data: data2,
160
+ params,
161
+ method,
150
162
  signature: __spreadProps(__spreadValues({}, signature), {
151
163
  "orderly-account-id": account4.accountId
152
164
  })
@@ -172,7 +184,7 @@ var signatureMiddleware = (useSWRNext) => {
172
184
  const signer = account4.signer;
173
185
  const payload = {
174
186
  method: "GET",
175
- url: fullUrl
187
+ url
176
188
  };
177
189
  const signature = yield signer.sign(payload);
178
190
  return fetcher4(fullUrl, {
@@ -390,7 +402,12 @@ var useTickerStream = (symbol) => {
390
402
  if (!symbol) {
391
403
  throw new Error("useFuturesForSymbol requires a symbol");
392
404
  }
393
- const { data: info } = useQuery(`/public/futures/${symbol}`);
405
+ const { data: info } = useQuery(
406
+ `/v1/public/futures/${symbol}`,
407
+ {
408
+ revalidateOnFocus: false
409
+ }
410
+ );
394
411
  const ws = useWS();
395
412
  const { data: ticker } = useSWRSubscription(
396
413
  `${symbol}@ticker`,
@@ -627,7 +644,7 @@ function createGetter(data, depth = 2) {
627
644
 
628
645
  // src/orderly/useSymbolsInfo.ts
629
646
  var useSymbolsInfo = () => {
630
- const { data = {} } = useQuery(`/public/info`, {
647
+ const { data = {} } = useQuery(`/v1/public/info`, {
631
648
  focusThrottleInterval: 1e3 * 60 * 60 * 24,
632
649
  revalidateOnFocus: false,
633
650
  formatter(data2) {
@@ -655,7 +672,7 @@ var useSymbolsInfo = () => {
655
672
  // src/orderly/useTokenInfo.ts
656
673
  var useTokenInfo = () => {
657
674
  const { data = {} } = useQuery(
658
- "/public/token",
675
+ "/v1/public/token",
659
676
  {
660
677
  focusThrottleInterval: 1e3 * 60 * 60 * 24,
661
678
  revalidateOnFocus: false,
@@ -802,7 +819,7 @@ var getCalculateHandler = (fieldName) => {
802
819
  // src/orderly/useFundingRates.ts
803
820
  var useFundingRates = () => {
804
821
  const { data } = useQuery(
805
- `/public/funding_rates`,
822
+ `/v1/public/funding_rates`,
806
823
  {
807
824
  focusThrottleInterval: 1e3 * 60 * 60 * 24,
808
825
  revalidateOnFocus: false,
@@ -856,9 +873,9 @@ var usePositionStream = (symbol, options) => {
856
873
  symbol
857
874
  );
858
875
  const symbolInfo = useSymbolsInfo();
859
- const { data: accountInfo } = usePrivateQuery("/client/info");
876
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
860
877
  const fundingRates = useFundingRates();
861
- const { data, error } = usePrivateQuery(`/positions`, __spreadProps(__spreadValues({}, options), {
878
+ const { data, error } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({}, options), {
862
879
  formatter: (data2) => data2,
863
880
  onError: (err) => {
864
881
  console.log("usePositionStream error", err);
@@ -960,15 +977,18 @@ var positionsPath = pathOr([], [0, "rows"]);
960
977
  var useCollateral = (options = { dp: 6 }) => {
961
978
  const { dp } = options;
962
979
  const positions2 = usePositionStream();
963
- const { data: orders } = usePrivateQuery(`/orders`);
964
- const { data: accountInfo } = usePrivateQuery("/client/info");
980
+ const { data: orders } = usePrivateQuery(`/v1/orders`);
981
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
965
982
  const symbolInfo = useSymbolsInfo();
966
983
  const { data: markPrices } = useMarkPricesStream();
967
- const { data: holding } = usePrivateQuery("/client/holding", {
968
- formatter: (data) => {
969
- return data.holding;
984
+ const { data: holding } = usePrivateQuery(
985
+ "/v1/client/holding",
986
+ {
987
+ formatter: (data) => {
988
+ return data.holding;
989
+ }
970
990
  }
971
- });
991
+ );
972
992
  const [totalCollateral, totalValue] = useMemo(() => {
973
993
  if (!holding || !markPrices) {
974
994
  return [zero, zero];
@@ -1026,8 +1046,8 @@ var useCollateral = (options = { dp: 6 }) => {
1026
1046
  var positionsPath2 = pathOr([], [0, "rows"]);
1027
1047
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1028
1048
  const positionsData = usePositionStream();
1029
- const { data: orders } = usePrivateQuery(`/orders`);
1030
- const { data: accountInfo } = usePrivateQuery("/client/info");
1049
+ const { data: orders } = usePrivateQuery(`/v1/orders`);
1050
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1031
1051
  const symbolInfo = useSymbolsInfo();
1032
1052
  const { totalCollateral } = useCollateral();
1033
1053
  const { data: markPrices } = useMarkPricesStream();
@@ -1125,7 +1145,6 @@ var BaseOrderCreator = class {
1125
1145
  baseValidate(values, configs) {
1126
1146
  const errors = {};
1127
1147
  const { maxQty } = configs;
1128
- console.log("baseValidate", values, configs);
1129
1148
  const { order_quantity, total } = values;
1130
1149
  if (!order_quantity) {
1131
1150
  errors.order_quantity = {
@@ -1246,10 +1265,9 @@ var OrderFactory = class {
1246
1265
  }
1247
1266
  }
1248
1267
  };
1249
-
1250
- // src/orderly/useOrderEntry.ts
1251
1268
  var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1252
- const [mutation] = useMutation("/order");
1269
+ const { mutate: mutate2 } = useSWRConfig();
1270
+ const [doCreateOrder] = useMutation("/v1/order");
1253
1271
  const { freeCollateral } = useCollateral();
1254
1272
  const symbolInfo = useSymbolsInfo();
1255
1273
  const tokenInfo = useTokenInfo();
@@ -1290,9 +1308,14 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1290
1308
  throw new Error("symbol is null");
1291
1309
  }
1292
1310
  const data = orderCreator.create(values);
1293
- return mutation(__spreadProps(__spreadValues({}, data), {
1311
+ return doCreateOrder(__spreadProps(__spreadValues({}, data), {
1294
1312
  symbol
1295
- }));
1313
+ })).then((res) => {
1314
+ if (res.success) {
1315
+ mutate2("/v1/orders?size=100&page=1$status=NEW");
1316
+ }
1317
+ return res;
1318
+ });
1296
1319
  });
1297
1320
  };
1298
1321
  const calculate = useCallback(
@@ -1331,7 +1354,12 @@ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1331
1354
  };
1332
1355
  };
1333
1356
  var useFetures = () => {
1334
- const { data, isLoading, error } = useQuery(`/public/futures`);
1357
+ const { data, isLoading, error } = useQuery(
1358
+ `/v1/public/futures`,
1359
+ {
1360
+ revalidateOnFocus: false
1361
+ }
1362
+ );
1335
1363
  const [sortedData, setSortedData] = useState(data);
1336
1364
  const ws = useWebSocketClient();
1337
1365
  useEffect(() => {
@@ -1366,11 +1394,13 @@ var useFetures = () => {
1366
1394
 
1367
1395
  // src/orderly/useAccountInfo.ts
1368
1396
  var useAccountInfo = () => {
1369
- return usePrivateQuery("/client/info");
1397
+ return usePrivateQuery("/v1/client/info");
1370
1398
  };
1371
1399
  var useMarketsStream = () => {
1372
1400
  const ws = useWS();
1373
- const { data: futures } = useQuery(`/public/futures`);
1401
+ const { data: futures } = useQuery(`/v1/public/futures`, {
1402
+ revalidateOnFocus: false
1403
+ });
1374
1404
  const { data: tickers } = useSWRSubscription("tickers", (_, { next }) => {
1375
1405
  const unsubscribe = ws.subscribe(
1376
1406
  // { event: "subscribe", topic: "markprices" },
@@ -1419,12 +1449,15 @@ var useFundingRate = (symbol) => {
1419
1449
  throw new Error("useFuturesForSymbol requires a symbol");
1420
1450
  }
1421
1451
  const [countDown, setCountDown] = useState("00:00:00");
1422
- const { data } = useQuery(`/public/funding_rate/${symbol}`, {
1423
- fallbackData: {
1424
- est_funding_rate: 0,
1425
- next_funing_time: 0
1452
+ const { data } = useQuery(
1453
+ `/v1/public/funding_rate/${symbol}`,
1454
+ {
1455
+ fallbackData: {
1456
+ est_funding_rate: 0,
1457
+ next_funing_time: 0
1458
+ }
1426
1459
  }
1427
- });
1460
+ );
1428
1461
  useEffect(() => {
1429
1462
  if (!data)
1430
1463
  return;
@@ -1476,7 +1509,9 @@ var useOrderStream = ({
1476
1509
  symbol
1477
1510
  } = {}) => {
1478
1511
  const { data: markPrices = {} } = useMarkPricesStream();
1479
- const res = usePrivateInfiniteQuery(
1512
+ const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1513
+ const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1514
+ const ordersResponse = usePrivateInfiniteQuery(
1480
1515
  (pageIndex, previousPageData) => {
1481
1516
  const search = new URLSearchParams([
1482
1517
  ["size", "100"],
@@ -1486,7 +1521,7 @@ var useOrderStream = ({
1486
1521
  if (symbol) {
1487
1522
  search.set(`symbol`, symbol);
1488
1523
  }
1489
- return `/orders?${search.toString()}`;
1524
+ return `/v1/orders?${search.toString()}`;
1490
1525
  },
1491
1526
  {
1492
1527
  initialSize: 1,
@@ -1497,21 +1532,35 @@ var useOrderStream = ({
1497
1532
  );
1498
1533
  const orders = useMemo(() => {
1499
1534
  var _a;
1500
- if (!res.data) {
1535
+ if (!ordersResponse.data) {
1501
1536
  return null;
1502
1537
  }
1503
- return (_a = res.data) == null ? void 0 : _a.flat().map((item) => {
1538
+ return (_a = ordersResponse.data) == null ? void 0 : _a.flat().map((item) => {
1504
1539
  var _a2;
1505
1540
  return __spreadProps(__spreadValues({}, item), {
1506
1541
  mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
1507
1542
  });
1508
1543
  });
1509
- }, [res.data, markPrices]);
1544
+ }, [ordersResponse.data, markPrices]);
1510
1545
  const cancelAllOrders = useCallback(() => {
1511
- }, [res.data]);
1512
- const updateOrder = useCallback((id, data) => {
1546
+ }, [ordersResponse.data]);
1547
+ const updateOrder = useCallback((orderId, order2) => {
1548
+ console.log("updateOrder", order2, orderId);
1549
+ return doUpdateOrder(__spreadProps(__spreadValues({}, order2), { order_id: orderId }));
1513
1550
  }, []);
1514
- const cancelOrder = useCallback((id) => {
1551
+ const cancelOrder = useCallback((orderId, symbol2) => {
1552
+ return doCancelOrder(null, {
1553
+ order_id: orderId,
1554
+ symbol: symbol2
1555
+ }).then((res) => {
1556
+ if (res.success) {
1557
+ return ordersResponse.mutate().then(() => {
1558
+ return res;
1559
+ });
1560
+ } else {
1561
+ throw new Error(res.message);
1562
+ }
1563
+ });
1515
1564
  }, []);
1516
1565
  return [
1517
1566
  orders,
@@ -1535,7 +1584,7 @@ var useTradeStream = (symbol) => {
1535
1584
  throw new Error("useTradeStream: symbol is required");
1536
1585
  }
1537
1586
  const { data, isLoading } = useQuery(
1538
- `/public/market_trades?symbol=${symbol}&limit=20`
1587
+ `/v1/public/market_trades?symbol=${symbol}&limit=20`
1539
1588
  );
1540
1589
  return { data, isLoading };
1541
1590
  };
@@ -1611,14 +1660,14 @@ __export(apis_exports, {
1611
1660
 
1612
1661
  // src/apis/useInfo.ts
1613
1662
  var useInfo = () => {
1614
- return useQuery("/public/info", {
1663
+ return useQuery("/v1/public/info", {
1615
1664
  // refreshInterval: 1000 * 60 * 60 * 24,
1616
1665
  });
1617
1666
  };
1618
1667
 
1619
1668
  // src/apis/useToken.ts
1620
1669
  var useToken = () => {
1621
- return useQuery("/public/token");
1670
+ return useQuery("/v1/public/token");
1622
1671
  };
1623
1672
 
1624
1673
  // src/apis/useFundingRateBySymbol.ts
@@ -1631,7 +1680,7 @@ var useFundingRateBySymbol = (symbol) => {
1631
1680
 
1632
1681
  // src/apis/useFundingRate.ts
1633
1682
  var useFundingRate2 = (symbol) => {
1634
- return useQuery(`/public/funding_rate`);
1683
+ return useQuery(`/v1/public/funding_rate`);
1635
1684
  };
1636
1685
 
1637
1686
  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, useWebSocketClient };