@orderly.network/hooks 2.9.1 → 2.10.0-alpha.1

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,9 +1,9 @@
1
1
  import { get, WS, mutate as mutate$1 } from '@orderly.network/net';
2
- import useSWR__default, { mutate } from 'swr';
3
- import * as useSWR from 'swr';
4
- export { useSWR as swr };
2
+ import useSWR5__default, { mutate } from 'swr';
3
+ import * as useSWR5 from 'swr';
4
+ export { useSWR5 as swr };
5
5
  export { unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
6
- import { TesnetTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, EMPTY_LIST, EMPTY_OBJECT, ARBITRUM_TESTNET_CHAINID, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, ETHEREUM_MAINNET_CHAINID, DEPOSIT_FEE_RATE, LedgerWalletKey, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
6
+ import { TesnetTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, AlgoOrderType, AlgoOrderRootType, OrderStatus, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, EMPTY_LIST, EMPTY_OBJECT, isNativeTokenChecker, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, ChainNamespace, MaxUint256, DEPOSIT_FEE_RATE, ETHEREUM_MAINNET_CHAINID, LedgerWalletKey, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
7
7
  import React2, { createContext, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
8
8
  import { zero, windowGuard, getTimestamp, getGlobalObject, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, getBBOType, camelCaseToUnderscoreCase, commify, todpIfNeed, getTPSLDirection } from '@orderly.network/utils';
9
9
  import useSWRMutation from 'swr/mutation';
@@ -38,9 +38,9 @@ var __export = (target, all) => {
38
38
  // src/version.ts
39
39
  if (typeof window !== "undefined") {
40
40
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
41
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.9.1";
41
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.10.0-alpha.1";
42
42
  }
43
- var version_default = "2.9.1";
43
+ var version_default = "2.10.0-alpha.1";
44
44
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
45
45
  var noCacheConfig = {
46
46
  dedupingInterval: 0,
@@ -79,7 +79,7 @@ var useQuery = (query, options) => {
79
79
  if (typeof apiBaseUrl === "undefined") {
80
80
  throw new SDKError("please add OrderlyConfigProvider to your app");
81
81
  }
82
- return useSWR__default(
82
+ return useSWR5__default(
83
83
  query,
84
84
  (url, init2) => fetcher(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init2, {
85
85
  formatter
@@ -465,7 +465,7 @@ var usePrivateQuery = (query, options) => {
465
465
  const { formatter, ...swrOptions } = options || {};
466
466
  const { state } = useAccount();
467
467
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
468
- return useSWR__default(
468
+ return useSWR5__default(
469
469
  () => query && (state.status >= AccountStatusEnum.EnableTrading || state.status === AccountStatusEnum.EnableTradingWithoutConnected) ? [query, state.accountId] : null,
470
470
  (url, init2) => {
471
471
  return fetcher(url, init2, { formatter });
@@ -934,7 +934,7 @@ function useSubAccountQuery(query, options) {
934
934
  const { formatter, accountId, ...swrOptions } = options || {};
935
935
  const { state, account: account9 } = useAccount();
936
936
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
937
- return useSWR__default(
937
+ return useSWR5__default(
938
938
  () => accountId && (state.status >= AccountStatusEnum.EnableTrading || state.status === AccountStatusEnum.EnableTradingWithoutConnected) ? [query, accountId] : null,
939
939
  (url, init2) => {
940
940
  return fetcher(url, init2, { formatter });
@@ -2762,7 +2762,7 @@ var usePreLoadData = () => {
2762
2762
  if (swapSupportInfo || !enableSwapDeposit) return;
2763
2763
  fetchSwapSupport();
2764
2764
  }, [swapSupportInfo, enableSwapDeposit]);
2765
- const { data: systemInfo } = useSWR__default(
2765
+ const { data: systemInfo } = useSWR5__default(
2766
2766
  "/v1/public/system_info",
2767
2767
  async (url, init2) => {
2768
2768
  const data = await fetch(
@@ -4061,6 +4061,29 @@ var useOpenInterest = (symbol) => {
4061
4061
  };
4062
4062
  });
4063
4063
  };
4064
+ var useMarkPriceStore = create((set, get3) => ({
4065
+ markPrices: {},
4066
+ // orderBook: {},
4067
+ // ask_bid: [],
4068
+ actions: {
4069
+ updateMarkPrice: (markPrice) => {
4070
+ set({
4071
+ markPrices: markPrice
4072
+ });
4073
+ },
4074
+ getMarkPriceBySymbol: (symbol) => {
4075
+ return get3().markPrices[symbol];
4076
+ }
4077
+ }
4078
+ }));
4079
+ var useMarkPriceBySymbol = (symbol) => useMarkPriceStore((state) => state.actions.getMarkPriceBySymbol(symbol));
4080
+ var useMarkPriceActions = () => useMarkPriceStore((state) => state.actions);
4081
+
4082
+ // src/orderly/useMarkPricesStream.ts
4083
+ var useMarkPricesStream = () => {
4084
+ const data = useMarkPriceStore((state) => state.markPrices);
4085
+ return { data };
4086
+ };
4064
4087
 
4065
4088
  // src/orderly/useTickerStream.ts
4066
4089
  var useTickerStream = (symbol) => {
@@ -4096,10 +4119,13 @@ var useTickerStream = (symbol) => {
4096
4119
  unsubscribe?.();
4097
4120
  };
4098
4121
  }, [symbol]);
4099
- const { data: markPrice } = useMarkPrice(symbol);
4122
+ const { data: markPrices } = useMarkPricesStream();
4100
4123
  const { data: indexPrice } = useIndexPrice(symbol);
4101
4124
  const { data: openInterest } = useOpenInterest(symbol);
4102
4125
  const marketMap = useMarketMap();
4126
+ const markPrice = useMemo(() => {
4127
+ return markPrices?.[symbol];
4128
+ }, [markPrices, symbol]);
4103
4129
  const value = useMemo(() => {
4104
4130
  if (!info) return null;
4105
4131
  if (!ticker || ticker.symbol !== symbol) return info;
@@ -4668,29 +4694,6 @@ function get24hChange2(close, open) {
4668
4694
  return new Decimal(close).minus(open).div(open).toNumber();
4669
4695
  }
4670
4696
  }
4671
- var useMarkPriceStore = create((set, get3) => ({
4672
- markPrices: {},
4673
- // orderBook: {},
4674
- // ask_bid: [],
4675
- actions: {
4676
- updateMarkPrice: (markPrice) => {
4677
- set({
4678
- markPrices: markPrice
4679
- });
4680
- },
4681
- getMarkPriceBySymbol: (symbol) => {
4682
- return get3().markPrices[symbol];
4683
- }
4684
- }
4685
- }));
4686
- var useMarkPriceBySymbol = (symbol) => useMarkPriceStore((state) => state.actions.getMarkPriceBySymbol(symbol));
4687
- var useMarkPriceActions = () => useMarkPriceStore((state) => state.actions);
4688
-
4689
- // src/orderly/useMarkPricesStream.ts
4690
- var useMarkPricesStream = () => {
4691
- const data = useMarkPriceStore((state) => state.markPrices);
4692
- return { data };
4693
- };
4694
4697
  var useIndexPriceStore = create((set) => ({
4695
4698
  indexPrices: {},
4696
4699
  actions: {
@@ -7225,20 +7228,22 @@ var useMarginRatio = () => {
7225
7228
  }, [rows, notional]);
7226
7229
  return { marginRatio, currentLeverage, mmr, maintenanceMargin };
7227
7230
  };
7228
- var TestNetWhiteList = [
7231
+ var TESTNET_WHITE_LIST = [
7229
7232
  ARBITRUM_TESTNET_CHAINID,
7230
7233
  SOLANA_TESTNET_CHAINID,
7231
7234
  MONAD_TESTNET_CHAINID,
7232
7235
  ABSTRACT_TESTNET_CHAINID,
7233
7236
  BSC_TESTNET_CHAINID
7234
7237
  ];
7238
+ var TESTNET_WHITE_CHAINS = TESTNET_WHITE_LIST.map((id) => ({
7239
+ id
7240
+ }));
7235
7241
  function useChains(networkId, options = {}) {
7236
- const { pick: pickField, ...swrOptions } = options;
7242
+ const { pick: pickField } = options;
7237
7243
  const {
7238
7244
  filteredChains: allowedChains,
7239
- configStore,
7240
7245
  customChains,
7241
- chainTransformer
7246
+ dataAdapter
7242
7247
  } = useContext(OrderlyContext);
7243
7248
  const filterFun = useRef(options?.filter);
7244
7249
  filterFun.current = options?.filter;
@@ -7248,7 +7253,6 @@ function useChains(networkId, options = {}) {
7248
7253
  const testTokenChainsRes = useTestTokenStore((state) => state.data);
7249
7254
  const chainInfos = useMainnetChainsStore((state) => state.data);
7250
7255
  const testChainInfos = useTestnetChainsStore((state) => state.data);
7251
- const { swapChains, swapChainsError } = useSwapChains();
7252
7256
  const chains = useMemo(() => {
7253
7257
  if (!tokenChainsRes || !testTokenChainsRes || !chainInfos || !testChainInfos) {
7254
7258
  return [];
@@ -7256,17 +7260,15 @@ function useChains(networkId, options = {}) {
7256
7260
  const mainnetChains = formatChains({
7257
7261
  tokenChains: tokenChainsRes,
7258
7262
  chainInfos,
7259
- swapChains,
7260
7263
  filter: filterFun.current,
7261
7264
  mainnet: true,
7262
- chainTransformer
7265
+ resolveChains: dataAdapter?.chainsList
7263
7266
  });
7264
7267
  const testnetChains = formatChains({
7265
7268
  tokenChains: testTokenChainsRes,
7266
7269
  chainInfos: testChainInfos,
7267
- swapChains,
7268
7270
  mainnet: false,
7269
- chainTransformer
7271
+ resolveChains: dataAdapter?.chainsList
7270
7272
  });
7271
7273
  let mainnetArr = needFetchFromAPI ? mainnetChains : customChains?.mainnet;
7272
7274
  let testnetArr = needFetchFromAPI ? testnetChains : customChains?.testnet;
@@ -7279,7 +7281,7 @@ function useChains(networkId, options = {}) {
7279
7281
  mainnetArr = filterByAllowedChains(mainnetArr, allowedChains?.mainnet);
7280
7282
  testnetArr = filterByAllowedChains(
7281
7283
  testnetArr,
7282
- allowedChains?.testnet ?? TestNetWhiteList.map((id) => ({ id }))
7284
+ allowedChains?.testnet ?? TESTNET_WHITE_CHAINS
7283
7285
  );
7284
7286
  if (!!pickField) {
7285
7287
  testnetArr = testnetArr.map((item) => item[pickField]);
@@ -7304,15 +7306,14 @@ function useChains(networkId, options = {}) {
7304
7306
  customChains,
7305
7307
  pickField,
7306
7308
  allowedChains,
7307
- swapChains,
7308
- chainTransformer
7309
+ dataAdapter
7309
7310
  ]);
7310
7311
  const findByChainId = useCallback(
7311
7312
  (chainId, field) => {
7312
7313
  const chain = chainsMap.current.get(chainId);
7313
7314
  if (chain) {
7314
7315
  chain.nativeToken = chain.token_infos?.find(
7315
- (item) => item.address === nativeTokenAddress
7316
+ (item) => isNativeTokenChecker(item.address)
7316
7317
  ) || {
7317
7318
  symbol: chain.network_infos?.currency_symbol
7318
7319
  };
@@ -7336,7 +7337,7 @@ function useChains(networkId, options = {}) {
7336
7337
  {
7337
7338
  findByChainId,
7338
7339
  checkChainSupport,
7339
- error: tokenError || swapChainsError
7340
+ error: tokenError
7340
7341
  }
7341
7342
  ];
7342
7343
  }
@@ -7352,70 +7353,23 @@ function filterByAllowedChains(chains, allowedChains) {
7352
7353
  if (!allowedChains) {
7353
7354
  return chains;
7354
7355
  }
7355
- return chains.filter(
7356
- (chain) => allowedChains.some(
7357
- (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
7358
- )
7359
- );
7360
- }
7361
- function useSwapChains() {
7362
- const { enableSwapDeposit } = useContext(OrderlyContext);
7363
- const { data: swapChainsRes, error: swapChainsError } = useSwapSupportStore();
7364
- const swapChains = useMemo(() => {
7365
- if (!enableSwapDeposit || !swapChainsRes || !swapChainsRes.data) {
7366
- return [];
7367
- }
7368
- const data = swapChainsRes.data;
7369
- return Object.keys(data).map((key) => {
7370
- const chain = data[key];
7371
- const { network_infos, token_infos } = chain;
7372
- const networkInfos = {
7373
- ...network_infos,
7374
- // swap deposit will use shortName to get swap info
7375
- shortName: key,
7376
- cross_chain_router: network_infos?.woofi_dex_cross_chain_router,
7377
- depositor: network_infos?.woofi_dex_depositor,
7378
- est_txn_mins: network_infos?.est_txn_mins
7379
- };
7380
- const nativeToken = token_infos.find(
7381
- (item) => item.symbol === network_infos.currency_symbol
7382
- );
7383
- if (nativeToken) {
7384
- networkInfos.currency_decimal = nativeToken.decimals;
7385
- } else {
7386
- networkInfos.currency_decimal = 18;
7387
- }
7388
- const tokenInfos = token_infos?.filter((item) => item.swap_enable).map((item) => {
7389
- const { woofi_dex_precision, ...rest } = item;
7390
- return {
7391
- ...rest,
7392
- precision: woofi_dex_precision
7393
- };
7394
- });
7395
- return {
7396
- network_infos: networkInfos,
7397
- token_infos: tokenInfos || []
7398
- };
7399
- });
7400
- }, [enableSwapDeposit, swapChainsRes]);
7401
- return { swapChains, swapChainsError };
7356
+ return allowedChains.map((allowedChain) => {
7357
+ return chains.find(
7358
+ (chain) => parseInt(chain.network_infos?.chain_id) === allowedChain.id
7359
+ );
7360
+ }).filter((chain) => !!chain);
7402
7361
  }
7403
- function formatChains({
7404
- chainInfos = [],
7405
- tokenChains = [],
7406
- swapChains = [],
7407
- filter,
7408
- mainnet,
7409
- chainTransformer
7410
- }) {
7362
+ function formatChains(options) {
7363
+ const {
7364
+ chainInfos = [],
7365
+ tokenChains = [],
7366
+ filter,
7367
+ mainnet,
7368
+ resolveChains
7369
+ } = options;
7411
7370
  const chains = [];
7412
7371
  for (const chainInfo of chainInfos) {
7413
7372
  const chainId = Number(chainInfo.chain_id);
7414
- const swapChainInfo = swapChains.find(
7415
- (item) => item.network_infos.chain_id === chainId
7416
- );
7417
- const swapNetworkInfo = swapChainInfo?.network_infos;
7418
- const swapTokenInfos = swapChainInfo?.token_infos || [];
7419
7373
  const {
7420
7374
  name,
7421
7375
  public_rpc_url,
@@ -7424,7 +7378,6 @@ function formatChains({
7424
7378
  explorer_base_url,
7425
7379
  vault_address
7426
7380
  } = chainInfo;
7427
- const { shortName, cross_chain_router, depositor, est_txn_mins } = swapNetworkInfo || {};
7428
7381
  const network_infos = {
7429
7382
  name,
7430
7383
  chain_id: chainId,
@@ -7435,32 +7388,21 @@ function formatChains({
7435
7388
  currency_decimal,
7436
7389
  bridge_enable: true,
7437
7390
  explorer_base_url,
7438
- // swap field
7439
- shortName: shortName ?? name,
7440
- cross_chain_router,
7441
- depositor,
7442
- est_txn_mins,
7391
+ shortName: name,
7443
7392
  vault_address
7444
7393
  };
7445
- const usdcSwapToken = swapTokenInfos.find(
7446
- (item) => item.symbol === "USDC"
7447
- );
7448
7394
  const tokenInfos = tokenChains.filter(
7449
7395
  (item) => item.chain_details.some((item2) => Number(item2.chain_id) === chainId)
7450
7396
  ).map((item) => {
7451
7397
  const chain = item.chain_details.find(
7452
7398
  (item2) => Number(item2.chain_id) === chainId
7453
7399
  );
7454
- const swapToken = swapTokenInfos.find(
7455
- (swapItem) => swapItem.symbol === item.token
7456
- );
7457
7400
  return {
7458
7401
  symbol: item.token,
7459
7402
  // if contract_address is not exist, use nativeTokenAddress to place holder
7460
7403
  address: chain?.contract_address || nativeTokenAddress,
7461
7404
  /** chain decimals */
7462
7405
  decimals: chain?.decimals,
7463
- // chain_decimals: chain?.decimals,
7464
7406
  /** token decimals */
7465
7407
  token_decimal: item?.decimals,
7466
7408
  precision: item.decimals,
@@ -7472,31 +7414,20 @@ function formatChains({
7472
7414
  discount_factor: item.discount_factor,
7473
7415
  haircut: item.haircut,
7474
7416
  user_max_qty: item.user_max_qty,
7475
- is_collateral: item.is_collateral,
7476
- // if source token is swap token, and usdc is swap token, set swap_enable to true
7477
- swap_enable: !!swapToken?.swap_enable && usdcSwapToken?.swap_enable
7417
+ is_collateral: item.is_collateral
7478
7418
  };
7479
7419
  });
7480
- const swapTokens = usdcSwapToken?.swap_enable ? swapTokenInfos?.filter((item) => {
7481
- return !tokenInfos?.some((token) => token.symbol === item.symbol);
7482
- }) : [];
7483
7420
  const _chain = {
7484
7421
  network_infos,
7485
- token_infos: [...tokenInfos, ...swapTokens]
7422
+ token_infos: tokenInfos
7486
7423
  };
7487
7424
  if (typeof filter === "function") {
7488
7425
  if (!filter(_chain)) continue;
7489
7426
  }
7490
7427
  chains.push(_chain);
7491
7428
  }
7492
- if (typeof chainTransformer === "function") {
7493
- return chainTransformer({
7494
- chains,
7495
- chainInfos,
7496
- tokenChains,
7497
- swapChains,
7498
- mainnet
7499
- });
7429
+ if (typeof resolveChains === "function") {
7430
+ return resolveChains(chains);
7500
7431
  }
7501
7432
  return chains;
7502
7433
  }
@@ -7744,128 +7675,32 @@ var useWithdraw = (options) => {
7744
7675
  };
7745
7676
  };
7746
7677
  var useDeposit = (options) => {
7747
- const networkId = useConfig("networkId");
7748
- const [balanceRevalidating, setBalanceRevalidating] = useState(false);
7749
- const [allowanceRevalidating, setAllowanceRevalidating] = useState(false);
7750
- const [_, { findByChainId }] = useChains(void 0);
7751
7678
  const [quantity, setQuantity] = useState("");
7752
- const [depositFee, setDepositFee] = useState(0n);
7753
- const [depositFeeRevalidating, setDepositFeeRevalidating] = useState(false);
7754
- const [balance, setBalance] = useState("0");
7755
- const [allowance, setAllowance] = useState("0");
7756
- const balanceRef = useRef("");
7757
- const currentAddressRef = useRef();
7758
7679
  const { account: account9, state } = useAccount();
7759
7680
  const { track: track2 } = useTrack();
7760
- const prevAddress = useRef();
7761
- const getBalanceListener = useRef();
7762
- const targetChain = useMemo(() => {
7763
- let chain;
7764
- if (networkId === "testnet") {
7765
- chain = findByChainId(
7766
- isTestnet(options.srcChainId) ? options.srcChainId : ARBITRUM_TESTNET_CHAINID
7767
- );
7768
- } else {
7769
- chain = findByChainId(options.srcChainId);
7770
- if (!chain?.network_infos?.bridgeless) {
7771
- chain = findByChainId(ARBITRUM_MAINNET_CHAINID);
7772
- }
7773
- }
7774
- return chain;
7775
- }, [networkId, findByChainId, options.srcChainId]);
7681
+ const targetChain = useTargetChain(options.srcChainId);
7776
7682
  const dst = useMemo(() => {
7777
- const USDC = targetChain?.token_infos.find(
7778
- (token) => token.symbol === "USDC"
7683
+ const symbol = options.dstToken || "USDC";
7684
+ const targetToken = targetChain?.token_infos.find(
7685
+ (token) => token.symbol === symbol
7779
7686
  );
7780
7687
  return {
7781
- symbol: "USDC",
7782
- address: USDC?.address,
7783
- decimals: USDC?.decimals,
7688
+ symbol,
7689
+ address: targetToken?.address,
7690
+ decimals: targetToken?.decimals,
7784
7691
  chainId: targetChain?.network_infos.chain_id,
7785
7692
  network: targetChain?.network_infos.shortName
7786
7693
  };
7787
- }, [targetChain]);
7694
+ }, [targetChain, options.dstToken]);
7788
7695
  const isNativeToken = useMemo(
7789
- () => isNativeTokenChecker(options.address || ""),
7696
+ () => isNativeTokenChecker(options.address),
7790
7697
  [options.address]
7791
7698
  );
7792
- const fetchBalanceHandler = useCallback(
7793
- async (address, decimals, token) => {
7794
- let balance2;
7795
- try {
7796
- if (address && isNativeTokenChecker(address)) {
7797
- balance2 = await account9.assetsManager.getNativeBalance({
7798
- decimals
7799
- });
7800
- } else {
7801
- balance2 = await account9.assetsManager.getBalance(address, {
7802
- decimals
7803
- });
7804
- }
7805
- } catch (err) {
7806
- if (ignoreBalanceError({
7807
- // TODO: use token params instead of options.srcToken
7808
- token: token || options.srcToken,
7809
- chainNamespace: account9.walletAdapter?.chainNamespace,
7810
- err
7811
- })) {
7812
- return "0";
7813
- }
7814
- throw err;
7815
- }
7816
- return balance2;
7817
- },
7818
- [options.srcToken, account9]
7819
- );
7820
- const fetchBalances = useCallback(async (tokens) => {
7821
- const tasks = [];
7822
- for (const token of tokens) {
7823
- tasks.push(
7824
- fetchBalanceHandler(token.address, token?.decimals, token.symbol)
7825
- );
7826
- }
7827
- const results = await Promise.allSettled(tasks);
7828
- const balances = {};
7829
- for (const [index, balance2] of results.entries()) {
7830
- if (balance2.status === "fulfilled") {
7831
- balances[tokens[index].symbol] = balance2.value;
7832
- }
7833
- }
7834
- return balances;
7835
- }, []);
7836
- const getAllowance = async (inputs) => {
7837
- const { address, vaultAddress: vaultAddress2, decimals } = inputs;
7838
- const key = `${address}-${vaultAddress2}`;
7839
- if (prevAddress.current === key) return;
7840
- if (!address || !vaultAddress2) return;
7841
- if (isNativeTokenChecker(address)) return;
7842
- prevAddress.current = key;
7843
- const allowance2 = await account9.assetsManager.getAllowance({
7844
- address,
7845
- vaultAddress: vaultAddress2,
7846
- decimals
7847
- });
7848
- setAllowance(allowance2);
7849
- return allowance2;
7850
- };
7851
- const getAllowanceByDefaultAddress = async (inputs) => {
7852
- const { address, decimals } = inputs;
7853
- if (prevAddress.current === address) return;
7854
- if (!address || isNativeTokenChecker(address)) return;
7855
- prevAddress.current = address;
7856
- const allowance2 = await account9.assetsManager.getAllowance({
7857
- address,
7858
- decimals,
7859
- vaultAddress
7860
- });
7861
- setAllowance(allowance2);
7862
- return allowance2;
7863
- };
7864
7699
  const vaultAddress = useMemo(() => {
7865
- if (dst.chainId !== options.srcChainId) {
7700
+ if (dst?.chainId !== options.srcChainId) {
7866
7701
  return options.crossChainRouteAddress;
7867
7702
  }
7868
- if (options.srcToken !== (options.dstToken || dst.symbol)) {
7703
+ if (options.srcToken !== options.dstToken) {
7869
7704
  return options.depositorAddress;
7870
7705
  }
7871
7706
  return targetChain?.network_infos.vault_address;
@@ -7878,103 +7713,43 @@ var useDeposit = (options) => {
7878
7713
  options.depositorAddress,
7879
7714
  targetChain
7880
7715
  ]);
7881
- const queryBalance = useDebouncedCallback(
7882
- (address, decimals) => {
7883
- fetchBalanceHandler(address, decimals).then((balance2) => {
7884
- setBalance(balance2);
7885
- setBalanceRevalidating(false);
7886
- });
7887
- },
7888
- 100
7889
- );
7890
- const queryAllowance = useDebouncedCallback(
7891
- (inputs) => {
7892
- getAllowance(inputs);
7893
- },
7894
- 100
7895
- );
7896
- useEffect(() => {
7897
- if (state.status < AccountStatusEnum.Connected) return;
7898
- setBalanceRevalidating(true);
7899
- queryBalance(options.address, options.decimals);
7900
- if (account9.walletAdapter?.chainNamespace === ChainNamespace.solana) {
7901
- setAllowance(
7902
- account9.walletAdapter.formatUnits(MaxUint256, options.decimals)
7903
- );
7904
- return;
7905
- }
7906
- if (vaultAddress && options.address) {
7907
- queryAllowance({
7908
- address: options.address,
7909
- decimals: options.decimals,
7910
- vaultAddress
7911
- });
7912
- } else {
7913
- getAllowanceByDefaultAddress({
7914
- address: options.address,
7915
- decimals: options.decimals
7916
- });
7917
- }
7918
- }, [
7919
- state.status,
7920
- options.address,
7921
- options.decimals,
7922
- account9.address,
7923
- vaultAddress
7924
- ]);
7925
- const updateAllowanceWhenTxSuccess = useCallback(
7926
- (txHash) => {
7927
- return account9.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
7928
- if (receipt.status === 1) {
7929
- account9.assetsManager.getAllowance({
7930
- address: options.address,
7931
- decimals: options.decimals,
7932
- vaultAddress
7933
- }).then((allowance2) => {
7934
- setAllowance(allowance2);
7935
- });
7936
- }
7937
- });
7938
- },
7939
- [account9, options.address, options.decimals, vaultAddress]
7940
- );
7941
- const enquireAllowance = useCallback(async () => {
7942
- if (isNativeToken) {
7943
- return;
7944
- }
7945
- if (!options.address) {
7946
- throw new Error("address is required");
7947
- }
7948
- const _allowance = await account9.assetsManager.getAllowance({
7949
- address: options.address,
7950
- vaultAddress,
7951
- decimals: options.decimals
7952
- });
7953
- setAllowance(_allowance);
7954
- if (new Decimal(quantity).greaterThan(_allowance)) {
7955
- throw new SDKError("Insufficient allowance");
7956
- }
7957
- return _allowance;
7958
- }, [
7959
- account9,
7960
- options.address,
7961
- options.decimals,
7716
+ const {
7717
+ balance,
7718
+ balanceRevalidating,
7719
+ fetchBalance,
7720
+ fetchBalances,
7721
+ setBalance
7722
+ } = useBalance({
7723
+ address: options.address,
7724
+ decimals: options.decimals,
7725
+ srcToken: options.srcToken,
7726
+ account: account9,
7727
+ status: state.status
7728
+ });
7729
+ const {
7730
+ allowance,
7731
+ allowanceRevalidating,
7732
+ updateAllowanceWhenTxSuccess,
7733
+ enquireAllowance
7734
+ } = useAllowance({
7735
+ address: options.address,
7736
+ decimals: options.decimals,
7962
7737
  vaultAddress,
7738
+ account: account9,
7739
+ status: state.status,
7963
7740
  quantity,
7964
- isNativeToken
7965
- ]);
7966
- const checkIfChainTokenNeedRestApprove = useCallback(
7967
- (chainId, token) => {
7968
- if (chainId !== ETHEREUM_MAINNET_CHAINID) {
7969
- return false;
7970
- }
7971
- if (token !== "USDT") {
7972
- return false;
7973
- }
7974
- return true;
7975
- },
7976
- []
7977
- );
7741
+ chainId: dst?.chainId
7742
+ });
7743
+ const { depositFee, depositFeeRevalidating } = useDepositFee({
7744
+ quantity,
7745
+ account: account9,
7746
+ targetChain,
7747
+ decimals: options.decimals,
7748
+ dstToken: options.dstToken,
7749
+ vaultAddress,
7750
+ isNativeToken,
7751
+ dst
7752
+ });
7978
7753
  const resetApprove = useCallback(
7979
7754
  async (tokenAddress, decimal, vaultAddress2) => {
7980
7755
  const result = await account9.assetsManager.approve({
@@ -7983,20 +7758,9 @@ var useDeposit = (options) => {
7983
7758
  vaultAddress: vaultAddress2,
7984
7759
  decimals: decimal
7985
7760
  });
7986
- const txResult = await account9.walletAdapter?.pollTransactionReceiptWithBackoff(
7987
- result.hash
7988
- );
7989
- if (txResult && txResult.status === 1) {
7990
- account9.assetsManager.getAllowance({
7991
- address: tokenAddress,
7992
- decimals: decimal,
7993
- vaultAddress: vaultAddress2
7994
- }).then((allowance2) => {
7995
- setAllowance(allowance2);
7996
- });
7997
- }
7761
+ await updateAllowanceWhenTxSuccess(result.hash);
7998
7762
  },
7999
- []
7763
+ [account9, updateAllowanceWhenTxSuccess]
8000
7764
  );
8001
7765
  const approve = useCallback(
8002
7766
  async (amount) => {
@@ -8033,7 +7797,6 @@ var useDeposit = (options) => {
8033
7797
  options.decimals,
8034
7798
  vaultAddress,
8035
7799
  updateAllowanceWhenTxSuccess,
8036
- checkIfChainTokenNeedRestApprove,
8037
7800
  resetApprove
8038
7801
  ]
8039
7802
  );
@@ -8079,104 +7842,287 @@ var useDeposit = (options) => {
8079
7842
  isNativeToken,
8080
7843
  vaultAddress
8081
7844
  ]);
8082
- const loopGetBalance = async (timeout) => {
8083
- if (getBalanceListener.current) {
8084
- clearTimeout(getBalanceListener.current);
8085
- }
8086
- const time = timeout ?? (account9.walletAdapter?.chainNamespace === ChainNamespace.solana ? 1e4 : 3e3);
8087
- if (balanceRef.current === "") {
8088
- setBalanceRevalidating(true);
8089
- }
8090
- currentAddressRef.current = options.address;
8091
- getBalanceListener.current = setTimeout(async () => {
7845
+ return {
7846
+ balance,
7847
+ allowance,
7848
+ /** deposit fee, unit: wei */
7849
+ depositFee,
7850
+ balanceRevalidating,
7851
+ allowanceRevalidating,
7852
+ depositFeeRevalidating,
7853
+ isNativeToken,
7854
+ dst,
7855
+ targetChain,
7856
+ /** input quantiy */
7857
+ quantity,
7858
+ /** set input quantity */
7859
+ setQuantity,
7860
+ approve,
7861
+ deposit,
7862
+ fetchBalance,
7863
+ fetchBalances
7864
+ };
7865
+ };
7866
+ function useBalance(options) {
7867
+ const { srcToken, address, decimals, account: account9, status } = options;
7868
+ const [balance, setBalance] = useState("0");
7869
+ const fetchBalance = useCallback(
7870
+ async (address2, decimals2) => {
8092
7871
  try {
8093
- const balance2 = await fetchBalanceHandler(
8094
- options.address,
8095
- options.decimals
8096
- );
8097
- setBalance(balance2);
8098
- balanceRef.current = balance2;
8099
- loopGetBalance();
7872
+ if (isNativeTokenChecker(address2)) {
7873
+ return account9.assetsManager.getNativeBalance({
7874
+ decimals: decimals2
7875
+ });
7876
+ }
7877
+ return account9.assetsManager.getBalance(address2, {
7878
+ decimals: decimals2
7879
+ });
8100
7880
  } catch (err) {
8101
- if (currentAddressRef.current !== options.address) return;
8102
- loopGetBalance(1e3);
8103
- } finally {
8104
- if (balanceRef.current !== "" && currentAddressRef.current === options.address) {
8105
- setBalanceRevalidating(false);
7881
+ if (ignoreBalanceError({
7882
+ chainNamespace: account9.walletAdapter?.chainNamespace,
7883
+ err
7884
+ })) {
7885
+ return "0";
8106
7886
  }
7887
+ throw err;
8107
7888
  }
8108
- }, time);
7889
+ },
7890
+ [srcToken, account9]
7891
+ );
7892
+ const fetchBalances = useCallback(
7893
+ async (tokens) => {
7894
+ return account9.assetsManager.getBalances(tokens);
7895
+ },
7896
+ [account9]
7897
+ );
7898
+ const key = useMemo(() => {
7899
+ if (!address || status < AccountStatusEnum.Connected) {
7900
+ return null;
7901
+ }
7902
+ return ["balance", address, decimals];
7903
+ }, [status, address, decimals]);
7904
+ const fetcher4 = useCallback(async () => {
7905
+ if (!address) {
7906
+ return "0";
7907
+ }
7908
+ const balance2 = await fetchBalance(address, decimals);
7909
+ return balance2;
7910
+ }, [address, decimals, fetchBalance]);
7911
+ const refreshInterval = useMemo(() => {
7912
+ return account9.walletAdapter?.chainNamespace === ChainNamespace.solana ? 1e4 : 3e3;
7913
+ }, [account9]);
7914
+ const { data: swrBalance, isLoading: balanceRevalidating } = useSWR5__default(
7915
+ key,
7916
+ fetcher4,
7917
+ {
7918
+ revalidateOnFocus: true,
7919
+ refreshInterval,
7920
+ errorRetryCount: 10
7921
+ }
7922
+ );
7923
+ useEffect(() => {
7924
+ if (swrBalance !== void 0) {
7925
+ setBalance(swrBalance || "0");
7926
+ }
7927
+ }, [swrBalance]);
7928
+ return {
7929
+ balance,
7930
+ balanceRevalidating,
7931
+ setBalance,
7932
+ fetchBalance,
7933
+ fetchBalances
8109
7934
  };
8110
- const getDepositFee = useCallback(
8111
- async (quantity2) => {
8112
- return account9.assetsManager.getDepositFee({
8113
- amount: quantity2,
8114
- chain: targetChain?.network_infos,
8115
- decimals: options.decimals,
8116
- token: options.srcToken,
8117
- address: options.address
7935
+ }
7936
+ function useAllowance(options) {
7937
+ const {
7938
+ address,
7939
+ decimals,
7940
+ vaultAddress,
7941
+ account: account9,
7942
+ status,
7943
+ quantity,
7944
+ chainId
7945
+ } = options;
7946
+ const [allowance, setAllowance] = useState("0");
7947
+ const fetchAllowance = useCallback(
7948
+ async (options2) => {
7949
+ const { address: address2, decimals: decimals2, vaultAddress: vaultAddress2 } = options2;
7950
+ if (!address2 || !decimals2 || !vaultAddress2) {
7951
+ return "0";
7952
+ }
7953
+ if (isNativeTokenChecker(address2) || account9.walletAdapter?.chainNamespace === ChainNamespace.solana) {
7954
+ return account9.walletAdapter?.formatUnits(MaxUint256, decimals2);
7955
+ }
7956
+ const allowance2 = await account9.assetsManager.getAllowance({
7957
+ address: address2,
7958
+ vaultAddress: vaultAddress2,
7959
+ decimals: decimals2
8118
7960
  });
7961
+ return allowance2;
8119
7962
  },
8120
- [account9, targetChain, options.decimals, options.srcToken, options.address]
7963
+ [account9]
8121
7964
  );
8122
- const enquiryDepositFee = useCallback(() => {
8123
- if (isNaN(Number(quantity)) || !quantity || Number(quantity) === 0) {
8124
- setDepositFee(0n);
8125
- setDepositFeeRevalidating(false);
8126
- return;
7965
+ const key = useMemo(() => {
7966
+ if (!address || !decimals || !vaultAddress || status < AccountStatusEnum.Connected) {
7967
+ return null;
8127
7968
  }
8128
- setDepositFeeRevalidating(true);
8129
- getDepositFee(quantity).then((res = 0n) => {
8130
- const fee = BigInt(
8131
- new Decimal(res.toString()).mul(DEPOSIT_FEE_RATE).toFixed(0, Decimal.ROUND_UP).toString()
8132
- );
8133
- setDepositFee(fee);
8134
- }).catch((error) => {
8135
- }).finally(() => {
8136
- setDepositFeeRevalidating(false);
8137
- });
8138
- }, [quantity]);
8139
- useEffect(() => {
8140
- enquiryDepositFee();
8141
- }, [quantity]);
7969
+ return ["allowance", address, vaultAddress, decimals];
7970
+ }, [status, address, vaultAddress, decimals, account9]);
7971
+ const refreshInterval = useMemo(() => {
7972
+ return account9.walletAdapter?.chainNamespace === ChainNamespace.solana ? 1e4 : 3e3;
7973
+ }, [account9, chainId]);
7974
+ const fetcher4 = useCallback(async () => {
7975
+ return fetchAllowance({ address, decimals, vaultAddress });
7976
+ }, [address, decimals, vaultAddress, fetchAllowance]);
7977
+ const {
7978
+ data: swrAllowance,
7979
+ isLoading: allowanceRevalidating,
7980
+ mutate: mutateAllowance
7981
+ } = useSWR5__default(key, fetcher4, {
7982
+ revalidateOnFocus: true,
7983
+ refreshInterval,
7984
+ errorRetryCount: 10
7985
+ });
8142
7986
  useEffect(() => {
8143
- if (!options.address) {
8144
- return;
7987
+ if (swrAllowance !== void 0) {
7988
+ setAllowance(swrAllowance || "0");
8145
7989
  }
8146
- currentAddressRef.current = options.address;
8147
- setBalance("0");
8148
- balanceRef.current = "";
8149
- setBalanceRevalidating(false);
8150
- loopGetBalance(0);
8151
- return () => {
8152
- if (getBalanceListener.current) {
8153
- clearTimeout(getBalanceListener.current);
8154
- }
8155
- };
8156
- }, [options.address, options.decimals]);
7990
+ }, [swrAllowance]);
7991
+ const updateAllowanceWhenTxSuccess = useCallback(
7992
+ (txHash) => {
7993
+ return account9.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
7994
+ if (receipt.status === 1) {
7995
+ mutateAllowance();
7996
+ }
7997
+ });
7998
+ },
7999
+ [account9]
8000
+ );
8001
+ const enquireAllowance = useCallback(async () => {
8002
+ const _allowance = await fetchAllowance({
8003
+ address,
8004
+ decimals,
8005
+ vaultAddress
8006
+ });
8007
+ setAllowance(_allowance);
8008
+ if (new Decimal(quantity).greaterThan(_allowance)) {
8009
+ throw new SDKError("Insufficient allowance");
8010
+ }
8011
+ return _allowance;
8012
+ }, [account9, address, decimals, vaultAddress, quantity]);
8157
8013
  return {
8158
- /** orderly support chain dst */
8159
- dst,
8160
- balance,
8161
8014
  allowance,
8162
- isNativeToken,
8163
- balanceRevalidating,
8164
8015
  allowanceRevalidating,
8165
- /** input quantiy */
8166
- quantity,
8167
- /** orderly deposit fee, unit: wei */
8168
- depositFee,
8169
- /** enquiring depositFee status on chain */
8170
- depositFeeRevalidating,
8171
- approve,
8172
- deposit,
8173
- fetchBalance: fetchBalanceHandler,
8174
- fetchBalances,
8175
- /** set input quantity */
8176
- setQuantity,
8177
- targetChain
8016
+ updateAllowanceWhenTxSuccess,
8017
+ enquireAllowance
8178
8018
  };
8179
- };
8019
+ }
8020
+ function useDepositFee(options) {
8021
+ const {
8022
+ quantity,
8023
+ account: account9,
8024
+ targetChain,
8025
+ decimals,
8026
+ dstToken,
8027
+ vaultAddress,
8028
+ isNativeToken,
8029
+ dst
8030
+ } = options;
8031
+ const getDepositFee = useCallback(
8032
+ async (quantity2) => {
8033
+ if (!quantity2 || Number(quantity2) === 0 || isNaN(Number(quantity2))) {
8034
+ return 0n;
8035
+ }
8036
+ const depositFee2 = await account9.assetsManager.getDepositFee({
8037
+ amount: quantity2,
8038
+ chain: targetChain?.network_infos,
8039
+ decimals,
8040
+ token: dstToken,
8041
+ // TODO: when swap deposit, dstToken address is not same as src token address
8042
+ address: dst?.address
8043
+ });
8044
+ let estimatedGasFee = 0n;
8045
+ try {
8046
+ const inputs = {
8047
+ amount: quantity2,
8048
+ fee: depositFee2,
8049
+ decimals,
8050
+ token: dstToken,
8051
+ address: dst?.address,
8052
+ vaultAddress
8053
+ };
8054
+ estimatedGasFee = isNativeToken ? await account9.assetsManager.estimateNativeDepositGasFee(inputs) : await account9.assetsManager.estimateDepositGasFee(inputs);
8055
+ } catch (error) {
8056
+ estimatedGasFee = 0n;
8057
+ }
8058
+ return depositFee2 + estimatedGasFee;
8059
+ },
8060
+ [
8061
+ account9,
8062
+ targetChain,
8063
+ decimals,
8064
+ dstToken,
8065
+ dst?.address,
8066
+ vaultAddress,
8067
+ isNativeToken,
8068
+ dst
8069
+ ]
8070
+ );
8071
+ const key = useMemo(() => {
8072
+ if (!dst?.address || !decimals || !vaultAddress || !dstToken || !quantity || !targetChain?.network_infos?.chain_id) {
8073
+ return null;
8074
+ }
8075
+ return [
8076
+ "depositFee",
8077
+ dst?.address,
8078
+ vaultAddress,
8079
+ dstToken,
8080
+ decimals,
8081
+ targetChain?.network_infos?.chain_id,
8082
+ quantity
8083
+ ];
8084
+ }, [quantity, targetChain, decimals, dstToken, dst, vaultAddress]);
8085
+ const fetcher4 = useCallback(async () => {
8086
+ const res = await getDepositFee(quantity);
8087
+ return res;
8088
+ }, [getDepositFee, quantity]);
8089
+ const {
8090
+ data,
8091
+ isValidating: depositFeeRevalidating,
8092
+ mutate: mutateDepositFee
8093
+ } = useSWR5__default(key, fetcher4, {
8094
+ revalidateOnFocus: true
8095
+ });
8096
+ const depositFee = useMemo(() => {
8097
+ const fee = data ?? 0n;
8098
+ return BigInt(
8099
+ new Decimal(fee.toString()).mul(DEPOSIT_FEE_RATE).toFixed(0, Decimal.ROUND_UP).toString()
8100
+ );
8101
+ }, [data]);
8102
+ return { depositFee, depositFeeRevalidating, mutateDepositFee };
8103
+ }
8104
+ function useTargetChain(srcChainId) {
8105
+ const networkId = useConfig("networkId");
8106
+ const [_, { findByChainId }] = useChains(void 0);
8107
+ const targetChain = useMemo(() => {
8108
+ let chain;
8109
+ if (networkId === "testnet") {
8110
+ chain = findByChainId(
8111
+ isTestnet(srcChainId) ? srcChainId : ARBITRUM_TESTNET_CHAINID
8112
+ );
8113
+ } else {
8114
+ chain = findByChainId(srcChainId);
8115
+ if (!chain?.network_infos?.bridgeless) {
8116
+ chain = findByChainId(ARBITRUM_MAINNET_CHAINID);
8117
+ }
8118
+ }
8119
+ return chain;
8120
+ }, [networkId, findByChainId, srcChainId]);
8121
+ return targetChain;
8122
+ }
8123
+ function checkIfChainTokenNeedRestApprove(chainId, token) {
8124
+ return chainId === ETHEREUM_MAINNET_CHAINID && token === "USDT";
8125
+ }
8180
8126
  function ignoreBalanceError(options) {
8181
8127
  const { chainNamespace, err } = options;
8182
8128
  return chainNamespace === ChainNamespace.solana && err?.name === "TokenAccountNotFoundError";
@@ -11418,7 +11364,6 @@ var OrderlyConfigProvider = (props) => {
11418
11364
  const {
11419
11365
  configStore,
11420
11366
  keyStore,
11421
- // getWalletAdapter,
11422
11367
  walletAdapters,
11423
11368
  brokerId,
11424
11369
  brokerName,
@@ -11427,7 +11372,6 @@ var OrderlyConfigProvider = (props) => {
11427
11372
  chainFilter,
11428
11373
  customChains,
11429
11374
  enableSwapDeposit = false,
11430
- chainTransformer,
11431
11375
  dataAdapter,
11432
11376
  notification,
11433
11377
  amplitudeConfig,
@@ -11503,7 +11447,6 @@ var OrderlyConfigProvider = (props) => {
11503
11447
  enableSwapDeposit,
11504
11448
  defaultOrderbookTickSizes,
11505
11449
  defaultOrderbookSymbolDepths,
11506
- chainTransformer,
11507
11450
  dataAdapter,
11508
11451
  notification,
11509
11452
  amplitudeConfig,
@@ -11521,7 +11464,6 @@ var OrderlyConfigProvider = (props) => {
11521
11464
  defaultOrderbookSymbolDepths,
11522
11465
  dataAdapter,
11523
11466
  notification,
11524
- chainTransformer,
11525
11467
  amplitudeConfig,
11526
11468
  orderMetadata
11527
11469
  ]);