@orderly.network/hooks 2.4.2-alpha.0 → 2.5.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
@@ -20,7 +20,7 @@ import { EthersProvider } from '@orderly.network/web3-provider-ethers';
20
20
  import { create } from 'zustand';
21
21
  import { immer } from 'zustand/middleware/immer';
22
22
  import { pathOr, omit, prop, pick, compose, head, mergeDeepRight, min, max, isNil, propOr, path, lensIndex, over } from 'ramda';
23
- import { order, account, positions } from '@orderly.network/perp';
23
+ import { account, order, positions } from '@orderly.network/perp';
24
24
  import useSWRSubscription from 'swr/subscription';
25
25
  import { useDebouncedCallback, useThrottledCallback } from 'use-debounce';
26
26
  export * from 'use-debounce';
@@ -36,9 +36,9 @@ var __export = (target, all) => {
36
36
  // src/version.ts
37
37
  if (typeof window !== "undefined") {
38
38
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
39
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.4.2-alpha.0";
39
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.5.0-alpha.1";
40
40
  }
41
- var version_default = "2.4.2-alpha.0";
41
+ var version_default = "2.5.0-alpha.1";
42
42
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
43
43
  var OrderlyContext = createContext({
44
44
  // configStore: new MemoryConfigStore(),
@@ -105,20 +105,20 @@ var useAccountInstance = () => {
105
105
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
106
106
  );
107
107
  }
108
- const account7 = useConstant(() => {
109
- let account8 = SimpleDI.get("account");
110
- if (!account8) {
111
- account8 = new Account(
108
+ const account9 = useConstant(() => {
109
+ let account10 = SimpleDI.get("account");
110
+ if (!account10) {
111
+ account10 = new Account(
112
112
  configStore,
113
113
  keyStore,
114
114
  // getWalletAdapter,
115
115
  walletAdapters
116
116
  );
117
- SimpleDI.registerByName("account", account8);
117
+ SimpleDI.registerByName("account", account10);
118
118
  }
119
- return account8;
119
+ return account10;
120
120
  });
121
- return account7;
121
+ return account9;
122
122
  };
123
123
  var fetcher2 = (url, options) => {
124
124
  const init2 = {
@@ -142,7 +142,7 @@ var useMutation = (url, method = "POST", options) => {
142
142
  if (!url.startsWith("http")) {
143
143
  fullUrl = `${apiBaseUrl}${url}`;
144
144
  }
145
- const account7 = useAccountInstance();
145
+ const account9 = useAccountInstance();
146
146
  const { trigger, data, error, reset, isMutating } = useSWRMutation(
147
147
  fullUrl,
148
148
  // method === "POST" ? fetcher : deleteFetcher,
@@ -160,7 +160,7 @@ var useMutation = (url, method = "POST", options) => {
160
160
  url: newUrl,
161
161
  data: data2
162
162
  };
163
- const signer = account7.signer;
163
+ const signer = account9.signer;
164
164
  const signature = await signer.sign(payload, getTimestamp());
165
165
  return trigger(
166
166
  {
@@ -169,7 +169,7 @@ var useMutation = (url, method = "POST", options) => {
169
169
  method,
170
170
  signature: {
171
171
  ...signature,
172
- "orderly-account-id": account7.accountId
172
+ "orderly-account-id": account9.accountId
173
173
  }
174
174
  },
175
175
  options2
@@ -191,9 +191,9 @@ var signatureMiddleware = (useSWRNext) => {
191
191
  try {
192
192
  const extendedFetcher = async (args) => {
193
193
  const url = Array.isArray(args) ? args[0] : args;
194
- const account7 = SimpleDI.get("account");
194
+ const account9 = SimpleDI.get("account");
195
195
  const fullUrl = `${apiBaseUrl}${url}`;
196
- const signer = account7.signer;
196
+ const signer = account9.signer;
197
197
  const payload = {
198
198
  method: "GET",
199
199
  url
@@ -202,7 +202,7 @@ var signatureMiddleware = (useSWRNext) => {
202
202
  return fetcher4(fullUrl, {
203
203
  headers: {
204
204
  ...signature,
205
- "orderly-account-id": account7.accountId
205
+ "orderly-account-id": account9.accountId
206
206
  }
207
207
  });
208
208
  };
@@ -275,25 +275,25 @@ var useWS = () => {
275
275
  const { configStore } = useContext(OrderlyContext);
276
276
  const ws = useConstant(() => {
277
277
  let websocketClient = SimpleDI.get(WS_NAME);
278
- const account7 = SimpleDI.get(Account.instanceName);
278
+ const account9 = SimpleDI.get(Account.instanceName);
279
279
  if (!websocketClient) {
280
280
  websocketClient = new WS({
281
281
  networkId: configStore.get("networkId"),
282
282
  publicUrl: configStore.get("publicWsUrl"),
283
283
  privateUrl: configStore.get("privateWsUrl"),
284
284
  onSigntureRequest: async (accountId) => {
285
- const signer = account7.signer;
285
+ const signer = account9.signer;
286
286
  const timestamp = getTimestamp();
287
287
  const result = await signer.signText(timestamp.toString());
288
288
  return { ...result, timestamp };
289
289
  }
290
290
  });
291
- if ((account7.stateValue.status === AccountStatusEnum.EnableTrading || account7.stateValue.status === AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
292
- websocketClient.openPrivate(account7.accountId);
291
+ if ((account9.stateValue.status === AccountStatusEnum.EnableTrading || account9.stateValue.status === AccountStatusEnum.EnableTradingWithoutConnected) && account9.accountId) {
292
+ websocketClient.openPrivate(account9.accountId);
293
293
  }
294
- account7.on("change:status", (nextState) => {
295
- if ((nextState.status === AccountStatusEnum.EnableTrading || nextState.status === AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
296
- websocketClient.openPrivate(account7.accountId);
294
+ account9.on("change:status", (nextState) => {
295
+ if ((nextState.status === AccountStatusEnum.EnableTrading || nextState.status === AccountStatusEnum.EnableTradingWithoutConnected) && account9.accountId) {
296
+ websocketClient.openPrivate(account9.accountId);
297
297
  } else {
298
298
  websocketClient.closePrivate(1e3, "switch account");
299
299
  }
@@ -320,63 +320,63 @@ var useAccount = () => {
320
320
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
321
321
  );
322
322
  }
323
- const account7 = useAccountInstance();
324
- const [state, setState] = useState(account7.stateValue);
323
+ const account9 = useAccountInstance();
324
+ const [state, setState] = useState(account9.stateValue);
325
325
  const { track: track2 } = useTrack();
326
326
  const statusChangeHandler = (nextState) => {
327
327
  setState(() => nextState);
328
328
  };
329
329
  useEffect(() => {
330
- account7.on("change:status", statusChangeHandler);
330
+ account9.on("change:status", statusChangeHandler);
331
331
  return () => {
332
- account7.off("change:status", statusChangeHandler);
332
+ account9.off("change:status", statusChangeHandler);
333
333
  };
334
- }, [account7]);
334
+ }, [account9]);
335
335
  const createOrderlyKey = useCallback(
336
336
  async (remember) => {
337
337
  track2(TrackerEventName.signinSuccess, {
338
- network: account7.chainId,
338
+ network: account9.chainId,
339
339
  wallet: state.connectWallet?.name
340
340
  });
341
- return account7.createOrderlyKey(remember ? 365 : 30).then((res) => {
342
- return account7.restoreSubAccount().then((_) => {
341
+ return account9.createOrderlyKey(remember ? 365 : 30).then((res) => {
342
+ return account9.restoreSubAccount().then((_) => {
343
343
  return res;
344
344
  });
345
345
  });
346
346
  },
347
- [account7, state]
347
+ [account9, state]
348
348
  );
349
349
  const ws = useWS();
350
350
  const switchAccount = useCallback(
351
351
  async (accountId) => {
352
352
  ws.closePrivate(1e3, "switch account");
353
- return account7.switchAccount(accountId);
353
+ return account9.switchAccount(accountId);
354
354
  },
355
- [account7]
355
+ [account9]
356
356
  );
357
357
  const createAccount = useCallback(async () => {
358
- return account7.createAccount();
359
- }, [account7]);
358
+ return account9.createAccount();
359
+ }, [account9]);
360
360
  const createSubAccount = useCallback(
361
361
  async (description) => {
362
- return account7.createSubAccount(description);
362
+ return account9.createSubAccount(description);
363
363
  },
364
- [account7]
364
+ [account9]
365
365
  );
366
366
  const updateSubAccount = useCallback(
367
367
  async (value) => {
368
- return account7.updateSubAccount(value);
368
+ return account9.updateSubAccount(value);
369
369
  },
370
- [account7]
370
+ [account9]
371
371
  );
372
372
  const refreshSubAccountBalances = useCallback(() => {
373
- return account7.refreshSubAccountBalances();
374
- }, [account7]);
373
+ return account9.refreshSubAccountBalances();
374
+ }, [account9]);
375
375
  const isSubAccount = useMemo(() => {
376
376
  return state.accountId !== state.mainAccountId;
377
377
  }, [state]);
378
378
  return {
379
- account: account7,
379
+ account: account9,
380
380
  state,
381
381
  isSubAccount,
382
382
  isMainAccount: !isSubAccount,
@@ -1162,6 +1162,24 @@ var useAppStore = create()(
1162
1162
  }))
1163
1163
  );
1164
1164
  var useAccountInfo = () => useAppStore((state) => state.accountInfo);
1165
+ var useTokensInfoStore = create(
1166
+ (set) => ({
1167
+ tokensInfo: [],
1168
+ setTokensInfo(data) {
1169
+ set({ tokensInfo: data });
1170
+ }
1171
+ })
1172
+ );
1173
+ var useTokensInfo = () => {
1174
+ const tokensInfo = useTokensInfoStore((state) => state.tokensInfo);
1175
+ return tokensInfo;
1176
+ };
1177
+ var useTokenInfo = (token) => {
1178
+ const tokensInfo = useTokensInfo();
1179
+ return useMemo(() => {
1180
+ return tokensInfo?.find((item) => item.token === token);
1181
+ }, [tokensInfo, token]);
1182
+ };
1165
1183
 
1166
1184
  // src/orderly/calculator/baseCalculator.ts
1167
1185
  var BaseCalculator = class {
@@ -1229,6 +1247,7 @@ var CalculatorContext = class _CalculatorContext {
1229
1247
  this.accountInfo = useAppStore.getState().accountInfo;
1230
1248
  this.symbolsInfo = useAppStore.getState().symbolsInfo;
1231
1249
  this.fundingRates = useAppStore.getState().fundingRates;
1250
+ this.tokensInfo = useTokensInfoStore.getState().tokensInfo;
1232
1251
  }
1233
1252
  get(fn) {
1234
1253
  return fn(this.output);
@@ -1745,25 +1764,68 @@ function createGetter(data, depth = 2) {
1745
1764
  }
1746
1765
  });
1747
1766
  }
1748
-
1749
- // src/utils/parseHolding.ts
1750
- var parseHolding = (holding, markPrices) => {
1767
+ var parseHolding = (holding, indexPrices, tokensInfo) => {
1751
1768
  const nonUSDC = [];
1752
1769
  let USDC_holding = 0;
1753
1770
  holding.forEach((item) => {
1754
1771
  if (item.token === "USDC") {
1755
1772
  USDC_holding = item.holding;
1756
1773
  } else {
1774
+ const tokenInfo = tokensInfo.find(({ token }) => token === item.token);
1775
+ const {
1776
+ base_weight = 0,
1777
+ discount_factor = 0,
1778
+ user_max_qty = 0
1779
+ } = tokenInfo || {};
1780
+ const holdingQty = item?.holding ?? 0;
1781
+ const indexPrice = indexPrices[`PERP_${item.token}_USDC`] ?? 0;
1782
+ const collateralRatio4 = account.collateralRatio({
1783
+ baseWeight: base_weight,
1784
+ discountFactor: discount_factor,
1785
+ collateralQty: holdingQty,
1786
+ collateralCap: user_max_qty,
1787
+ indexPrice
1788
+ });
1757
1789
  nonUSDC.push({
1758
- holding: item.holding,
1759
- markPrice: markPrices[item.token] ?? 0,
1760
- // markPrice: 0,
1761
- discount: 0
1790
+ holding: holdingQty,
1791
+ indexPrice,
1792
+ collateralCap: user_max_qty,
1793
+ collateralRatio: collateralRatio4
1762
1794
  });
1763
1795
  }
1764
1796
  });
1765
1797
  return [USDC_holding, nonUSDC];
1766
1798
  };
1799
+ var useIndexPriceStore = create((set) => ({
1800
+ indexPrices: {},
1801
+ actions: {
1802
+ updateIndexPrice: (indexPrice) => {
1803
+ set({
1804
+ indexPrices: indexPrice
1805
+ });
1806
+ }
1807
+ }
1808
+ }));
1809
+
1810
+ // src/orderly/calculator/indexPrice.ts
1811
+ var IndexPriceCalculatorName = "indexPriceCalculator";
1812
+ var IndexPriceCalculator = class extends BaseCalculator {
1813
+ constructor() {
1814
+ super(...arguments);
1815
+ this.name = IndexPriceCalculatorName;
1816
+ }
1817
+ calc(scope, data, ctx) {
1818
+ return data;
1819
+ }
1820
+ update(data) {
1821
+ if (!data)
1822
+ return;
1823
+ useIndexPriceStore.getState().actions.updateIndexPrice(data);
1824
+ }
1825
+ static getValue() {
1826
+ return useIndexPriceStore.getState().indexPrices;
1827
+ }
1828
+ };
1767
1829
 
1768
1830
  // src/orderly/calculator/portfolio.ts
1769
1831
  var PortfolioCalculatorName = "portfolio";
@@ -1773,7 +1835,8 @@ var PortfolioCalculator = class extends BaseCalculator {
1773
1835
  this.name = PortfolioCalculatorName;
1774
1836
  }
1775
1837
  calc(scope, data, ctx) {
1776
- let markPrices, positions3;
1838
+ let markPrices;
1839
+ let indexPrices;
1777
1840
  const portfolio = this.getPortfolio(ctx);
1778
1841
  if (scope === "markPrice" /* MARK_PRICE */) {
1779
1842
  markPrices = data;
@@ -1782,7 +1845,14 @@ var PortfolioCalculator = class extends BaseCalculator {
1782
1845
  (cache) => cache[MarketCalculatorName]
1783
1846
  );
1784
1847
  }
1785
- positions3 = ctx.get(
1848
+ if (scope === "indexPrice" /* INDEX_PRICE */) {
1849
+ indexPrices = data;
1850
+ } else {
1851
+ indexPrices = ctx.get(
1852
+ (cache) => cache[IndexPriceCalculatorName]
1853
+ );
1854
+ }
1855
+ const positions3 = ctx.get(
1786
1856
  (output) => output.positionCalculator_all
1787
1857
  );
1788
1858
  let holding = portfolio.holding;
@@ -1804,25 +1874,40 @@ var PortfolioCalculator = class extends BaseCalculator {
1804
1874
  }
1805
1875
  const accountInfo = ctx.accountInfo;
1806
1876
  const symbolsInfo = ctx.symbolsInfo;
1877
+ const tokensInfo = ctx.tokensInfo;
1807
1878
  return this.format({
1808
1879
  holding,
1809
1880
  positions: positions3,
1810
1881
  markPrices,
1811
1882
  accountInfo,
1812
- symbolsInfo
1883
+ symbolsInfo,
1884
+ indexPrices,
1885
+ tokensInfo: tokensInfo ?? []
1813
1886
  });
1814
1887
  }
1815
1888
  getPortfolio(ctx) {
1816
1889
  return ctx.get((output) => output[this.name]) || useAppStore.getState().portfolio;
1817
1890
  }
1818
1891
  format(inputs) {
1819
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
1820
- if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo) {
1892
+ const {
1893
+ holding,
1894
+ positions: positions3,
1895
+ markPrices,
1896
+ indexPrices,
1897
+ accountInfo,
1898
+ symbolsInfo,
1899
+ tokensInfo
1900
+ } = inputs;
1901
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo) {
1821
1902
  return null;
1822
1903
  }
1823
1904
  const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
1824
1905
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
1825
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1906
+ const [USDC_holding, nonUSDC] = parseHolding(
1907
+ holding,
1908
+ indexPrices,
1909
+ tokensInfo
1910
+ );
1826
1911
  const usdc = holding.find((item) => item.token === "USDC");
1827
1912
  const totalCollateral = account.totalCollateral({
1828
1913
  USDCHolding: USDC_holding,
@@ -1877,36 +1962,6 @@ var PortfolioCalculator = class extends BaseCalculator {
1877
1962
  }
1878
1963
  }
1879
1964
  };
1880
- var useIndexPriceStore = create((set) => ({
1881
- indexPrices: {},
1882
- actions: {
1883
- updateIndexPrice: (indexPrice) => {
1884
- set({
1885
- indexPrices: indexPrice
1886
- });
1887
- }
1888
- }
1889
- }));
1890
-
1891
- // src/orderly/calculator/indexPrice.ts
1892
- var IndexPriceCalculatorName = "indexPriceCalculator";
1893
- var IndexPriceCalculator = class extends BaseCalculator {
1894
- constructor() {
1895
- super(...arguments);
1896
- this.name = IndexPriceCalculatorName;
1897
- }
1898
- calc(scope, data, ctx) {
1899
- return data;
1900
- }
1901
- update(data) {
1902
- if (!data)
1903
- return;
1904
- useIndexPriceStore.getState().actions.updateIndexPrice(data);
1905
- }
1906
- static getValue() {
1907
- return useIndexPriceStore.getState().indexPrices;
1908
- }
1909
- };
1910
1965
 
1911
1966
  // src/useCalculatorService.ts
1912
1967
  var useCalculatorService = () => {
@@ -3247,6 +3302,68 @@ var useLeverage = () => {
3247
3302
  maxLeverage: memoizedMaxLeverage
3248
3303
  };
3249
3304
  };
3305
+
3306
+ // src/orderly/useOdosQuote.ts
3307
+ var useOdosQuote = () => {
3308
+ return useMutation(`https://api.odos.xyz/sor/quote/v2`);
3309
+ };
3310
+ var { LTV, collateralRatio } = account;
3311
+ var useComputedLTV = (options = {}) => {
3312
+ const { input, token } = options;
3313
+ const isUSDC = token?.toUpperCase() === "USDC";
3314
+ const tokensInfo = useTokensInfo();
3315
+ const { usdc, data: holdingList = [] } = useHoldingStream();
3316
+ const { data: indexPrices } = useIndexPricesStream();
3317
+ const { unsettledPnL } = useCollateral();
3318
+ const usdcBalance = useMemo(() => {
3319
+ if (isUSDC && input) {
3320
+ return new Decimal(usdc?.holding ?? 0).add(input).toNumber();
3321
+ }
3322
+ return usdc?.holding ?? 0;
3323
+ }, [usdc?.holding, input, token, isUSDC]);
3324
+ const getAdjustedQty = useCallback(
3325
+ (item) => {
3326
+ if (input && item.token === token) {
3327
+ return new Decimal(item?.holding ?? 0).add(input).toNumber();
3328
+ }
3329
+ return item?.holding ?? 0;
3330
+ },
3331
+ [input, token]
3332
+ );
3333
+ const memoizedLTV = useMemo(() => {
3334
+ return LTV({
3335
+ usdcBalance,
3336
+ upnl: unsettledPnL,
3337
+ assets: holdingList.filter((h) => h.token.toUpperCase() !== "USDC").map((item) => {
3338
+ const indexPrice = indexPrices[`PERP_${item.token}_USDC`] ?? 0;
3339
+ const findToken = tokensInfo?.find((i) => i.token === item.token);
3340
+ const qty = getAdjustedQty(item);
3341
+ return {
3342
+ qty,
3343
+ indexPrice,
3344
+ weight: collateralRatio({
3345
+ baseWeight: findToken?.base_weight ?? 0,
3346
+ discountFactor: findToken?.discount_factor ?? 0,
3347
+ collateralCap: findToken?.user_max_qty ?? qty,
3348
+ collateralQty: qty,
3349
+ indexPrice
3350
+ })
3351
+ };
3352
+ })
3353
+ });
3354
+ }, [
3355
+ usdcBalance,
3356
+ unsettledPnL,
3357
+ holdingList,
3358
+ indexPrices,
3359
+ tokensInfo,
3360
+ getAdjustedQty
3361
+ ]);
3362
+ if (new Decimal(usdcBalance).add(new Decimal(unsettledPnL)).gte(zero)) {
3363
+ return 0;
3364
+ }
3365
+ return new Decimal(memoizedLTV).mul(100).toDecimalPlaces(2, Decimal.ROUND_DOWN).toNumber();
3366
+ };
3250
3367
  var useFundingRate = (symbol) => {
3251
3368
  if (!symbol) {
3252
3369
  throw new SDKError("Symbol is required");
@@ -4003,7 +4120,8 @@ function useChains(networkId, options = {}) {
4003
4120
  const {
4004
4121
  filteredChains: allowedChains,
4005
4122
  configStore,
4006
- customChains
4123
+ customChains,
4124
+ chainTransformer
4007
4125
  } = useContext(OrderlyContext);
4008
4126
  const filterFun = useRef(options?.filter);
4009
4127
  filterFun.current = options?.filter;
@@ -4014,7 +4132,7 @@ function useChains(networkId, options = {}) {
4014
4132
  revalidateOnReconnect: false,
4015
4133
  // If false, undefined data gets cached against the key.
4016
4134
  revalidateOnMount: true,
4017
- // dont duplicate a request w/ same key for 1hr
4135
+ // don't duplicate a request with the same key for 1hr
4018
4136
  dedupingInterval: 36e5,
4019
4137
  ...swrOptions
4020
4138
  };
@@ -4030,13 +4148,15 @@ function useChains(networkId, options = {}) {
4030
4148
  }
4031
4149
  );
4032
4150
  const brokerId = configStore.get("brokerId");
4151
+ const env = configStore.get("env");
4152
+ const brokerIdQuery = brokerId !== "orderly" ? `?broker_id=${brokerId}` : "";
4033
4153
  const needFetchFromAPI = options.forceAPI || !customChains;
4034
4154
  const { data: chainInfos, error: chainInfoErr } = useQuery(
4035
- needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
4155
+ needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerIdQuery}` : null,
4036
4156
  { ...commonSwrOpts }
4037
4157
  );
4038
4158
  const { data: testChainInfos, error: testChainInfoError } = useQuery(
4039
- needFetchFromAPI ? `https://testnet-api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
4159
+ needFetchFromAPI ? `https://testnet-api.orderly.org/v1/public/chain_info${brokerIdQuery}` : null,
4040
4160
  {
4041
4161
  ...commonSwrOpts,
4042
4162
  fallbackData: testnetChainFallback,
@@ -4044,35 +4164,34 @@ function useChains(networkId, options = {}) {
4044
4164
  }
4045
4165
  }
4046
4166
  );
4167
+ const { data: envChainInfos, error: envChainInfoError } = useQuery(
4168
+ needFetchFromAPI && env !== "prod" ? `/v1/public/chain_info${brokerIdQuery}` : null,
4169
+ commonSwrOpts
4170
+ );
4171
+ const { swapChains, swapChainsError } = useSwapChains();
4047
4172
  const chains = useMemo(() => {
4048
- const tokenChains = fillChainsInfo(
4049
- tokenChainsRes,
4050
- filterFun.current,
4051
- chainInfos
4052
- );
4053
- const testTokenChains = fillChainsInfo(
4054
- testTokenChainsRes,
4055
- void 0,
4056
- testChainInfos
4057
- );
4058
- let testnetArr = needFetchFromAPI ? filterAndUpdateChains(testTokenChains, testChainInfos, void 0, true) : customChains?.testnet;
4059
- tokenChains?.forEach((item) => {
4060
- const chainId = item.network_infos?.chain_id;
4061
- chainsMap.current.set(chainId, item);
4173
+ const mainnetChains = formatChains({
4174
+ tokenChains: tokenChainsRes,
4175
+ chainInfos,
4176
+ swapChains,
4177
+ filter: filterFun.current,
4178
+ mainnet: true,
4179
+ chainTransformer
4062
4180
  });
4063
- testnetArr.forEach((chain) => {
4181
+ const testnetChains = formatChains({
4182
+ tokenChains: testTokenChainsRes,
4183
+ chainInfos: formatTestnetChainInfos(testChainInfos, envChainInfos),
4184
+ swapChains,
4185
+ mainnet: false,
4186
+ chainTransformer
4187
+ });
4188
+ let mainnetArr = needFetchFromAPI ? mainnetChains : customChains?.mainnet;
4189
+ let testnetArr = needFetchFromAPI ? testnetChains : customChains?.testnet;
4190
+ testnetArr?.forEach((chain) => {
4064
4191
  chainsMap.current.set(chain.network_infos?.chain_id, chain);
4065
4192
  });
4066
- let mainnetArr = [];
4067
- mainnetArr = filterAndUpdateChains(
4068
- tokenChains,
4069
- chainInfos,
4070
- filterFun.current
4071
- );
4072
- mainnetArr = needFetchFromAPI ? mainnetArr : customChains?.mainnet;
4073
- mainnetArr.forEach((item) => {
4074
- const chainId = item.network_infos?.chain_id;
4075
- chainsMap.current.set(chainId, item);
4193
+ mainnetArr?.forEach((chain) => {
4194
+ chainsMap.current.set(chain.network_infos?.chain_id, chain);
4076
4195
  });
4077
4196
  mainnetArr = filterByAllowedChains(mainnetArr, allowedChains?.mainnet);
4078
4197
  testnetArr = filterByAllowedChains(
@@ -4101,7 +4220,10 @@ function useChains(networkId, options = {}) {
4101
4220
  testTokenChainsRes,
4102
4221
  customChains,
4103
4222
  pickField,
4104
- allowedChains
4223
+ allowedChains,
4224
+ swapChains,
4225
+ chainTransformer,
4226
+ envChainInfos
4105
4227
  ]);
4106
4228
  const findByChainId = useCallback(
4107
4229
  (chainId, field) => {
@@ -4132,7 +4254,7 @@ function useChains(networkId, options = {}) {
4132
4254
  {
4133
4255
  findByChainId,
4134
4256
  checkChainSupport,
4135
- error: tokenError
4257
+ error: tokenError || swapChainsError
4136
4258
  }
4137
4259
  ];
4138
4260
  }
@@ -4144,80 +4266,173 @@ function _checkChainSupport(chainId, chains) {
4144
4266
  return chain.network_infos.chain_id === chainId;
4145
4267
  });
4146
4268
  }
4147
- function fillChainsInfo(chains, filter, chainInfos) {
4148
- const _chains = [];
4149
- chains?.forEach((item) => {
4150
- item.chain_details.forEach((chain) => {
4151
- const chainId = Number(chain.chain_id);
4152
- const chainInfo = chainInfos?.find(
4153
- (item2) => item2.chain_id == chainId
4154
- );
4155
- const _chain = {
4156
- network_infos: {
4157
- name: chain.chain_name ?? chainInfo?.name ?? "--",
4158
- chain_id: chainId,
4159
- withdrawal_fee: chain.withdrawal_fee,
4160
- cross_chain_withdrawal_fee: chain.cross_chain_withdrawal_fee,
4161
- bridgeless: true
4162
- },
4163
- token_infos: [
4164
- {
4165
- symbol: item.token,
4166
- address: chain.contract_address,
4167
- decimals: chain.decimals,
4168
- display_name: chain.display_name
4169
- }
4170
- ]
4269
+ function filterByAllowedChains(chains, allowedChains) {
4270
+ if (!allowedChains) {
4271
+ return chains;
4272
+ }
4273
+ return chains.filter(
4274
+ (chain) => allowedChains.some(
4275
+ (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
4276
+ )
4277
+ );
4278
+ }
4279
+ function useSwapChains() {
4280
+ const { enableSwapDeposit } = useContext(OrderlyContext);
4281
+ const { data: swapChainsRes, error: swapChainsError } = useSWR__default(
4282
+ () => enableSwapDeposit ? "https://fi-api.woo.org/swap_support" : null,
4283
+ (url) => fetch(url).then((res) => res.json()),
4284
+ {
4285
+ revalidateIfStale: false,
4286
+ revalidateOnFocus: false,
4287
+ revalidateOnReconnect: false,
4288
+ // If false, undefined data gets cached against the key.
4289
+ revalidateOnMount: true,
4290
+ // dont duplicate a request w/ same key for 1hr
4291
+ dedupingInterval: 36e5
4292
+ }
4293
+ );
4294
+ const swapChains = useMemo(() => {
4295
+ if (!enableSwapDeposit || !swapChainsRes || !swapChainsRes.data) {
4296
+ return [];
4297
+ }
4298
+ const data = swapChainsRes.data;
4299
+ return Object.keys(data).map((key) => {
4300
+ const chain = data[key];
4301
+ const { network_infos, token_infos } = chain;
4302
+ const networkInfos = {
4303
+ ...network_infos,
4304
+ // swap deposit will use shortName to get swap info
4305
+ shortName: key,
4306
+ cross_chain_router: network_infos?.woofi_dex_cross_chain_router,
4307
+ depositor: network_infos?.woofi_dex_depositor,
4308
+ est_txn_mins: network_infos?.est_txn_mins
4171
4309
  };
4172
- if (typeof filter === "function") {
4173
- if (!filter(_chain))
4174
- return;
4310
+ const nativeToken = token_infos.find(
4311
+ (item) => item.symbol === network_infos.currency_symbol
4312
+ );
4313
+ if (nativeToken) {
4314
+ networkInfos.currency_decimal = nativeToken.decimals;
4315
+ } else {
4316
+ networkInfos.currency_decimal = 18;
4175
4317
  }
4176
- _chains.push(_chain);
4318
+ const tokenInfos = token_infos?.filter((item) => item.swap_enable).map((item) => {
4319
+ const { woofi_dex_precision, ...rest } = item;
4320
+ return {
4321
+ ...rest,
4322
+ precision: woofi_dex_precision
4323
+ };
4324
+ });
4325
+ return {
4326
+ network_infos: networkInfos,
4327
+ token_infos: tokenInfos || []
4328
+ };
4177
4329
  });
4178
- });
4179
- return _chains;
4330
+ }, [enableSwapDeposit, swapChainsRes]);
4331
+ return { swapChains, swapChainsError };
4180
4332
  }
4181
- function filterAndUpdateChains(chains, chainInfos, filter, isTestNet) {
4182
- const chainsMap = /* @__PURE__ */ new Map();
4183
- chains.forEach((chain) => {
4184
- const _chain = { ...chain };
4185
- const networkInfo = chainInfos?.find(
4186
- (item) => item.chain_id == chain.network_infos.chain_id
4333
+ function formatChains({
4334
+ chainInfos = [],
4335
+ tokenChains = [],
4336
+ swapChains = [],
4337
+ filter,
4338
+ mainnet,
4339
+ chainTransformer
4340
+ }) {
4341
+ const chains = [];
4342
+ for (const chainInfo of chainInfos) {
4343
+ const chainId = Number(chainInfo.chain_id);
4344
+ const swapChainInfo = swapChains.find(
4345
+ (item) => item.network_infos.chain_id === chainId
4187
4346
  );
4188
- if (networkInfo) {
4189
- const { name, public_rpc_url, currency_symbol, explorer_base_url } = networkInfo;
4190
- _chain.network_infos = {
4191
- ..._chain.network_infos,
4192
- name,
4193
- shortName: name,
4194
- public_rpc_url,
4195
- currency_symbol,
4196
- bridge_enable: true,
4197
- mainnet: !isTestNet,
4198
- explorer_base_url
4199
- // est_txn_mins: null,
4347
+ const swapNetworkInfo = swapChainInfo?.network_infos;
4348
+ const swapTokenInfos = swapChainInfo?.token_infos || [];
4349
+ const {
4350
+ name,
4351
+ public_rpc_url,
4352
+ currency_symbol,
4353
+ explorer_base_url,
4354
+ vault_address
4355
+ } = chainInfo;
4356
+ const { shortName, cross_chain_router, depositor, est_txn_mins } = swapNetworkInfo || {};
4357
+ const network_infos = {
4358
+ name,
4359
+ chain_id: chainId,
4360
+ bridgeless: true,
4361
+ mainnet,
4362
+ public_rpc_url,
4363
+ currency_symbol,
4364
+ bridge_enable: true,
4365
+ explorer_base_url,
4366
+ // swap field
4367
+ shortName: shortName ?? name,
4368
+ cross_chain_router,
4369
+ depositor,
4370
+ est_txn_mins,
4371
+ vault_address
4372
+ };
4373
+ const tokenInfos = tokenChains.filter(
4374
+ (item) => item.chain_details.some((item2) => Number(item2.chain_id) === chainId)
4375
+ ).map((item) => {
4376
+ const chain = item.chain_details.find(
4377
+ (item2) => Number(item2.chain_id) === chainId
4378
+ );
4379
+ return {
4380
+ symbol: item.token,
4381
+ // if contract_address is not exist, use nativeTokenAddress to place holder
4382
+ address: chain?.contract_address || nativeTokenAddress,
4383
+ /** chain decimals */
4384
+ decimals: chain?.decimals,
4385
+ // chain_decimals: chain?.decimals,
4386
+ /** token decimals */
4387
+ token_decimal: item?.decimals,
4388
+ precision: item.decimals,
4389
+ display_name: chain?.display_name,
4390
+ withdrawal_fee: chain?.withdrawal_fee,
4391
+ cross_chain_withdrawal_fee: chain?.cross_chain_withdrawal_fee,
4392
+ minimum_withdraw_amount: item.minimum_withdraw_amount,
4393
+ base_weight: item.base_weight,
4394
+ discount_factor: item.discount_factor,
4395
+ haircut: item.haircut,
4396
+ user_max_qty: item.user_max_qty,
4397
+ is_collateral: item.is_collateral,
4398
+ swap_enable: false
4200
4399
  };
4201
- }
4400
+ });
4401
+ const swapTokens = swapTokenInfos?.filter((item) => {
4402
+ return !tokenInfos?.some((token) => token.symbol === item.symbol);
4403
+ });
4404
+ const _chain = {
4405
+ network_infos,
4406
+ token_infos: [...tokenInfos, ...swapTokens]
4407
+ };
4202
4408
  if (typeof filter === "function") {
4203
4409
  if (!filter(_chain))
4204
- return;
4205
- }
4206
- if (networkInfo) {
4207
- chainsMap.set(chain.network_infos.chain_id, _chain);
4410
+ continue;
4208
4411
  }
4209
- });
4210
- return Array.from(chainsMap.values());
4412
+ chains.push(_chain);
4413
+ }
4414
+ if (typeof chainTransformer === "function") {
4415
+ return chainTransformer({
4416
+ chains,
4417
+ chainInfos,
4418
+ tokenChains,
4419
+ swapChains,
4420
+ mainnet
4421
+ });
4422
+ }
4423
+ return chains;
4211
4424
  }
4212
- function filterByAllowedChains(chains, allowedChains) {
4213
- if (!allowedChains) {
4214
- return chains;
4425
+ function formatTestnetChainInfos(chainInfos, envChainInfos) {
4426
+ if (!chainInfos || !envChainInfos || !Array.isArray(chainInfos) || !Array.isArray(envChainInfos)) {
4427
+ return chainInfos;
4215
4428
  }
4216
- return chains.filter(
4217
- (chain) => allowedChains.some(
4218
- (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
4219
- )
4220
- );
4429
+ return chainInfos.map((chain) => {
4430
+ const info = envChainInfos.find((item) => item.chain_id === chain.chain_id);
4431
+ if (info) {
4432
+ chain.vault_address = info.vault_address;
4433
+ }
4434
+ return chain;
4435
+ });
4221
4436
  }
4222
4437
  function useStorageChain() {
4223
4438
  const [chain, setChain] = useLocalStorage(ChainKey, null);
@@ -4239,9 +4454,10 @@ function useStorageChain() {
4239
4454
  var useChain = (token) => {
4240
4455
  const { data, isLoading } = useQuery("/v1/public/token");
4241
4456
  const chains = useMemo(() => {
4242
- if (!data)
4457
+ if (!data) {
4243
4458
  return null;
4244
- let item = data.find((chain) => chain.token === token);
4459
+ }
4460
+ const item = data.find((chain) => chain.token === token);
4245
4461
  if (item) {
4246
4462
  item.chain_details = item.chain_details.map((d) => {
4247
4463
  const chain = chainsInfoMap.get(Number(d.chain_id));
@@ -4308,19 +4524,72 @@ var useHoldingStream = () => {
4308
4524
  };
4309
4525
  };
4310
4526
 
4527
+ // src/orderly/useMaxWithdrawal.ts
4528
+ var { maxWithdrawalUSDC, maxWithdrawalOtherCollateral, collateralRatio: collateralRatio2 } = account;
4529
+ function useMaxWithdrawal(token) {
4530
+ const { unsettledPnL, freeCollateral } = useCollateral();
4531
+ const tokenInfo = useTokenInfo(token);
4532
+ const { data: indexPrices } = useIndexPricesStream();
4533
+ const { usdc, data: holdings = [] } = useHoldingStream();
4534
+ const holding = useMemo(() => {
4535
+ return holdings?.find((item) => item?.token === token);
4536
+ }, [holdings, token]);
4537
+ const usdcBalance = usdc?.holding ?? 0;
4538
+ const indexPrice = useMemo(() => {
4539
+ if (token === "USDC") {
4540
+ return 1;
4541
+ }
4542
+ const symbol = `PERP_${token}_USDC`;
4543
+ return indexPrices[symbol] ?? 0;
4544
+ }, [token, indexPrices]);
4545
+ const memoizedCollateralRatio = useMemo(() => {
4546
+ const { base_weight = 0, discount_factor = 0 } = tokenInfo || {};
4547
+ const holdingQty = holding?.holding ?? 0;
4548
+ return collateralRatio2({
4549
+ baseWeight: base_weight,
4550
+ discountFactor: discount_factor,
4551
+ collateralQty: holdingQty,
4552
+ collateralCap: tokenInfo?.user_max_qty ?? holdingQty,
4553
+ indexPrice
4554
+ });
4555
+ }, [holdings, tokenInfo, indexPrice, token, holding]);
4556
+ const maxAmount = useMemo(() => {
4557
+ if (token === "USDC") {
4558
+ return maxWithdrawalUSDC({
4559
+ USDCBalance: usdcBalance,
4560
+ freeCollateral,
4561
+ upnl: unsettledPnL ?? 0
4562
+ });
4563
+ }
4564
+ return maxWithdrawalOtherCollateral({
4565
+ collateralQty: holding?.holding ?? 0,
4566
+ freeCollateral,
4567
+ indexPrice,
4568
+ weight: memoizedCollateralRatio
4569
+ });
4570
+ }, [
4571
+ usdcBalance,
4572
+ freeCollateral,
4573
+ unsettledPnL,
4574
+ memoizedCollateralRatio,
4575
+ holdings,
4576
+ indexPrice,
4577
+ token,
4578
+ holding
4579
+ ]);
4580
+ return maxAmount;
4581
+ }
4582
+
4311
4583
  // src/orderly/useWithdraw.ts
4312
4584
  var useWithdraw = (options) => {
4313
- const { account: account7, state } = useAccount();
4585
+ const { srcChainId, token, decimals } = options;
4586
+ const { account: account9, state } = useAccount();
4314
4587
  const [isLoading, setIsLoading] = useState(false);
4315
4588
  const { unsettledPnL, availableBalance, freeCollateral } = useCollateral();
4316
4589
  const networkId = useConfig("networkId");
4317
4590
  const [_, { findByChainId }] = useChains(void 0);
4318
- useEventEmitter();
4319
4591
  const { track: track2 } = useTrack();
4320
- const { usdc } = useHoldingStream();
4321
- const maxAmount = useMemo(() => {
4322
- return freeCollateral;
4323
- }, [freeCollateral]);
4592
+ const maxAmount = useMaxWithdrawal(token);
4324
4593
  const availableWithdraw = useMemo(() => {
4325
4594
  if (unsettledPnL < 0) {
4326
4595
  return freeCollateral;
@@ -4332,19 +4601,19 @@ var useWithdraw = (options) => {
4332
4601
  let chain;
4333
4602
  if (networkId === "testnet") {
4334
4603
  chain = findByChainId(
4335
- isTestnet(options?.srcChainId) ? options?.srcChainId : ARBITRUM_TESTNET_CHAINID
4604
+ isTestnet(srcChainId) ? srcChainId : ARBITRUM_TESTNET_CHAINID
4336
4605
  );
4337
4606
  } else {
4338
- chain = findByChainId(options?.srcChainId);
4607
+ chain = findByChainId(srcChainId);
4339
4608
  if (!chain?.network_infos?.bridgeless) {
4340
4609
  chain = findByChainId(ARBITRUM_MAINNET_CHAINID);
4341
4610
  }
4342
4611
  }
4343
4612
  return chain;
4344
- }, [networkId, findByChainId, options?.srcChainId]);
4613
+ }, [networkId, findByChainId, srcChainId]);
4345
4614
  const dst = useMemo(() => {
4346
4615
  const USDC = targetChain?.token_infos.find(
4347
- (token) => token.symbol === "USDC"
4616
+ (token2) => token2.symbol === "USDC"
4348
4617
  );
4349
4618
  return {
4350
4619
  symbol: USDC?.display_name || "USDC",
@@ -4356,7 +4625,7 @@ var useWithdraw = (options) => {
4356
4625
  }, [targetChain]);
4357
4626
  const withdraw = useCallback(
4358
4627
  (inputs) => {
4359
- return account7.assetsManager.withdraw({ ...inputs, decimals: 6 }).then((res) => {
4628
+ return account9.assetsManager.withdraw({ ...inputs, decimals: decimals ?? 6 }).then((res) => {
4360
4629
  if (res.success) {
4361
4630
  track2(TrackerEventName.withdrawSuccess, {
4362
4631
  wallet: state?.connectWallet?.name,
@@ -4375,16 +4644,17 @@ var useWithdraw = (options) => {
4375
4644
  throw err;
4376
4645
  });
4377
4646
  },
4378
- [state, targetChain, state, options?.decimals]
4647
+ [state, targetChain, state, decimals]
4379
4648
  );
4380
4649
  return {
4381
4650
  dst,
4382
4651
  withdraw,
4383
4652
  isLoading,
4384
4653
  maxAmount,
4654
+ unsettledPnL,
4385
4655
  availableBalance,
4386
- availableWithdraw,
4387
- unsettledPnL
4656
+ /** @deprecated use maxAmount instead */
4657
+ availableWithdraw
4388
4658
  };
4389
4659
  };
4390
4660
  var useDeposit = (options) => {
@@ -4397,7 +4667,7 @@ var useDeposit = (options) => {
4397
4667
  const [depositFeeRevalidating, setDepositFeeRevalidating] = useState(false);
4398
4668
  const [balance, setBalance] = useState("0");
4399
4669
  const [allowance, setAllowance] = useState("0");
4400
- const { account: account7, state } = useAccount();
4670
+ const { account: account9, state } = useAccount();
4401
4671
  const { track: track2 } = useTrack();
4402
4672
  const prevAddress = useRef();
4403
4673
  const getBalanceListener = useRef();
@@ -4423,8 +4693,8 @@ var useDeposit = (options) => {
4423
4693
  symbol: "USDC",
4424
4694
  address: USDC?.address,
4425
4695
  decimals: USDC?.decimals,
4426
- chainId: targetChain?.network_infos?.chain_id,
4427
- network: targetChain?.network_infos?.shortName
4696
+ chainId: targetChain?.network_infos.chain_id,
4697
+ network: targetChain?.network_infos.shortName
4428
4698
  };
4429
4699
  }, [targetChain]);
4430
4700
  const isNativeToken = useMemo(
@@ -4434,12 +4704,12 @@ var useDeposit = (options) => {
4434
4704
  const fetchBalanceHandler = useCallback(
4435
4705
  async (address, decimals) => {
4436
4706
  let balance2;
4437
- if (!!address && isNativeTokenChecker(address)) {
4438
- balance2 = await account7.assetsManager.getNativeBalance({
4707
+ if (address && isNativeTokenChecker(address)) {
4708
+ balance2 = await account9.assetsManager.getNativeBalance({
4439
4709
  decimals
4440
4710
  });
4441
4711
  } else {
4442
- balance2 = await account7.assetsManager.getBalance(address, { decimals });
4712
+ balance2 = await account9.assetsManager.getBalance(address, { decimals });
4443
4713
  }
4444
4714
  return balance2;
4445
4715
  },
@@ -4465,29 +4735,30 @@ var useDeposit = (options) => {
4465
4735
  continue;
4466
4736
  }
4467
4737
  tasks.push(
4468
- account7.assetsManager.getBalanceByAddress(token.address, {
4738
+ account9.assetsManager.getBalance(token.address, {
4469
4739
  decimals: token?.decimals
4470
4740
  })
4471
4741
  );
4472
4742
  }
4473
- await Promise.all(tasks);
4743
+ const balances = await Promise.all(tasks);
4744
+ return balances;
4474
4745
  }, []);
4475
4746
  const getAllowance = async (inputs) => {
4476
- const { address, vaultAddress, decimals } = inputs;
4477
- const key = `${address}-${vaultAddress}`;
4747
+ const { address, vaultAddress: vaultAddress2, decimals } = inputs;
4748
+ const key = `${address}-${vaultAddress2}`;
4478
4749
  if (prevAddress.current === key)
4479
4750
  return;
4480
- if (!address || !vaultAddress)
4751
+ if (!address || !vaultAddress2)
4481
4752
  return;
4482
- if (address && isNativeTokenChecker(address))
4753
+ if (isNativeTokenChecker(address))
4483
4754
  return;
4484
4755
  prevAddress.current = key;
4485
- const allowance2 = await account7.assetsManager.getAllowance({
4756
+ const allowance2 = await account9.assetsManager.getAllowance({
4486
4757
  address,
4487
- vaultAddress,
4758
+ vaultAddress: vaultAddress2,
4488
4759
  decimals
4489
4760
  });
4490
- setAllowance(() => allowance2);
4761
+ setAllowance(allowance2);
4491
4762
  return allowance2;
4492
4763
  };
4493
4764
  const getAllowanceByDefaultAddress = async (inputs) => {
@@ -4497,12 +4768,31 @@ var useDeposit = (options) => {
4497
4768
  if (!address || isNativeTokenChecker(address))
4498
4769
  return;
4499
4770
  prevAddress.current = address;
4500
- const allowance2 = await account7.assetsManager.getAllowance({
4771
+ const allowance2 = await account9.assetsManager.getAllowance({
4501
4772
  address,
4502
- decimals
4773
+ decimals,
4774
+ vaultAddress
4503
4775
  });
4504
- setAllowance(() => allowance2);
4776
+ setAllowance(allowance2);
4777
+ return allowance2;
4505
4778
  };
4779
+ const vaultAddress = useMemo(() => {
4780
+ if (dst.chainId !== options.srcChainId) {
4781
+ return options.crossChainRouteAddress;
4782
+ }
4783
+ if (options.srcToken !== (options.dstToken || dst.symbol)) {
4784
+ return options.depositorAddress;
4785
+ }
4786
+ return targetChain?.network_infos.vault_address;
4787
+ }, [
4788
+ dst,
4789
+ options.srcChainId,
4790
+ options.srcToken,
4791
+ options.dstToken,
4792
+ options.crossChainRouteAddress,
4793
+ options.depositorAddress,
4794
+ targetChain
4795
+ ]);
4506
4796
  const queryBalance = useDebouncedCallback(
4507
4797
  (address, decimals) => {
4508
4798
  fetchBalance(address, decimals).finally(() => {
@@ -4522,89 +4812,113 @@ var useDeposit = (options) => {
4522
4812
  return;
4523
4813
  setBalanceRevalidating(true);
4524
4814
  queryBalance(options.address, options.decimals);
4525
- const params = {
4526
- address: options.address,
4527
- decimals: options.decimals
4528
- };
4529
- if (account7.walletAdapter?.chainNamespace === ChainNamespace.solana) {
4815
+ if (account9.walletAdapter?.chainNamespace === ChainNamespace.solana) {
4530
4816
  setAllowance(
4531
- account7.walletAdapter.formatUnits(MaxUint256, options.decimals)
4817
+ account9.walletAdapter.formatUnits(MaxUint256, options.decimals)
4532
4818
  );
4533
4819
  return;
4534
4820
  }
4535
- if (dst.chainId !== options.srcChainId) {
4536
- queryAllowance(params);
4821
+ if (vaultAddress && options.address) {
4822
+ queryAllowance({
4823
+ address: options.address,
4824
+ decimals: options.decimals,
4825
+ vaultAddress
4826
+ });
4537
4827
  } else {
4538
- if (dst.symbol !== options.srcToken) {
4539
- queryAllowance(params);
4540
- } else {
4541
- getAllowanceByDefaultAddress(params);
4542
- }
4828
+ getAllowanceByDefaultAddress({
4829
+ address: options.address,
4830
+ decimals: options.decimals
4831
+ });
4543
4832
  }
4544
4833
  }, [
4545
4834
  state.status,
4546
4835
  options.address,
4547
- options.srcChainId,
4548
- options.srcToken,
4549
4836
  options.decimals,
4550
- account7.address,
4551
- dst.chainId,
4552
- dst.symbol
4837
+ account9.address,
4838
+ vaultAddress
4553
4839
  ]);
4554
4840
  const updateAllowanceWhenTxSuccess = useCallback(
4555
4841
  (txHash) => {
4556
- return account7.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4842
+ return account9.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4557
4843
  if (receipt.status === 1) {
4558
- account7.assetsManager.getAllowance({ address: options.address }).then((allowance2) => {
4559
- setAllowance(() => allowance2);
4844
+ account9.assetsManager.getAllowance({
4845
+ address: options.address,
4846
+ decimals: options.decimals,
4847
+ vaultAddress
4848
+ }).then((allowance2) => {
4849
+ setAllowance(allowance2);
4560
4850
  });
4561
4851
  }
4562
4852
  });
4563
4853
  },
4564
- [account7, options.address]
4854
+ [account9, options.address, options.decimals, vaultAddress]
4565
4855
  );
4856
+ const enquireAllowance = useCallback(async () => {
4857
+ if (isNativeToken) {
4858
+ return;
4859
+ }
4860
+ if (!options.address) {
4861
+ throw new Error("address is required");
4862
+ }
4863
+ const _allowance = await account9.assetsManager.getAllowance({
4864
+ address: options.address,
4865
+ vaultAddress,
4866
+ decimals: options.decimals
4867
+ });
4868
+ setAllowance(_allowance);
4869
+ if (new Decimal(quantity).greaterThan(_allowance)) {
4870
+ throw new SDKError("Insufficient allowance");
4871
+ }
4872
+ return _allowance;
4873
+ }, [
4874
+ account9,
4875
+ options.address,
4876
+ options.decimals,
4877
+ vaultAddress,
4878
+ quantity,
4879
+ isNativeToken
4880
+ ]);
4566
4881
  const approve = useCallback(
4567
4882
  async (amount) => {
4568
4883
  if (!options.address) {
4569
- throw new SDKError("Address is required");
4884
+ throw new Error("address is required");
4570
4885
  }
4571
- return account7.assetsManager.approve({
4886
+ return account9.assetsManager.approve({
4572
4887
  address: options.address,
4573
4888
  amount,
4889
+ vaultAddress,
4574
4890
  decimals: options.decimals
4575
- }).then((res) => {
4576
- return updateAllowanceWhenTxSuccess(res.hash);
4577
- }).catch((e) => {
4578
- throw e;
4891
+ }).then((result) => {
4892
+ return updateAllowanceWhenTxSuccess(result.hash);
4579
4893
  });
4580
4894
  },
4581
- [account7, getAllowance, options.address, options.decimals, dst]
4895
+ [
4896
+ account9,
4897
+ options.address,
4898
+ options.decimals,
4899
+ vaultAddress,
4900
+ updateAllowanceWhenTxSuccess
4901
+ ]
4582
4902
  );
4583
4903
  const deposit = useCallback(async () => {
4584
- if (!options.address) {
4585
- throw new SDKError("Address is required");
4586
- }
4587
- const _allowance = await account7.assetsManager.getAllowance({
4588
- address: options.address,
4589
- decimals: options.decimals
4590
- });
4591
- setAllowance(() => _allowance);
4592
- if (new Decimal(quantity).greaterThan(_allowance)) {
4593
- throw new SDKError("Insufficient allowance");
4594
- }
4595
- return account7.assetsManager.deposit({
4904
+ await enquireAllowance();
4905
+ const inputs = {
4596
4906
  amount: quantity,
4597
4907
  fee: depositFee,
4598
- decimals: options.decimals
4599
- }).then((res) => {
4908
+ decimals: options.decimals,
4909
+ token: options.srcToken,
4910
+ vaultAddress
4911
+ };
4912
+ const depositPromise = isNativeToken ? account9.assetsManager.depositNativeToken(inputs) : account9.assetsManager.deposit(inputs);
4913
+ return depositPromise.then((result) => {
4914
+ updateAllowanceWhenTxSuccess(result.hash);
4915
+ setBalance((value) => new Decimal(value).sub(quantity).toString());
4600
4916
  track2(TrackerEventName.depositSuccess, {
4601
4917
  wallet: state?.connectWallet?.name,
4602
4918
  network: targetChain?.network_infos.name,
4603
4919
  quantity
4604
4920
  });
4605
- updateAllowanceWhenTxSuccess(res.hash);
4606
- setBalance((value) => new Decimal(value).sub(quantity).toString());
4607
- return res;
4921
+ return result;
4608
4922
  }).catch((e) => {
4609
4923
  track2(TrackerEventName.depositFailed, {
4610
4924
  wallet: state?.connectWallet?.name,
@@ -4614,16 +4928,23 @@ var useDeposit = (options) => {
4614
4928
  throw e;
4615
4929
  });
4616
4930
  }, [
4617
- account7,
4618
- fetchBalance,
4931
+ state,
4932
+ account9,
4619
4933
  quantity,
4620
4934
  depositFee,
4621
- options.address,
4622
- options.decimals
4935
+ targetChain,
4936
+ options.decimals,
4937
+ options.srcToken,
4938
+ enquireAllowance,
4939
+ updateAllowanceWhenTxSuccess,
4940
+ isNativeToken,
4941
+ vaultAddress
4623
4942
  ]);
4624
4943
  const loopGetBalance = async () => {
4625
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
4626
- const time = account7.walletAdapter?.chainNamespace === ChainNamespace.solana ? 1e4 : 3e3;
4944
+ if (getBalanceListener.current) {
4945
+ clearTimeout(getBalanceListener.current);
4946
+ }
4947
+ const time = account9.walletAdapter?.chainNamespace === ChainNamespace.solana ? 1e4 : 3e3;
4627
4948
  getBalanceListener.current = setTimeout(async () => {
4628
4949
  try {
4629
4950
  const balance2 = await fetchBalanceHandler(
@@ -4638,13 +4959,15 @@ var useDeposit = (options) => {
4638
4959
  };
4639
4960
  const getDepositFee = useCallback(
4640
4961
  async (quantity2) => {
4641
- return account7.assetsManager.getDepositFee({
4962
+ return account9.assetsManager.getDepositFee({
4642
4963
  amount: quantity2,
4643
4964
  chain: targetChain?.network_infos,
4644
- decimals: options.decimals
4965
+ decimals: options.decimals,
4966
+ token: options.srcToken,
4967
+ address: options.address
4645
4968
  });
4646
4969
  },
4647
- [account7, targetChain, options.decimals]
4970
+ [account9, targetChain, options.decimals, options.srcToken, options.address]
4648
4971
  );
4649
4972
  const enquiryDepositFee = useCallback(() => {
4650
4973
  if (isNaN(Number(quantity)) || !quantity || Number(quantity) === 0) {
@@ -4672,7 +4995,9 @@ var useDeposit = (options) => {
4672
4995
  }
4673
4996
  loopGetBalance();
4674
4997
  return () => {
4675
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
4998
+ if (getBalanceListener.current) {
4999
+ clearTimeout(getBalanceListener.current);
5000
+ }
4676
5001
  };
4677
5002
  }, [options.address, options.decimals]);
4678
5003
  return {
@@ -4691,12 +5016,26 @@ var useDeposit = (options) => {
4691
5016
  depositFeeRevalidating,
4692
5017
  approve,
4693
5018
  deposit,
4694
- fetchBalances,
4695
5019
  fetchBalance: fetchBalanceHandler,
5020
+ fetchBalances,
4696
5021
  /** set input quantity */
4697
5022
  setQuantity
4698
5023
  };
4699
5024
  };
5025
+
5026
+ // src/orderly/useConvert.ts
5027
+ var useConvert = (options) => {
5028
+ const { token = "" } = options;
5029
+ const { account: account9 } = useAccount();
5030
+ const maxAmount = useMaxWithdrawal(token);
5031
+ const convert = async (inputs) => {
5032
+ return account9.assetsManager.convert({
5033
+ ...inputs,
5034
+ converted_asset: token
5035
+ });
5036
+ };
5037
+ return { maxAmount, convert };
5038
+ };
4700
5039
  var fetcher3 = (url, options) => {
4701
5040
  const init2 = {
4702
5041
  method: options.arg.method,
@@ -4720,7 +5059,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4720
5059
  if (!url.startsWith("http")) {
4721
5060
  fullUrl = `${apiBaseUrl}${url}`;
4722
5061
  }
4723
- const account7 = useAccountInstance();
5062
+ const account9 = useAccountInstance();
4724
5063
  const { trigger, reset, data, error, isMutating } = useSWRMutation(
4725
5064
  fullUrl,
4726
5065
  // method === "POST" ? fetcher : deleteFetcher,
@@ -4740,7 +5079,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4740
5079
  url: newUrl,
4741
5080
  data: data2
4742
5081
  };
4743
- const signer = account7.signer;
5082
+ const signer = account9.signer;
4744
5083
  const signature = await signer.sign(payload, getTimestamp());
4745
5084
  return trigger(
4746
5085
  {
@@ -4749,13 +5088,13 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4749
5088
  method,
4750
5089
  signature: {
4751
5090
  ...signature,
4752
- "orderly-account-id": accountId || _accountId || account7.accountId
5091
+ "orderly-account-id": accountId || _accountId || account9.accountId
4753
5092
  }
4754
5093
  },
4755
5094
  restOptions2
4756
5095
  );
4757
5096
  },
4758
- [trigger, account7, accountId]
5097
+ [trigger, account9, accountId]
4759
5098
  );
4760
5099
  return [
4761
5100
  mutation,
@@ -4770,8 +5109,8 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4770
5109
 
4771
5110
  // src/orderly/useTransfer.ts
4772
5111
  var useTransfer = (options) => {
4773
- const { fromAccountId } = options || {};
4774
- const { unsettledPnL, availableBalance, freeCollateral, holding } = useCollateral();
5112
+ const { fromAccountId, token } = options || {};
5113
+ const { unsettledPnL, holding } = useCollateral();
4775
5114
  const [doTransfer, { isMutating: submitting }] = useSubAccountMutation(
4776
5115
  "/v1/internal_transfer",
4777
5116
  "POST",
@@ -4780,9 +5119,9 @@ var useTransfer = (options) => {
4780
5119
  }
4781
5120
  );
4782
5121
  const transfer = useCallback(
4783
- async (token, receivers) => {
5122
+ async (token2, receivers) => {
4784
5123
  return doTransfer({
4785
- token,
5124
+ token: token2,
4786
5125
  receiver_list: Array.isArray(receivers) ? receivers : [receivers]
4787
5126
  }).then((res) => {
4788
5127
  if (res.success) {
@@ -4795,23 +5134,12 @@ var useTransfer = (options) => {
4795
5134
  },
4796
5135
  [doTransfer]
4797
5136
  );
4798
- const maxAmount = useMemo(() => {
4799
- return freeCollateral;
4800
- }, [freeCollateral]);
4801
- const availableTransfer = useMemo(() => {
4802
- if (unsettledPnL < 0) {
4803
- return freeCollateral;
4804
- } else {
4805
- return freeCollateral - unsettledPnL;
4806
- }
4807
- }, [freeCollateral, unsettledPnL]);
5137
+ const maxAmount = useMaxWithdrawal(token);
4808
5138
  return {
4809
5139
  submitting,
4810
5140
  transfer,
4811
5141
  maxAmount,
4812
5142
  unsettledPnL,
4813
- availableBalance,
4814
- availableTransfer,
4815
5143
  holding
4816
5144
  };
4817
5145
  };
@@ -6413,7 +6741,7 @@ var OrderFactory = class {
6413
6741
  };
6414
6742
  function useSubAccountQuery(query, options) {
6415
6743
  const { formatter, accountId, ...swrOptions } = options || {};
6416
- const { state, account: account7 } = useAccount();
6744
+ const { state, account: account9 } = useAccount();
6417
6745
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
6418
6746
  return useSWR__default(
6419
6747
  () => accountId && (state.status >= AccountStatusEnum.EnableTrading || state.status === AccountStatusEnum.EnableTradingWithoutConnected) ? [query, accountId] : null,
@@ -6422,13 +6750,13 @@ function useSubAccountQuery(query, options) {
6422
6750
  },
6423
6751
  {
6424
6752
  ...swrOptions,
6425
- use: [...middleware, signatureMiddleware2(account7, accountId)],
6753
+ use: [...middleware, signatureMiddleware2(account9, accountId)],
6426
6754
  onError: () => {
6427
6755
  }
6428
6756
  }
6429
6757
  );
6430
6758
  }
6431
- function signatureMiddleware2(account7, accountId) {
6759
+ function signatureMiddleware2(account9, accountId) {
6432
6760
  const apiBaseUrl = useConfig("apiBaseUrl");
6433
6761
  return (useSWRNext) => {
6434
6762
  return (key, fetcher4, config) => {
@@ -6436,7 +6764,7 @@ function signatureMiddleware2(account7, accountId) {
6436
6764
  const extendedFetcher = async (args) => {
6437
6765
  const url = Array.isArray(args) ? args[0] : args;
6438
6766
  const fullUrl = `${apiBaseUrl}${url}`;
6439
- const signer = account7.signer;
6767
+ const signer = account9.signer;
6440
6768
  const payload = {
6441
6769
  method: "GET",
6442
6770
  url
@@ -6457,13 +6785,25 @@ function signatureMiddleware2(account7, accountId) {
6457
6785
  };
6458
6786
  }
6459
6787
  function formatPortfolio(inputs) {
6460
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
6461
- if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo || symbolsInfo?.isNil) {
6788
+ const {
6789
+ holding,
6790
+ positions: positions3,
6791
+ markPrices,
6792
+ indexPrices,
6793
+ accountInfo,
6794
+ symbolsInfo,
6795
+ tokensInfo
6796
+ } = inputs;
6797
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo || symbolsInfo?.isNil) {
6462
6798
  return null;
6463
6799
  }
6464
6800
  const unsettledPnL = pathOr(0, ["total_unsettled_pnl"])(positions3);
6465
6801
  const unrealizedPnL = pathOr(0, ["total_unreal_pnl"])(positions3);
6466
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
6802
+ const [USDC_holding, nonUSDC] = parseHolding(
6803
+ holding,
6804
+ indexPrices,
6805
+ tokensInfo
6806
+ );
6467
6807
  const usdc = holding.find((item) => item.token === "USDC");
6468
6808
  const totalCollateral = account.totalCollateral({
6469
6809
  USDCHolding: USDC_holding,
@@ -6615,7 +6955,7 @@ function calcByPrice(positions3, markPrice, indexPrice) {
6615
6955
  var useSubAccountWS = (options) => {
6616
6956
  const { accountId } = options;
6617
6957
  const { configStore } = useContext(OrderlyContext);
6618
- const { state, account: account7 } = useAccount();
6958
+ const { state, account: account9 } = useAccount();
6619
6959
  const websocketClient = useRef(
6620
6960
  new WS({
6621
6961
  networkId: configStore.get("networkId"),
@@ -6623,7 +6963,7 @@ var useSubAccountWS = (options) => {
6623
6963
  // publicUrl: configStore.get("publicWsUrl"),
6624
6964
  privateUrl: configStore.get("privateWsUrl"),
6625
6965
  onSigntureRequest: async () => {
6626
- const signer = account7.signer;
6966
+ const signer = account9.signer;
6627
6967
  const timestamp = getTimestamp();
6628
6968
  const result = await signer.signText(timestamp.toString());
6629
6969
  return { ...result, timestamp };
@@ -6648,11 +6988,12 @@ var useSubAccountDataObserver = (accountId) => {
6648
6988
  const { data: indexPrices } = useIndexPricesStream();
6649
6989
  const symbolsInfo = useSymbolsInfo();
6650
6990
  const fundingRates = useFundingRatesStore();
6991
+ const tokensInfo = useTokensInfo();
6651
6992
  const [holding, setHolding] = useState([]);
6652
6993
  const [positions3, setPositions] = useState(
6653
6994
  POSITION_EMPTY
6654
6995
  );
6655
- const [portfolio, setportfolio] = useState();
6996
+ const [portfolio, setPortfolio] = useState();
6656
6997
  const { data: accountInfo } = useSubAccountQuery(
6657
6998
  "/v1/client/info",
6658
6999
  { accountId, revalidateOnFocus: false }
@@ -6676,11 +7017,21 @@ var useSubAccountDataObserver = (accountId) => {
6676
7017
  holding,
6677
7018
  positions: positions3,
6678
7019
  markPrices,
7020
+ indexPrices,
6679
7021
  accountInfo,
6680
- symbolsInfo
7022
+ symbolsInfo,
7023
+ tokensInfo
6681
7024
  });
6682
- setportfolio(portfolio2);
6683
- }, [holding, positions3, markPrices, accountInfo, symbolsInfo]);
7025
+ setPortfolio(portfolio2);
7026
+ }, [
7027
+ holding,
7028
+ positions3,
7029
+ markPrices,
7030
+ indexPrices,
7031
+ accountInfo,
7032
+ symbolsInfo,
7033
+ tokensInfo
7034
+ ]);
6684
7035
  useEffect(() => {
6685
7036
  if (!positionsInfo)
6686
7037
  return;
@@ -6789,6 +7140,63 @@ var useSubAccountDataObserver = (accountId) => {
6789
7140
  }, [accountId]);
6790
7141
  return { portfolio, positions: positions3 };
6791
7142
  };
7143
+ var { maxWithdrawalUSDC: maxWithdrawalUSDC2, maxWithdrawalOtherCollateral: maxWithdrawalOtherCollateral2, collateralRatio: collateralRatio3 } = account;
7144
+ function useSubAccountMaxWithdrawal(options) {
7145
+ const { token, unsettledPnL, freeCollateral, holdings } = options;
7146
+ const tokenInfo = useTokenInfo(token);
7147
+ const { data: indexPrices } = useIndexPricesStream();
7148
+ const usdc = useMemo(() => {
7149
+ const usdc2 = holdings?.find((item) => item.token === "USDC");
7150
+ return usdc2;
7151
+ }, [holdings]);
7152
+ const holding = useMemo(() => {
7153
+ return holdings?.find((item) => item?.token === token);
7154
+ }, [holdings, token]);
7155
+ const usdcBalance = usdc?.holding ?? 0;
7156
+ const indexPrice = useMemo(() => {
7157
+ if (token === "USDC") {
7158
+ return 1;
7159
+ }
7160
+ const symbol = `PERP_${token}_USDC`;
7161
+ return indexPrices[symbol] ?? 0;
7162
+ }, [token, indexPrices]);
7163
+ const memoizedCollateralRatio = useMemo(() => {
7164
+ const { base_weight = 0, discount_factor = 0 } = tokenInfo || {};
7165
+ const holdingQty = holding?.holding ?? 0;
7166
+ return collateralRatio3({
7167
+ baseWeight: base_weight,
7168
+ discountFactor: discount_factor,
7169
+ collateralQty: holdingQty,
7170
+ collateralCap: tokenInfo?.user_max_qty ?? holdingQty,
7171
+ indexPrice
7172
+ });
7173
+ }, [holdings, tokenInfo, indexPrice, token, holding]);
7174
+ const maxAmount = useMemo(() => {
7175
+ if (token === "USDC") {
7176
+ return maxWithdrawalUSDC2({
7177
+ USDCBalance: usdcBalance,
7178
+ freeCollateral,
7179
+ upnl: unsettledPnL ?? 0
7180
+ });
7181
+ }
7182
+ return maxWithdrawalOtherCollateral2({
7183
+ collateralQty: holding?.holding ?? 0,
7184
+ freeCollateral,
7185
+ indexPrice,
7186
+ weight: memoizedCollateralRatio
7187
+ });
7188
+ }, [
7189
+ usdcBalance,
7190
+ freeCollateral,
7191
+ unsettledPnL,
7192
+ memoizedCollateralRatio,
7193
+ holdings,
7194
+ indexPrice,
7195
+ token,
7196
+ holding
7197
+ ]);
7198
+ return maxAmount;
7199
+ }
6792
7200
  function offsetToPrice(inputs) {
6793
7201
  const { offset, entryPrice, orderType, orderSide } = inputs;
6794
7202
  if (!offset)
@@ -7588,7 +7996,7 @@ var useStorageLedgerAddress = () => {
7588
7996
  var usePrivateDataObserver = (options) => {
7589
7997
  const ws = useWS();
7590
7998
  const ee = useEventEmitter();
7591
- const { state, account: account7 } = useAccount();
7999
+ const { state, account: account9 } = useAccount();
7592
8000
  const { setAccountInfo, restoreHolding, cleanAll } = useAppStore(
7593
8001
  (state2) => state2.actions
7594
8002
  );
@@ -7621,9 +8029,9 @@ var usePrivateDataObserver = (options) => {
7621
8029
  positionsActions.clearAll();
7622
8030
  }
7623
8031
  };
7624
- account7.on(EVENT_NAMES.statusChanged, handler);
8032
+ account9.on(EVENT_NAMES.statusChanged, handler);
7625
8033
  return () => {
7626
- account7.off(EVENT_NAMES.statusChanged, handler);
8034
+ account9.off(EVENT_NAMES.statusChanged, handler);
7627
8035
  };
7628
8036
  }, []);
7629
8037
  useEffect(() => {
@@ -7644,7 +8052,7 @@ var usePrivateDataObserver = (options) => {
7644
8052
  }
7645
8053
  );
7646
8054
  useEffect(() => {
7647
- if (!account7.accountId)
8055
+ if (!account9.accountId)
7648
8056
  return;
7649
8057
  const unsubscribe = ws.privateSubscribe(
7650
8058
  {
@@ -7663,11 +8071,11 @@ var usePrivateDataObserver = (options) => {
7663
8071
  }
7664
8072
  );
7665
8073
  return () => unsubscribe?.();
7666
- }, [account7.accountId]);
8074
+ }, [account9.accountId]);
7667
8075
  const isHoldingInit = useRef(false);
7668
8076
  useEffect(() => {
7669
8077
  isHoldingInit.current = false;
7670
- }, [state.accountId]);
8078
+ }, [state.address]);
7671
8079
  useEffect(() => {
7672
8080
  if (!holding) {
7673
8081
  return;
@@ -7836,6 +8244,7 @@ var usePublicDataObserver = () => {
7836
8244
  (state) => state.actions
7837
8245
  );
7838
8246
  const { updateMarket } = useMarketStore((state) => state.actions);
8247
+ const setTokensInfo = useTokensInfoStore((state) => state.setTokensInfo);
7839
8248
  useQuery(`/v1/public/info`, {
7840
8249
  ...publicQueryOptions,
7841
8250
  onSuccess(data) {
@@ -7888,6 +8297,16 @@ var usePublicDataObserver = () => {
7888
8297
  updateMarket(data);
7889
8298
  }
7890
8299
  });
8300
+ useQuery(`/v1/public/token`, {
8301
+ // revalidateOnFocus: false,
8302
+ ...publicQueryOptions,
8303
+ onSuccess(data) {
8304
+ if (!data || !data.length) {
8305
+ return [];
8306
+ }
8307
+ setTokensInfo(data);
8308
+ }
8309
+ });
7891
8310
  };
7892
8311
  function getEstFundingRate(data) {
7893
8312
  if (!data)
@@ -8002,7 +8421,7 @@ var ExtendedConfigStore = class extends DefaultConfigStore {
8002
8421
  }
8003
8422
  };
8004
8423
  var OrderlyConfigProvider = (props) => {
8005
- const [account7, setAccount] = React.useState(null);
8424
+ const [account9, setAccount] = React.useState(null);
8006
8425
  const {
8007
8426
  configStore,
8008
8427
  keyStore,
@@ -8013,7 +8432,9 @@ var OrderlyConfigProvider = (props) => {
8013
8432
  networkId,
8014
8433
  contracts,
8015
8434
  chainFilter,
8016
- customChains
8435
+ customChains,
8436
+ enableSwapDeposit = true,
8437
+ chainTransformer
8017
8438
  } = props;
8018
8439
  if (typeof configStore !== "undefined" && !configStore.get("brokerId")) {
8019
8440
  throw new SDKError(
@@ -8043,9 +8464,9 @@ var OrderlyConfigProvider = (props) => {
8043
8464
  return props.orderbookDefaultTickSizes || DEFAULT_TICK_SIZES;
8044
8465
  }, [props.orderbookDefaultTickSizes]);
8045
8466
  useLayoutEffect(() => {
8046
- let account8 = SimpleDI.get(Account.instanceName);
8047
- if (!account8) {
8048
- account8 = new Account(
8467
+ let account10 = SimpleDI.get(Account.instanceName);
8468
+ if (!account10) {
8469
+ account10 = new Account(
8049
8470
  innerConfigStore,
8050
8471
  innerKeyStore,
8051
8472
  // innerGetWalletAdapter,
@@ -8054,9 +8475,9 @@ var OrderlyConfigProvider = (props) => {
8054
8475
  contracts
8055
8476
  }
8056
8477
  );
8057
- SimpleDI.registerByName(Account.instanceName, account8);
8478
+ SimpleDI.registerByName(Account.instanceName, account10);
8058
8479
  }
8059
- setAccount(account8);
8480
+ setAccount(account10);
8060
8481
  }, []);
8061
8482
  const filteredChains = useMemo(() => {
8062
8483
  if (typeof chainFilter === "function") {
@@ -8064,7 +8485,7 @@ var OrderlyConfigProvider = (props) => {
8064
8485
  }
8065
8486
  return chainFilter;
8066
8487
  }, [props.chainFilter, innerConfigStore]);
8067
- if (!account7) {
8488
+ if (!account9) {
8068
8489
  return null;
8069
8490
  }
8070
8491
  return /* @__PURE__ */ jsx(
@@ -8079,6 +8500,8 @@ var OrderlyConfigProvider = (props) => {
8079
8500
  walletAdapters: innerWalletAdapters,
8080
8501
  // apiBaseUrl,
8081
8502
  customChains,
8503
+ enableSwapDeposit,
8504
+ chainTransformer,
8082
8505
  defaultOrderbookTickSizes
8083
8506
  },
8084
8507
  children: /* @__PURE__ */ jsx(StatusProvider, { children: /* @__PURE__ */ jsx(DataCenterProvider, { children: props.children }) })
@@ -9904,9 +10327,9 @@ var useAllBrokers = () => {
9904
10327
  };
9905
10328
  var useCurEpochEstimate = (type) => {
9906
10329
  const [data, setData] = useState(void 0);
9907
- const { account: account7 } = useAccount();
10330
+ const { account: account9 } = useAccount();
9908
10331
  const brokers = useAllBrokers();
9909
- const address = account7.address;
10332
+ const address = account9.address;
9910
10333
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/current_epoch_estimate?address=${address}` : `/v1/public/market_making_rewards/current_epoch_estimate?address=${address}`;
9911
10334
  const { data: estimateData } = useQuery(address !== void 0 ? path2 : "", {
9912
10335
  formatter: (res) => {
@@ -14866,14 +15289,14 @@ var DistributionId = /* @__PURE__ */ ((DistributionId2) => {
14866
15289
  })(DistributionId || {});
14867
15290
  var useGetClaimed = (id) => {
14868
15291
  const [data, setData] = useState(0);
14869
- const { account: account7 } = useAccount();
14870
- const address = account7.address;
15292
+ const { account: account9 } = useAccount();
15293
+ const address = account9.address;
14871
15294
  const env = useGetEnv();
14872
15295
  const refresh = useCallback(() => {
14873
15296
  const params = getContractByEnv(env);
14874
15297
  if (typeof address === "undefined")
14875
15298
  return;
14876
- account7.walletAdapter?.callOnChain(
15299
+ account9.walletAdapter?.callOnChain(
14877
15300
  // @ts-ignore
14878
15301
  { public_rpc_url: params.orderlyChainRpcUrl },
14879
15302
  params.orderlyContract,
@@ -14898,8 +15321,8 @@ var useGetClaimed = (id) => {
14898
15321
 
14899
15322
  // src/trading-rewards/useWalletRewardsHistory.ts
14900
15323
  var useWalletRewardsHistory = (type) => {
14901
- const { account: account7 } = useAccount();
14902
- const address = account7.address;
15324
+ const { account: account9 } = useAccount();
15325
+ const address = account9.address;
14903
15326
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/wallet_rewards_history?address=${address}` : `/v1/public/market_making_rewards/group_rewards_history?address=${address}`;
14904
15327
  const {
14905
15328
  data,
@@ -14947,7 +15370,7 @@ function useTradingRewardsStatus(isMMRewards) {
14947
15370
  };
14948
15371
  }
14949
15372
  var useApiKeyManager = (queryParams) => {
14950
- const { account: account7, state, isSubAccount } = useAccount();
15373
+ const { account: account9, state, isSubAccount } = useAccount();
14951
15374
  const { keyInfo } = queryParams || {};
14952
15375
  const keyInfoPrams = getQueryParamsFromObject(keyInfo);
14953
15376
  const { data, mutate: mutate5, error, isLoading } = usePrivateQuery(
@@ -14984,13 +15407,13 @@ var useApiKeyManager = (queryParams) => {
14984
15407
  }, []);
14985
15408
  const generateOrderlyKey = (scope) => {
14986
15409
  if (isSubAccount) {
14987
- return account7?.createSubAccountApiKey(365, {
15410
+ return account9?.createSubAccountApiKey(365, {
14988
15411
  tag: "manualCreated",
14989
15412
  scope,
14990
15413
  subAccountId: state.accountId
14991
15414
  });
14992
15415
  }
14993
- return account7?.createApiKey(365, {
15416
+ return account9?.createApiKey(365, {
14994
15417
  tag: "manualCreated",
14995
15418
  scope
14996
15419
  });
@@ -16032,6 +16455,6 @@ var usePositionClose = (options) => {
16032
16455
  };
16033
16456
  };
16034
16457
 
16035
- export { AssetHistoryStatusEnum, DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusContext, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, getMinNotional, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useConfig, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMutation, useNetworkInfo, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTickerStream, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
16458
+ export { AssetHistoryStatusEnum, DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusContext, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, getMinNotional, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTickerStream, useTokenInfo, useTokensInfo, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
16036
16459
  //# sourceMappingURL=out.js.map
16037
16460
  //# sourceMappingURL=index.mjs.map