@orderly.network/hooks 0.0.53 → 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,25 +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
- var usePreLoadData = (onSuccess) => {
321
+ var usePreLoadData = () => {
322
322
  const { configStore } = useContext(OrderlyContext);
323
- useSWR(
323
+ const { error: swapSupportError, data: swapSupportData } = useSWR(
324
324
  `${configStore.get("swapSupportApiUrl")}/swap_support`,
325
325
  (url) => fetch(url).then((res) => res.json()),
326
326
  {
327
- revalidateOnFocus: false,
328
- // suspense: true,
329
- onSuccess: (data, key, config) => {
330
- onSuccess("chains_fetch");
331
- }
327
+ revalidateOnFocus: false
332
328
  }
333
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
+ };
334
340
  };
335
341
  var useEventEmitter = (channel) => {
336
342
  return useConstant(() => {
@@ -1898,7 +1904,6 @@ var useMarketTradeStream = (symbol, options = {}) => {
1898
1904
  unsubscript == null ? void 0 : unsubscript();
1899
1905
  };
1900
1906
  }, [symbol]);
1901
- console.log("trades", trades);
1902
1907
  return { data: trades, isLoading };
1903
1908
  };
1904
1909
  var useMarginRatio = () => {
@@ -1925,56 +1930,106 @@ var useChains = (networkId, options = {}) => {
1925
1930
  const _a = options, { filter, pick, crossEnabled, wooSwapEnabled } = _a, swrOptions = __objRest(_a, ["filter", "pick", "crossEnabled", "wooSwapEnabled"]);
1926
1931
  const { configStore } = useContext(OrderlyContext);
1927
1932
  const field = options == null ? void 0 : options.pick;
1928
- const { data } = useSWR(
1929
- // () =>
1930
- // wooSwapEnabled
1931
- // ? `${configStore.get("swapSupportApiUrl")}/swap_support`
1932
- // : null,
1933
- `${configStore.get("swapSupportApiUrl")}/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`,
1934
1937
  (url) => fetch(url).then((res) => res.json()),
1935
1938
  __spreadValues({
1936
1939
  revalidateOnFocus: false,
1937
1940
  revalidateOnReconnect: false
1938
1941
  }, swrOptions)
1939
1942
  );
1940
- const { data: orderlyChains } = useQuery("/v1/public/token");
1943
+ const { data: orderlyChains, error: tokenError } = useQuery("/v1/public/token");
1941
1944
  const chains = useMemo(() => {
1942
- if (!data || !data.data || !orderlyChains)
1943
- return data;
1944
- let testnetArr = [];
1945
- let mainnetArr = [];
1946
- Object.keys(data.data).forEach((key) => {
1947
- const item = __spreadProps(__spreadValues({}, data.data[key]), { name: key, priority: 1 });
1948
- if (typeof (options == null ? void 0 : options.filter) === "function") {
1949
- if (!options.filter(item))
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
+ });
1979
+ });
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))
1950
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
+ }
2006
+ });
2007
+ if (orderlyChainIds.size > 0) {
2008
+ testnetArr = [...orderlyChainsArr, ...testnetArr];
1951
2009
  }
1952
- if (item.network_infos.mainnet) {
1953
- mainnetArr.push(field ? item[field] : item);
1954
- } else {
1955
- testnetArr.push(field ? item[field] : item);
2010
+ if (networkId === "mainnet") {
2011
+ return mainnetArr;
1956
2012
  }
1957
- });
1958
- if (networkId === "mainnet") {
1959
- return mainnetArr;
1960
- }
1961
- if (networkId === "testnet") {
1962
- return testnetArr;
2013
+ if (networkId === "testnet") {
2014
+ return testnetArr;
2015
+ }
2016
+ return {
2017
+ testnet: testnetArr,
2018
+ mainnet: mainnetArr
2019
+ };
1963
2020
  }
1964
- return {
1965
- testnet: testnetArr,
1966
- mainnet: mainnetArr
1967
- };
1968
2021
  }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
1969
2022
  const findByChainId = useCallback(
1970
- (chainId) => {
1971
- if (!data || !data.data)
1972
- return void 0;
1973
- 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;
1974
2029
  },
1975
- [data]
2030
+ [chains, map.current]
1976
2031
  );
1977
- return [chains, { findByChainId }];
2032
+ return [chains, { findByChainId, error: swapSupportError || tokenError }];
1978
2033
  };
1979
2034
  var useChain = (token) => {
1980
2035
  const { data, isLoading } = useQuery("/v1/public/token");
@@ -2019,25 +2074,78 @@ var useWithdraw = () => {
2019
2074
  }, [usdc, unsettledPnL]);
2020
2075
  return { withdraw, isLoading, maxAmount, availableBalance, unsettledPnL };
2021
2076
  };
2022
- 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);
2023
2082
  const [balance, setBalance] = useState("0");
2024
2083
  const [allowance, setAllowance] = useState("0");
2025
2084
  const { account: account5, state } = useAccount();
2026
- const fetchBalance = useCallback(() => __async(void 0, null, function* () {
2027
- const balance2 = yield account5.assetsManager.getBalance();
2028
- setBalance(() => balance2);
2029
- }), [state]);
2030
- const fetchAllowance = useCallback(() => __async(void 0, null, function* () {
2031
- const allowance2 = yield account5.assetsManager.getAllowance();
2032
- setAllowance(() => allowance2);
2033
- 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;
2034
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
+ );
2035
2143
  useEffect(() => {
2036
2144
  if (state.status < AccountStatusEnum.EnableTrading)
2037
2145
  return;
2038
- fetchBalance();
2039
- fetchAllowance();
2040
- }, [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]);
2041
2149
  const approve = useCallback(
2042
2150
  (amount) => {
2043
2151
  return account5.assetsManager.approve(amount).then((result) => {
@@ -2052,7 +2160,6 @@ var useDeposit = () => {
2052
2160
  const deposit = useCallback(
2053
2161
  (amount) => {
2054
2162
  return account5.assetsManager.deposit(amount).then((res) => {
2055
- console.log("----- deposit -----", res);
2056
2163
  setAllowance((value) => new Decimal(value).sub(amount).toString());
2057
2164
  setBalance((value) => new Decimal(value).sub(amount).toString());
2058
2165
  return res;
@@ -2063,8 +2170,12 @@ var useDeposit = () => {
2063
2170
  return {
2064
2171
  balance,
2065
2172
  allowance,
2173
+ balanceRevalidating,
2174
+ allowanceRevalidating,
2066
2175
  approve,
2067
- deposit
2176
+ deposit,
2177
+ fetchBalances,
2178
+ fetchBalance: fetchBalanceHandler
2068
2179
  };
2069
2180
  };
2070
2181
  var useWalletSubscription = (options) => {