@orderly.network/hooks 0.0.52 → 0.0.54

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,4 +1,4 @@
1
- import React2, { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
1
+ import React2, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
2
  import useSWR, { useSWRConfig } from 'swr';
3
3
  export { SWRConfig, default as useSWR } from 'swr';
4
4
  import { WS, get, mutate } from '@orderly.network/net';
@@ -21,26 +21,26 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
21
21
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
22
22
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
23
23
  var __spreadValues = (a, b) => {
24
- for (var prop2 in b || (b = {}))
25
- if (__hasOwnProp.call(b, prop2))
26
- __defNormalProp(a, prop2, b[prop2]);
24
+ for (var prop3 in b || (b = {}))
25
+ if (__hasOwnProp.call(b, prop3))
26
+ __defNormalProp(a, prop3, b[prop3]);
27
27
  if (__getOwnPropSymbols)
28
- for (var prop2 of __getOwnPropSymbols(b)) {
29
- if (__propIsEnum.call(b, prop2))
30
- __defNormalProp(a, prop2, b[prop2]);
28
+ for (var prop3 of __getOwnPropSymbols(b)) {
29
+ if (__propIsEnum.call(b, prop3))
30
+ __defNormalProp(a, prop3, b[prop3]);
31
31
  }
32
32
  return a;
33
33
  };
34
34
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
35
35
  var __objRest = (source, exclude) => {
36
36
  var target = {};
37
- for (var prop2 in source)
38
- if (__hasOwnProp.call(source, prop2) && exclude.indexOf(prop2) < 0)
39
- target[prop2] = source[prop2];
37
+ for (var prop3 in source)
38
+ if (__hasOwnProp.call(source, prop3) && exclude.indexOf(prop3) < 0)
39
+ target[prop3] = source[prop3];
40
40
  if (source != null && __getOwnPropSymbols)
41
- for (var prop2 of __getOwnPropSymbols(source)) {
42
- if (exclude.indexOf(prop2) < 0 && __propIsEnum.call(source, prop2))
43
- target[prop2] = source[prop2];
41
+ for (var prop3 of __getOwnPropSymbols(source)) {
42
+ if (exclude.indexOf(prop3) < 0 && __propIsEnum.call(source, prop3))
43
+ target[prop3] = source[prop3];
44
44
  }
45
45
  return target;
46
46
  };
@@ -312,26 +312,31 @@ var useTopicObserve = (topic) => {
312
312
  };
313
313
  };
314
314
  var useAppState = () => {
315
- const { errors, ready } = useContext(OrderlyContext);
315
+ const { errors } = useContext(OrderlyContext);
316
316
  return {
317
- errors,
318
- ready
317
+ errors
318
+ // ready,
319
319
  };
320
320
  };
321
-
322
- // src/usePreloadData.ts
323
- var usePreLoadData = (onSuccess) => {
324
- useSWR(
325
- "https://fi-api.woo.org/swap_support",
321
+ var usePreLoadData = () => {
322
+ const { configStore } = useContext(OrderlyContext);
323
+ const { error: swapSupportError, data: swapSupportData } = useSWR(
324
+ `${configStore.get("swapSupportApiUrl")}/swap_support`,
326
325
  (url) => fetch(url).then((res) => res.json()),
327
326
  {
328
- revalidateOnFocus: false,
329
- // suspense: true,
330
- onSuccess: (data, key, config) => {
331
- onSuccess("chains_fetch");
332
- }
327
+ revalidateOnFocus: false
333
328
  }
334
329
  );
330
+ const { error: tokenError, data: tokenData } = useQuery("/v1/public/token", {
331
+ revalidateOnFocus: false
332
+ });
333
+ const isDone = useMemo(() => {
334
+ return !!swapSupportData && !!tokenData;
335
+ }, [swapSupportData, tokenData]);
336
+ return {
337
+ error: swapSupportError || tokenError,
338
+ done: isDone
339
+ };
335
340
  };
336
341
  var useEventEmitter = (channel) => {
337
342
  return useConstant(() => {
@@ -1114,7 +1119,7 @@ var usePositionStream = (symbol, options) => {
1114
1119
  const MMR = positions.MMR({
1115
1120
  baseMMR: info("base_mmr"),
1116
1121
  baseIMR: info("base_imr"),
1117
- IMRFactor: accountInfo.imr_factor[info("base")],
1122
+ IMRFactor: accountInfo.imr_factor[item.symbol],
1118
1123
  positionNotional: item.notional,
1119
1124
  IMR_factor_power: 4 / 5
1120
1125
  });
@@ -1334,7 +1339,7 @@ var useMaxQty = (symbol, side, reduceOnly = false) => {
1334
1339
  positionQty,
1335
1340
  buyOrdersQty,
1336
1341
  sellOrdersQty,
1337
- IMR_Factor: accountInfo.imr_factor[getSymbolInfo("base")]
1342
+ IMR_Factor: accountInfo.imr_factor[symbol]
1338
1343
  });
1339
1344
  }, [
1340
1345
  orders,
@@ -1899,7 +1904,6 @@ var useMarketTradeStream = (symbol, options = {}) => {
1899
1904
  unsubscript == null ? void 0 : unsubscript();
1900
1905
  };
1901
1906
  }, [symbol]);
1902
- console.log("trades", trades);
1903
1907
  return { data: trades, isLoading };
1904
1908
  };
1905
1909
  var useMarginRatio = () => {
@@ -1923,51 +1927,109 @@ var useMarginRatio = () => {
1923
1927
  return { marginRatio, currentLeverage };
1924
1928
  };
1925
1929
  var useChains = (networkId, options = {}) => {
1926
- const _a = options, swrOptions = __objRest(_a, ["filter", "pick"]);
1930
+ const _a = options, { filter, pick, crossEnabled, wooSwapEnabled } = _a, swrOptions = __objRest(_a, ["filter", "pick", "crossEnabled", "wooSwapEnabled"]);
1931
+ const { configStore } = useContext(OrderlyContext);
1927
1932
  const field = options == null ? void 0 : options.pick;
1928
- const { data } = useSWR(
1929
- "https://fi-api.woo.org/swap_support",
1933
+ const map = useRef(/* @__PURE__ */ new Map());
1934
+ const { data, error: swapSupportError } = useSWR(
1935
+ () => wooSwapEnabled ? `${configStore.get("swapSupportApiUrl")}/swap_support` : null,
1936
+ // `${configStore.get("swapSupportApiUrl")}/swap_support`,
1930
1937
  (url) => fetch(url).then((res) => res.json()),
1931
1938
  __spreadValues({
1932
1939
  revalidateOnFocus: false,
1933
1940
  revalidateOnReconnect: false
1934
1941
  }, swrOptions)
1935
1942
  );
1943
+ const { data: orderlyChains, error: tokenError } = useQuery("/v1/public/token");
1936
1944
  const chains = useMemo(() => {
1937
- if (!data || !data.data)
1938
- return data;
1939
- let arr = [];
1940
- Object.keys(data.data).forEach((key) => {
1941
- const item = data.data[key];
1942
- arr.push(__spreadProps(__spreadValues({}, item), {
1943
- name: key
1944
- }));
1945
+ if (!orderlyChains)
1946
+ return void 0;
1947
+ const orderlyChainsArr = [];
1948
+ const orderlyChainIds = /* @__PURE__ */ new Set();
1949
+ orderlyChains.forEach((item) => {
1950
+ item.chain_details.forEach((chain) => {
1951
+ var _a2;
1952
+ const chainId = Number(chain.chain_id);
1953
+ orderlyChainIds.add(chainId);
1954
+ const chainInfo = chainsMap.get(chainId);
1955
+ const _chain = {
1956
+ network_infos: {
1957
+ name: (_a2 = chainInfo == null ? void 0 : chainInfo.chainName) != null ? _a2 : "--",
1958
+ // "public_rpc_url": "https://arb1.arbitrum.io/rpc",
1959
+ chain_id: chainId,
1960
+ // decimals: chain.decimals,
1961
+ // contract_address: chain.contract_address,
1962
+ bridgeless: true
1963
+ },
1964
+ token_infos: [
1965
+ {
1966
+ symbol: item.token,
1967
+ address: chain.contract_address,
1968
+ decimals: chain.decimals
1969
+ }
1970
+ ]
1971
+ };
1972
+ if (typeof (options == null ? void 0 : options.filter) === "function") {
1973
+ if (!options.filter(_chain))
1974
+ return;
1975
+ }
1976
+ map.current.set(chainId, _chain);
1977
+ orderlyChainsArr.push(field ? _chain[field] : _chain);
1978
+ });
1945
1979
  });
1946
- if (networkId === "mainnet") {
1947
- arr = arr.filter((item) => item.network_infos.mainnet);
1948
- }
1949
- if (networkId === "testnet") {
1950
- arr = arr.filter((item) => !item.network_infos.mainnet);
1951
- }
1952
- if (typeof (options == null ? void 0 : options.filter) === "function") {
1953
- arr = arr.filter(options.filter);
1954
- }
1955
- if (typeof field !== "undefined") {
1956
- return arr.map((item) => {
1957
- return item[field];
1980
+ if (!wooSwapEnabled) {
1981
+ return orderlyChainsArr;
1982
+ } else {
1983
+ if (!data || !data.data)
1984
+ return data;
1985
+ let testnetArr = [];
1986
+ let mainnetArr = [];
1987
+ Object.keys(data.data).forEach((key) => {
1988
+ var _a2;
1989
+ if (orderlyChainIds.has(data.data[key].network_infos.chain_id))
1990
+ return;
1991
+ const item = __spreadProps(__spreadValues({}, data.data[key]), {
1992
+ name: key
1993
+ });
1994
+ if (((_a2 = item.token_infos) == null ? void 0 : _a2.length) === 0)
1995
+ return;
1996
+ map.current.set(item.network_infos.chain_id, item);
1997
+ if (typeof (options == null ? void 0 : options.filter) === "function") {
1998
+ if (!options.filter(item))
1999
+ return;
2000
+ }
2001
+ if (item.network_infos.mainnet) {
2002
+ mainnetArr.push(field ? item[field] : item);
2003
+ } else {
2004
+ testnetArr.push(field ? item[field] : item);
2005
+ }
1958
2006
  });
2007
+ if (orderlyChainIds.size > 0) {
2008
+ testnetArr = [...orderlyChainsArr, ...testnetArr];
2009
+ }
2010
+ if (networkId === "mainnet") {
2011
+ return mainnetArr;
2012
+ }
2013
+ if (networkId === "testnet") {
2014
+ return testnetArr;
2015
+ }
2016
+ return {
2017
+ testnet: testnetArr,
2018
+ mainnet: mainnetArr
2019
+ };
1959
2020
  }
1960
- return arr;
1961
- }, [data, networkId, field, options]);
2021
+ }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
1962
2022
  const findByChainId = useCallback(
1963
- (chainId) => {
1964
- if (!data || !data.data)
1965
- return void 0;
1966
- return data.data[chainId];
2023
+ (chainId, field2) => {
2024
+ const chain = map.current.get(chainId);
2025
+ if (typeof field2 === "string") {
2026
+ return prop(field2, chain);
2027
+ }
2028
+ return chain;
1967
2029
  },
1968
- [data]
2030
+ [chains, map.current]
1969
2031
  );
1970
- return [chains, { findByChainId }];
2032
+ return [chains, { findByChainId, error: swapSupportError || tokenError }];
1971
2033
  };
1972
2034
  var useChain = (token) => {
1973
2035
  const { data, isLoading } = useQuery("/v1/public/token");
@@ -2012,25 +2074,78 @@ var useWithdraw = () => {
2012
2074
  }, [usdc, unsettledPnL]);
2013
2075
  return { withdraw, isLoading, maxAmount, availableBalance, unsettledPnL };
2014
2076
  };
2015
- var useDeposit = () => {
2077
+ var nativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
2078
+ var isNativeToken = (address) => address === nativeTokenAddress;
2079
+ var useDeposit = (options) => {
2080
+ const [balanceRevalidating, setBalanceRevalidating] = useState(false);
2081
+ const [allowanceRevalidating, setAllowanceRevalidating] = useState(false);
2016
2082
  const [balance, setBalance] = useState("0");
2017
2083
  const [allowance, setAllowance] = useState("0");
2018
2084
  const { account: account5, state } = useAccount();
2019
- const fetchBalance = useCallback(() => __async(void 0, null, function* () {
2020
- const balance2 = yield account5.assetsManager.getBalance();
2021
- setBalance(() => balance2);
2022
- }), [state]);
2023
- const fetchAllowance = useCallback(() => __async(void 0, null, function* () {
2024
- const allowance2 = yield account5.assetsManager.getAllowance();
2025
- setAllowance(() => allowance2);
2026
- return allowance2;
2085
+ const fetchBalanceHandler = useCallback((address) => __async(void 0, null, function* () {
2086
+ let balance2;
2087
+ if (!!address && isNativeToken(address)) {
2088
+ balance2 = yield account5.assetsManager.getNativeBalance();
2089
+ } else {
2090
+ balance2 = yield account5.assetsManager.getBalance(address);
2091
+ }
2092
+ return balance2;
2027
2093
  }), []);
2094
+ const fetchBalance = useCallback(
2095
+ (address) => __async(void 0, null, function* () {
2096
+ if (!address)
2097
+ return;
2098
+ try {
2099
+ if (balanceRevalidating)
2100
+ return;
2101
+ setBalanceRevalidating(true);
2102
+ const balance2 = yield fetchBalanceHandler(address);
2103
+ console.log("----- refresh balance -----", balance2);
2104
+ setBalance(() => balance2);
2105
+ setBalanceRevalidating(false);
2106
+ } catch (e) {
2107
+ console.warn("----- refresh balance error -----", e);
2108
+ setBalanceRevalidating(false);
2109
+ setBalance(() => "0");
2110
+ }
2111
+ }),
2112
+ [state, balanceRevalidating]
2113
+ );
2114
+ const fetchBalances = useCallback((tokens) => __async(void 0, null, function* () {
2115
+ const tasks = [];
2116
+ console.log("fetch balances ---->>>>", tokens);
2117
+ for (const token of tokens) {
2118
+ if (isNativeToken(token.address)) {
2119
+ continue;
2120
+ }
2121
+ tasks.push(account5.assetsManager.getBalanceByAddress(token.address));
2122
+ }
2123
+ const balances = yield Promise.all(tasks);
2124
+ console.log("----- get balances from tokens -----", balances);
2125
+ }), []);
2126
+ const fetchAllowance = useCallback(
2127
+ (address) => __async(void 0, null, function* () {
2128
+ if (!address)
2129
+ return;
2130
+ if (address && isNativeToken(address))
2131
+ return;
2132
+ if (allowanceRevalidating)
2133
+ return;
2134
+ setAllowanceRevalidating(true);
2135
+ const allowance2 = yield account5.assetsManager.getAllowance(address);
2136
+ console.log("----- refresh allowance -----", allowance2);
2137
+ setAllowance(() => allowance2);
2138
+ setAllowanceRevalidating(false);
2139
+ return allowance2;
2140
+ }),
2141
+ [allowanceRevalidating]
2142
+ );
2028
2143
  useEffect(() => {
2029
2144
  if (state.status < AccountStatusEnum.EnableTrading)
2030
2145
  return;
2031
- fetchBalance();
2032
- fetchAllowance();
2033
- }, [state]);
2146
+ fetchBalance(options == null ? void 0 : options.address);
2147
+ fetchAllowance(options == null ? void 0 : options.address);
2148
+ }, [state.status, options == null ? void 0 : options.address]);
2034
2149
  const approve = useCallback(
2035
2150
  (amount) => {
2036
2151
  return account5.assetsManager.approve(amount).then((result) => {
@@ -2045,7 +2160,6 @@ var useDeposit = () => {
2045
2160
  const deposit = useCallback(
2046
2161
  (amount) => {
2047
2162
  return account5.assetsManager.deposit(amount).then((res) => {
2048
- console.log("----- deposit -----", res);
2049
2163
  setAllowance((value) => new Decimal(value).sub(amount).toString());
2050
2164
  setBalance((value) => new Decimal(value).sub(amount).toString());
2051
2165
  return res;
@@ -2056,8 +2170,12 @@ var useDeposit = () => {
2056
2170
  return {
2057
2171
  balance,
2058
2172
  allowance,
2173
+ balanceRevalidating,
2174
+ allowanceRevalidating,
2059
2175
  approve,
2060
- deposit
2176
+ deposit,
2177
+ fetchBalances,
2178
+ fetchBalance: fetchBalanceHandler
2061
2179
  };
2062
2180
  };
2063
2181
  var useWalletSubscription = (options) => {