@orderly.network/hooks 2.4.1 → 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.js CHANGED
@@ -12,6 +12,9 @@ var lodash = require('lodash');
12
12
  var useSWRInfinite = require('swr/infinite');
13
13
  var amplitude = require('@amplitude/analytics-browser');
14
14
  var jsxRuntime = require('react/jsx-runtime');
15
+ var defaultEvmAdapter = require('@orderly.network/default-evm-adapter');
16
+ var defaultSolanaAdapter = require('@orderly.network/default-solana-adapter');
17
+ var web3ProviderEthers = require('@orderly.network/web3-provider-ethers');
15
18
  var zustand = require('zustand');
16
19
  var immer = require('zustand/middleware/immer');
17
20
  var ramda = require('ramda');
@@ -19,9 +22,6 @@ var perp = require('@orderly.network/perp');
19
22
  var useSWRSubscription = require('swr/subscription');
20
23
  var useDebounce = require('use-debounce');
21
24
  var immer$1 = require('immer');
22
- var defaultEvmAdapter = require('@orderly.network/default-evm-adapter');
23
- var defaultSolanaAdapter = require('@orderly.network/default-solana-adapter');
24
- var web3ProviderEthers = require('@orderly.network/web3-provider-ethers');
25
25
  var qr = require('@akamfoad/qr');
26
26
 
27
27
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -61,9 +61,9 @@ var __export = (target, all) => {
61
61
  // src/version.ts
62
62
  if (typeof window !== "undefined") {
63
63
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
64
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.4.1";
64
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.5.0-alpha.1";
65
65
  }
66
- var version_default = "2.4.1";
66
+ var version_default = "2.5.0-alpha.1";
67
67
  var fetcher = (url, init2 = {}, queryOptions) => net.get(url, init2, queryOptions?.formatter);
68
68
  var OrderlyContext = React.createContext({
69
69
  // configStore: new MemoryConfigStore(),
@@ -130,20 +130,20 @@ var useAccountInstance = () => {
130
130
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
131
131
  );
132
132
  }
133
- const account7 = useConstant__default.default(() => {
134
- let account8 = core.SimpleDI.get("account");
135
- if (!account8) {
136
- account8 = new core.Account(
133
+ const account9 = useConstant__default.default(() => {
134
+ let account10 = core.SimpleDI.get("account");
135
+ if (!account10) {
136
+ account10 = new core.Account(
137
137
  configStore,
138
138
  keyStore,
139
139
  // getWalletAdapter,
140
140
  walletAdapters
141
141
  );
142
- core.SimpleDI.registerByName("account", account8);
142
+ core.SimpleDI.registerByName("account", account10);
143
143
  }
144
- return account8;
144
+ return account10;
145
145
  });
146
- return account7;
146
+ return account9;
147
147
  };
148
148
  var fetcher2 = (url, options) => {
149
149
  const init2 = {
@@ -167,7 +167,7 @@ var useMutation = (url, method = "POST", options) => {
167
167
  if (!url.startsWith("http")) {
168
168
  fullUrl = `${apiBaseUrl}${url}`;
169
169
  }
170
- const account7 = useAccountInstance();
170
+ const account9 = useAccountInstance();
171
171
  const { trigger, data, error, reset, isMutating } = useSWRMutation__default.default(
172
172
  fullUrl,
173
173
  // method === "POST" ? fetcher : deleteFetcher,
@@ -185,7 +185,7 @@ var useMutation = (url, method = "POST", options) => {
185
185
  url: newUrl,
186
186
  data: data2
187
187
  };
188
- const signer = account7.signer;
188
+ const signer = account9.signer;
189
189
  const signature = await signer.sign(payload, utils.getTimestamp());
190
190
  return trigger(
191
191
  {
@@ -194,7 +194,7 @@ var useMutation = (url, method = "POST", options) => {
194
194
  method,
195
195
  signature: {
196
196
  ...signature,
197
- "orderly-account-id": account7.accountId
197
+ "orderly-account-id": account9.accountId
198
198
  }
199
199
  },
200
200
  options2
@@ -216,9 +216,9 @@ var signatureMiddleware = (useSWRNext) => {
216
216
  try {
217
217
  const extendedFetcher = async (args) => {
218
218
  const url = Array.isArray(args) ? args[0] : args;
219
- const account7 = core.SimpleDI.get("account");
219
+ const account9 = core.SimpleDI.get("account");
220
220
  const fullUrl = `${apiBaseUrl}${url}`;
221
- const signer = account7.signer;
221
+ const signer = account9.signer;
222
222
  const payload = {
223
223
  method: "GET",
224
224
  url
@@ -227,7 +227,7 @@ var signatureMiddleware = (useSWRNext) => {
227
227
  return fetcher4(fullUrl, {
228
228
  headers: {
229
229
  ...signature,
230
- "orderly-account-id": account7.accountId
230
+ "orderly-account-id": account9.accountId
231
231
  }
232
232
  });
233
233
  };
@@ -300,25 +300,25 @@ var useWS = () => {
300
300
  const { configStore } = React.useContext(OrderlyContext);
301
301
  const ws = useConstant__default.default(() => {
302
302
  let websocketClient = core.SimpleDI.get(WS_NAME);
303
- const account7 = core.SimpleDI.get(core.Account.instanceName);
303
+ const account9 = core.SimpleDI.get(core.Account.instanceName);
304
304
  if (!websocketClient) {
305
305
  websocketClient = new net.WS({
306
306
  networkId: configStore.get("networkId"),
307
307
  publicUrl: configStore.get("publicWsUrl"),
308
308
  privateUrl: configStore.get("privateWsUrl"),
309
309
  onSigntureRequest: async (accountId) => {
310
- const signer = account7.signer;
310
+ const signer = account9.signer;
311
311
  const timestamp = utils.getTimestamp();
312
312
  const result = await signer.signText(timestamp.toString());
313
313
  return { ...result, timestamp };
314
314
  }
315
315
  });
316
- if ((account7.stateValue.status === types.AccountStatusEnum.EnableTrading || account7.stateValue.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
317
- websocketClient.openPrivate(account7.accountId);
316
+ if ((account9.stateValue.status === types.AccountStatusEnum.EnableTrading || account9.stateValue.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account9.accountId) {
317
+ websocketClient.openPrivate(account9.accountId);
318
318
  }
319
- account7.on("change:status", (nextState) => {
320
- if ((nextState.status === types.AccountStatusEnum.EnableTrading || nextState.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account7.accountId) {
321
- websocketClient.openPrivate(account7.accountId);
319
+ account9.on("change:status", (nextState) => {
320
+ if ((nextState.status === types.AccountStatusEnum.EnableTrading || nextState.status === types.AccountStatusEnum.EnableTradingWithoutConnected) && account9.accountId) {
321
+ websocketClient.openPrivate(account9.accountId);
322
322
  } else {
323
323
  websocketClient.closePrivate(1e3, "switch account");
324
324
  }
@@ -345,63 +345,63 @@ var useAccount = () => {
345
345
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
346
346
  );
347
347
  }
348
- const account7 = useAccountInstance();
349
- const [state, setState] = React.useState(account7.stateValue);
348
+ const account9 = useAccountInstance();
349
+ const [state, setState] = React.useState(account9.stateValue);
350
350
  const { track: track2 } = useTrack();
351
351
  const statusChangeHandler = (nextState) => {
352
352
  setState(() => nextState);
353
353
  };
354
354
  React.useEffect(() => {
355
- account7.on("change:status", statusChangeHandler);
355
+ account9.on("change:status", statusChangeHandler);
356
356
  return () => {
357
- account7.off("change:status", statusChangeHandler);
357
+ account9.off("change:status", statusChangeHandler);
358
358
  };
359
- }, [account7]);
359
+ }, [account9]);
360
360
  const createOrderlyKey = React.useCallback(
361
361
  async (remember) => {
362
362
  track2(types.TrackerEventName.signinSuccess, {
363
- network: account7.chainId,
363
+ network: account9.chainId,
364
364
  wallet: state.connectWallet?.name
365
365
  });
366
- return account7.createOrderlyKey(remember ? 365 : 30).then((res) => {
367
- return account7.restoreSubAccount().then((_) => {
366
+ return account9.createOrderlyKey(remember ? 365 : 30).then((res) => {
367
+ return account9.restoreSubAccount().then((_) => {
368
368
  return res;
369
369
  });
370
370
  });
371
371
  },
372
- [account7, state]
372
+ [account9, state]
373
373
  );
374
374
  const ws = useWS();
375
375
  const switchAccount = React.useCallback(
376
376
  async (accountId) => {
377
377
  ws.closePrivate(1e3, "switch account");
378
- return account7.switchAccount(accountId);
378
+ return account9.switchAccount(accountId);
379
379
  },
380
- [account7]
380
+ [account9]
381
381
  );
382
382
  const createAccount = React.useCallback(async () => {
383
- return account7.createAccount();
384
- }, [account7]);
383
+ return account9.createAccount();
384
+ }, [account9]);
385
385
  const createSubAccount = React.useCallback(
386
386
  async (description) => {
387
- return account7.createSubAccount(description);
387
+ return account9.createSubAccount(description);
388
388
  },
389
- [account7]
389
+ [account9]
390
390
  );
391
391
  const updateSubAccount = React.useCallback(
392
392
  async (value) => {
393
- return account7.updateSubAccount(value);
393
+ return account9.updateSubAccount(value);
394
394
  },
395
- [account7]
395
+ [account9]
396
396
  );
397
397
  const refreshSubAccountBalances = React.useCallback(() => {
398
- return account7.refreshSubAccountBalances();
399
- }, [account7]);
398
+ return account9.refreshSubAccountBalances();
399
+ }, [account9]);
400
400
  const isSubAccount = React.useMemo(() => {
401
401
  return state.accountId !== state.mainAccountId;
402
402
  }, [state]);
403
403
  return {
404
- account: account7,
404
+ account: account9,
405
405
  state,
406
406
  isSubAccount,
407
407
  isMainAccount: !isSubAccount,
@@ -773,6 +773,13 @@ var StatusProvider = (props) => {
773
773
  const wsStatus = useWsStatus();
774
774
  return /* @__PURE__ */ jsxRuntime.jsx(StatusContext.Provider, { value: { ws: wsStatus }, children: props.children });
775
775
  };
776
+
777
+ // src/constants.ts
778
+ var DEFAULT_TICK_SIZES = {
779
+ PERP_BTC_USDC: "1",
780
+ PERP_ETH_USDC: "0.1",
781
+ PERP_SOL_USDC: "0.01"
782
+ };
776
783
  var useWSObserver = (calculatorService) => {
777
784
  const ws = useWS();
778
785
  React.useEffect(() => {
@@ -1180,6 +1187,24 @@ var useAppStore = zustand.create()(
1180
1187
  }))
1181
1188
  );
1182
1189
  var useAccountInfo = () => useAppStore((state) => state.accountInfo);
1190
+ var useTokensInfoStore = zustand.create(
1191
+ (set) => ({
1192
+ tokensInfo: [],
1193
+ setTokensInfo(data) {
1194
+ set({ tokensInfo: data });
1195
+ }
1196
+ })
1197
+ );
1198
+ var useTokensInfo = () => {
1199
+ const tokensInfo = useTokensInfoStore((state) => state.tokensInfo);
1200
+ return tokensInfo;
1201
+ };
1202
+ var useTokenInfo = (token) => {
1203
+ const tokensInfo = useTokensInfo();
1204
+ return React.useMemo(() => {
1205
+ return tokensInfo?.find((item) => item.token === token);
1206
+ }, [tokensInfo, token]);
1207
+ };
1183
1208
 
1184
1209
  // src/orderly/calculator/baseCalculator.ts
1185
1210
  var BaseCalculator = class {
@@ -1247,6 +1272,7 @@ var CalculatorContext = class _CalculatorContext {
1247
1272
  this.accountInfo = useAppStore.getState().accountInfo;
1248
1273
  this.symbolsInfo = useAppStore.getState().symbolsInfo;
1249
1274
  this.fundingRates = useAppStore.getState().fundingRates;
1275
+ this.tokensInfo = useTokensInfoStore.getState().tokensInfo;
1250
1276
  }
1251
1277
  get(fn) {
1252
1278
  return fn(this.output);
@@ -1763,25 +1789,68 @@ function createGetter(data, depth = 2) {
1763
1789
  }
1764
1790
  });
1765
1791
  }
1766
-
1767
- // src/utils/parseHolding.ts
1768
- var parseHolding = (holding, markPrices) => {
1792
+ var parseHolding = (holding, indexPrices, tokensInfo) => {
1769
1793
  const nonUSDC = [];
1770
1794
  let USDC_holding = 0;
1771
1795
  holding.forEach((item) => {
1772
1796
  if (item.token === "USDC") {
1773
1797
  USDC_holding = item.holding;
1774
1798
  } else {
1799
+ const tokenInfo = tokensInfo.find(({ token }) => token === item.token);
1800
+ const {
1801
+ base_weight = 0,
1802
+ discount_factor = 0,
1803
+ user_max_qty = 0
1804
+ } = tokenInfo || {};
1805
+ const holdingQty = item?.holding ?? 0;
1806
+ const indexPrice = indexPrices[`PERP_${item.token}_USDC`] ?? 0;
1807
+ const collateralRatio4 = perp.account.collateralRatio({
1808
+ baseWeight: base_weight,
1809
+ discountFactor: discount_factor,
1810
+ collateralQty: holdingQty,
1811
+ collateralCap: user_max_qty,
1812
+ indexPrice
1813
+ });
1775
1814
  nonUSDC.push({
1776
- holding: item.holding,
1777
- markPrice: markPrices[item.token] ?? 0,
1778
- // markPrice: 0,
1779
- discount: 0
1815
+ holding: holdingQty,
1816
+ indexPrice,
1817
+ collateralCap: user_max_qty,
1818
+ collateralRatio: collateralRatio4
1780
1819
  });
1781
1820
  }
1782
1821
  });
1783
1822
  return [USDC_holding, nonUSDC];
1784
1823
  };
1824
+ var useIndexPriceStore = zustand.create((set) => ({
1825
+ indexPrices: {},
1826
+ actions: {
1827
+ updateIndexPrice: (indexPrice) => {
1828
+ set({
1829
+ indexPrices: indexPrice
1830
+ });
1831
+ }
1832
+ }
1833
+ }));
1834
+
1835
+ // src/orderly/calculator/indexPrice.ts
1836
+ var IndexPriceCalculatorName = "indexPriceCalculator";
1837
+ var IndexPriceCalculator = class extends BaseCalculator {
1838
+ constructor() {
1839
+ super(...arguments);
1840
+ this.name = IndexPriceCalculatorName;
1841
+ }
1842
+ calc(scope, data, ctx) {
1843
+ return data;
1844
+ }
1845
+ update(data) {
1846
+ if (!data)
1847
+ return;
1848
+ useIndexPriceStore.getState().actions.updateIndexPrice(data);
1849
+ }
1850
+ static getValue() {
1851
+ return useIndexPriceStore.getState().indexPrices;
1852
+ }
1853
+ };
1785
1854
 
1786
1855
  // src/orderly/calculator/portfolio.ts
1787
1856
  var PortfolioCalculatorName = "portfolio";
@@ -1791,7 +1860,8 @@ var PortfolioCalculator = class extends BaseCalculator {
1791
1860
  this.name = PortfolioCalculatorName;
1792
1861
  }
1793
1862
  calc(scope, data, ctx) {
1794
- let markPrices, positions3;
1863
+ let markPrices;
1864
+ let indexPrices;
1795
1865
  const portfolio = this.getPortfolio(ctx);
1796
1866
  if (scope === "markPrice" /* MARK_PRICE */) {
1797
1867
  markPrices = data;
@@ -1800,7 +1870,14 @@ var PortfolioCalculator = class extends BaseCalculator {
1800
1870
  (cache) => cache[MarketCalculatorName]
1801
1871
  );
1802
1872
  }
1803
- positions3 = ctx.get(
1873
+ if (scope === "indexPrice" /* INDEX_PRICE */) {
1874
+ indexPrices = data;
1875
+ } else {
1876
+ indexPrices = ctx.get(
1877
+ (cache) => cache[IndexPriceCalculatorName]
1878
+ );
1879
+ }
1880
+ const positions3 = ctx.get(
1804
1881
  (output) => output.positionCalculator_all
1805
1882
  );
1806
1883
  let holding = portfolio.holding;
@@ -1822,25 +1899,40 @@ var PortfolioCalculator = class extends BaseCalculator {
1822
1899
  }
1823
1900
  const accountInfo = ctx.accountInfo;
1824
1901
  const symbolsInfo = ctx.symbolsInfo;
1902
+ const tokensInfo = ctx.tokensInfo;
1825
1903
  return this.format({
1826
1904
  holding,
1827
1905
  positions: positions3,
1828
1906
  markPrices,
1829
1907
  accountInfo,
1830
- symbolsInfo
1908
+ symbolsInfo,
1909
+ indexPrices,
1910
+ tokensInfo: tokensInfo ?? []
1831
1911
  });
1832
1912
  }
1833
1913
  getPortfolio(ctx) {
1834
1914
  return ctx.get((output) => output[this.name]) || useAppStore.getState().portfolio;
1835
1915
  }
1836
1916
  format(inputs) {
1837
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
1838
- if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo) {
1917
+ const {
1918
+ holding,
1919
+ positions: positions3,
1920
+ markPrices,
1921
+ indexPrices,
1922
+ accountInfo,
1923
+ symbolsInfo,
1924
+ tokensInfo
1925
+ } = inputs;
1926
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo) {
1839
1927
  return null;
1840
1928
  }
1841
1929
  const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
1842
1930
  const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
1843
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1931
+ const [USDC_holding, nonUSDC] = parseHolding(
1932
+ holding,
1933
+ indexPrices,
1934
+ tokensInfo
1935
+ );
1844
1936
  const usdc = holding.find((item) => item.token === "USDC");
1845
1937
  const totalCollateral = perp.account.totalCollateral({
1846
1938
  USDCHolding: USDC_holding,
@@ -1895,36 +1987,6 @@ var PortfolioCalculator = class extends BaseCalculator {
1895
1987
  }
1896
1988
  }
1897
1989
  };
1898
- var useIndexPriceStore = zustand.create((set) => ({
1899
- indexPrices: {},
1900
- actions: {
1901
- updateIndexPrice: (indexPrice) => {
1902
- set({
1903
- indexPrices: indexPrice
1904
- });
1905
- }
1906
- }
1907
- }));
1908
-
1909
- // src/orderly/calculator/indexPrice.ts
1910
- var IndexPriceCalculatorName = "indexPriceCalculator";
1911
- var IndexPriceCalculator = class extends BaseCalculator {
1912
- constructor() {
1913
- super(...arguments);
1914
- this.name = IndexPriceCalculatorName;
1915
- }
1916
- calc(scope, data, ctx) {
1917
- return data;
1918
- }
1919
- update(data) {
1920
- if (!data)
1921
- return;
1922
- useIndexPriceStore.getState().actions.updateIndexPrice(data);
1923
- }
1924
- static getValue() {
1925
- return useIndexPriceStore.getState().indexPrices;
1926
- }
1927
- };
1928
1990
 
1929
1991
  // src/useCalculatorService.ts
1930
1992
  var useCalculatorService = () => {
@@ -2300,10 +2362,6 @@ var useTickerStream = (symbol) => {
2300
2362
  };
2301
2363
 
2302
2364
  // src/orderly/useOrderbookStream.ts
2303
- var DEFAULT_DEPTH = {
2304
- PERP_BTC_USDC: "1",
2305
- PERP_ETH_USDC: "0.1"
2306
- };
2307
2365
  var paddingFn = (len) => Array(len).fill([
2308
2366
  Number.NaN,
2309
2367
  Number.NaN,
@@ -2412,7 +2470,7 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2412
2470
  const padding = options?.padding ?? true;
2413
2471
  const symbolRef = React.useRef(symbol);
2414
2472
  symbolRef.current = symbol;
2415
- const [requestData, setRequestData] = React.useState(null);
2473
+ const { defaultOrderbookTickSizes: DEFAULT_TICK_SIZES2 } = React.useContext(OrderlyContext);
2416
2474
  const [data, setData] = React.useState(initial);
2417
2475
  const [isLoading, setIsLoading] = React.useState(true);
2418
2476
  const config = useSymbolsInfo()[symbol];
@@ -2435,12 +2493,12 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2435
2493
  return [tick];
2436
2494
  }, [config("quote_tick")]);
2437
2495
  React.useEffect(() => {
2438
- if (DEFAULT_DEPTH[symbol]) {
2439
- setDepth(Number(DEFAULT_DEPTH[symbol]));
2496
+ if (DEFAULT_TICK_SIZES2[symbol]) {
2497
+ setDepth(Number(DEFAULT_TICK_SIZES2[symbol]));
2440
2498
  } else {
2441
2499
  setDepth(config("quote_tick"));
2442
2500
  }
2443
- }, [config("quote_tick"), symbol]);
2501
+ }, [config("quote_tick"), symbol, DEFAULT_TICK_SIZES2]);
2444
2502
  const ws = useWS();
2445
2503
  const ticker = useTickerStream(symbol);
2446
2504
  const eventEmitter = useEventEmitter();
@@ -3269,6 +3327,68 @@ var useLeverage = () => {
3269
3327
  maxLeverage: memoizedMaxLeverage
3270
3328
  };
3271
3329
  };
3330
+
3331
+ // src/orderly/useOdosQuote.ts
3332
+ var useOdosQuote = () => {
3333
+ return useMutation(`https://api.odos.xyz/sor/quote/v2`);
3334
+ };
3335
+ var { LTV, collateralRatio } = perp.account;
3336
+ var useComputedLTV = (options = {}) => {
3337
+ const { input, token } = options;
3338
+ const isUSDC = token?.toUpperCase() === "USDC";
3339
+ const tokensInfo = useTokensInfo();
3340
+ const { usdc, data: holdingList = [] } = useHoldingStream();
3341
+ const { data: indexPrices } = useIndexPricesStream();
3342
+ const { unsettledPnL } = useCollateral();
3343
+ const usdcBalance = React.useMemo(() => {
3344
+ if (isUSDC && input) {
3345
+ return new utils.Decimal(usdc?.holding ?? 0).add(input).toNumber();
3346
+ }
3347
+ return usdc?.holding ?? 0;
3348
+ }, [usdc?.holding, input, token, isUSDC]);
3349
+ const getAdjustedQty = React.useCallback(
3350
+ (item) => {
3351
+ if (input && item.token === token) {
3352
+ return new utils.Decimal(item?.holding ?? 0).add(input).toNumber();
3353
+ }
3354
+ return item?.holding ?? 0;
3355
+ },
3356
+ [input, token]
3357
+ );
3358
+ const memoizedLTV = React.useMemo(() => {
3359
+ return LTV({
3360
+ usdcBalance,
3361
+ upnl: unsettledPnL,
3362
+ assets: holdingList.filter((h) => h.token.toUpperCase() !== "USDC").map((item) => {
3363
+ const indexPrice = indexPrices[`PERP_${item.token}_USDC`] ?? 0;
3364
+ const findToken = tokensInfo?.find((i) => i.token === item.token);
3365
+ const qty = getAdjustedQty(item);
3366
+ return {
3367
+ qty,
3368
+ indexPrice,
3369
+ weight: collateralRatio({
3370
+ baseWeight: findToken?.base_weight ?? 0,
3371
+ discountFactor: findToken?.discount_factor ?? 0,
3372
+ collateralCap: findToken?.user_max_qty ?? qty,
3373
+ collateralQty: qty,
3374
+ indexPrice
3375
+ })
3376
+ };
3377
+ })
3378
+ });
3379
+ }, [
3380
+ usdcBalance,
3381
+ unsettledPnL,
3382
+ holdingList,
3383
+ indexPrices,
3384
+ tokensInfo,
3385
+ getAdjustedQty
3386
+ ]);
3387
+ if (new utils.Decimal(usdcBalance).add(new utils.Decimal(unsettledPnL)).gte(utils.zero)) {
3388
+ return 0;
3389
+ }
3390
+ return new utils.Decimal(memoizedLTV).mul(100).toDecimalPlaces(2, utils.Decimal.ROUND_DOWN).toNumber();
3391
+ };
3272
3392
  var useFundingRate = (symbol) => {
3273
3393
  if (!symbol) {
3274
3394
  throw new types.SDKError("Symbol is required");
@@ -4025,7 +4145,8 @@ function useChains(networkId, options = {}) {
4025
4145
  const {
4026
4146
  filteredChains: allowedChains,
4027
4147
  configStore,
4028
- customChains
4148
+ customChains,
4149
+ chainTransformer
4029
4150
  } = React.useContext(OrderlyContext);
4030
4151
  const filterFun = React.useRef(options?.filter);
4031
4152
  filterFun.current = options?.filter;
@@ -4036,7 +4157,7 @@ function useChains(networkId, options = {}) {
4036
4157
  revalidateOnReconnect: false,
4037
4158
  // If false, undefined data gets cached against the key.
4038
4159
  revalidateOnMount: true,
4039
- // dont duplicate a request w/ same key for 1hr
4160
+ // don't duplicate a request with the same key for 1hr
4040
4161
  dedupingInterval: 36e5,
4041
4162
  ...swrOptions
4042
4163
  };
@@ -4052,13 +4173,15 @@ function useChains(networkId, options = {}) {
4052
4173
  }
4053
4174
  );
4054
4175
  const brokerId = configStore.get("brokerId");
4176
+ const env = configStore.get("env");
4177
+ const brokerIdQuery = brokerId !== "orderly" ? `?broker_id=${brokerId}` : "";
4055
4178
  const needFetchFromAPI = options.forceAPI || !customChains;
4056
4179
  const { data: chainInfos, error: chainInfoErr } = useQuery(
4057
- needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
4180
+ needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerIdQuery}` : null,
4058
4181
  { ...commonSwrOpts }
4059
4182
  );
4060
4183
  const { data: testChainInfos, error: testChainInfoError } = useQuery(
4061
- needFetchFromAPI ? `https://testnet-api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
4184
+ needFetchFromAPI ? `https://testnet-api.orderly.org/v1/public/chain_info${brokerIdQuery}` : null,
4062
4185
  {
4063
4186
  ...commonSwrOpts,
4064
4187
  fallbackData: testnetChainFallback,
@@ -4066,35 +4189,34 @@ function useChains(networkId, options = {}) {
4066
4189
  }
4067
4190
  }
4068
4191
  );
4192
+ const { data: envChainInfos, error: envChainInfoError } = useQuery(
4193
+ needFetchFromAPI && env !== "prod" ? `/v1/public/chain_info${brokerIdQuery}` : null,
4194
+ commonSwrOpts
4195
+ );
4196
+ const { swapChains, swapChainsError } = useSwapChains();
4069
4197
  const chains = React.useMemo(() => {
4070
- const tokenChains = fillChainsInfo(
4071
- tokenChainsRes,
4072
- filterFun.current,
4073
- chainInfos
4074
- );
4075
- const testTokenChains = fillChainsInfo(
4076
- testTokenChainsRes,
4077
- void 0,
4078
- testChainInfos
4079
- );
4080
- let testnetArr = needFetchFromAPI ? filterAndUpdateChains(testTokenChains, testChainInfos, void 0, true) : customChains?.testnet;
4081
- tokenChains?.forEach((item) => {
4082
- const chainId = item.network_infos?.chain_id;
4083
- chainsMap.current.set(chainId, item);
4198
+ const mainnetChains = formatChains({
4199
+ tokenChains: tokenChainsRes,
4200
+ chainInfos,
4201
+ swapChains,
4202
+ filter: filterFun.current,
4203
+ mainnet: true,
4204
+ chainTransformer
4084
4205
  });
4085
- testnetArr.forEach((chain) => {
4206
+ const testnetChains = formatChains({
4207
+ tokenChains: testTokenChainsRes,
4208
+ chainInfos: formatTestnetChainInfos(testChainInfos, envChainInfos),
4209
+ swapChains,
4210
+ mainnet: false,
4211
+ chainTransformer
4212
+ });
4213
+ let mainnetArr = needFetchFromAPI ? mainnetChains : customChains?.mainnet;
4214
+ let testnetArr = needFetchFromAPI ? testnetChains : customChains?.testnet;
4215
+ testnetArr?.forEach((chain) => {
4086
4216
  chainsMap.current.set(chain.network_infos?.chain_id, chain);
4087
4217
  });
4088
- let mainnetArr = [];
4089
- mainnetArr = filterAndUpdateChains(
4090
- tokenChains,
4091
- chainInfos,
4092
- filterFun.current
4093
- );
4094
- mainnetArr = needFetchFromAPI ? mainnetArr : customChains?.mainnet;
4095
- mainnetArr.forEach((item) => {
4096
- const chainId = item.network_infos?.chain_id;
4097
- chainsMap.current.set(chainId, item);
4218
+ mainnetArr?.forEach((chain) => {
4219
+ chainsMap.current.set(chain.network_infos?.chain_id, chain);
4098
4220
  });
4099
4221
  mainnetArr = filterByAllowedChains(mainnetArr, allowedChains?.mainnet);
4100
4222
  testnetArr = filterByAllowedChains(
@@ -4123,7 +4245,10 @@ function useChains(networkId, options = {}) {
4123
4245
  testTokenChainsRes,
4124
4246
  customChains,
4125
4247
  pickField,
4126
- allowedChains
4248
+ allowedChains,
4249
+ swapChains,
4250
+ chainTransformer,
4251
+ envChainInfos
4127
4252
  ]);
4128
4253
  const findByChainId = React.useCallback(
4129
4254
  (chainId, field) => {
@@ -4154,7 +4279,7 @@ function useChains(networkId, options = {}) {
4154
4279
  {
4155
4280
  findByChainId,
4156
4281
  checkChainSupport,
4157
- error: tokenError
4282
+ error: tokenError || swapChainsError
4158
4283
  }
4159
4284
  ];
4160
4285
  }
@@ -4166,80 +4291,173 @@ function _checkChainSupport(chainId, chains) {
4166
4291
  return chain.network_infos.chain_id === chainId;
4167
4292
  });
4168
4293
  }
4169
- function fillChainsInfo(chains, filter, chainInfos) {
4170
- const _chains = [];
4171
- chains?.forEach((item) => {
4172
- item.chain_details.forEach((chain) => {
4173
- const chainId = Number(chain.chain_id);
4174
- const chainInfo = chainInfos?.find(
4175
- (item2) => item2.chain_id == chainId
4176
- );
4177
- const _chain = {
4178
- network_infos: {
4179
- name: chain.chain_name ?? chainInfo?.name ?? "--",
4180
- chain_id: chainId,
4181
- withdrawal_fee: chain.withdrawal_fee,
4182
- cross_chain_withdrawal_fee: chain.cross_chain_withdrawal_fee,
4183
- bridgeless: true
4184
- },
4185
- token_infos: [
4186
- {
4187
- symbol: item.token,
4188
- address: chain.contract_address,
4189
- decimals: chain.decimals,
4190
- display_name: chain.display_name
4191
- }
4192
- ]
4294
+ function filterByAllowedChains(chains, allowedChains) {
4295
+ if (!allowedChains) {
4296
+ return chains;
4297
+ }
4298
+ return chains.filter(
4299
+ (chain) => allowedChains.some(
4300
+ (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
4301
+ )
4302
+ );
4303
+ }
4304
+ function useSwapChains() {
4305
+ const { enableSwapDeposit } = React.useContext(OrderlyContext);
4306
+ const { data: swapChainsRes, error: swapChainsError } = useSWR__namespace.default(
4307
+ () => enableSwapDeposit ? "https://fi-api.woo.org/swap_support" : null,
4308
+ (url) => fetch(url).then((res) => res.json()),
4309
+ {
4310
+ revalidateIfStale: false,
4311
+ revalidateOnFocus: false,
4312
+ revalidateOnReconnect: false,
4313
+ // If false, undefined data gets cached against the key.
4314
+ revalidateOnMount: true,
4315
+ // dont duplicate a request w/ same key for 1hr
4316
+ dedupingInterval: 36e5
4317
+ }
4318
+ );
4319
+ const swapChains = React.useMemo(() => {
4320
+ if (!enableSwapDeposit || !swapChainsRes || !swapChainsRes.data) {
4321
+ return [];
4322
+ }
4323
+ const data = swapChainsRes.data;
4324
+ return Object.keys(data).map((key) => {
4325
+ const chain = data[key];
4326
+ const { network_infos, token_infos } = chain;
4327
+ const networkInfos = {
4328
+ ...network_infos,
4329
+ // swap deposit will use shortName to get swap info
4330
+ shortName: key,
4331
+ cross_chain_router: network_infos?.woofi_dex_cross_chain_router,
4332
+ depositor: network_infos?.woofi_dex_depositor,
4333
+ est_txn_mins: network_infos?.est_txn_mins
4193
4334
  };
4194
- if (typeof filter === "function") {
4195
- if (!filter(_chain))
4196
- return;
4335
+ const nativeToken = token_infos.find(
4336
+ (item) => item.symbol === network_infos.currency_symbol
4337
+ );
4338
+ if (nativeToken) {
4339
+ networkInfos.currency_decimal = nativeToken.decimals;
4340
+ } else {
4341
+ networkInfos.currency_decimal = 18;
4197
4342
  }
4198
- _chains.push(_chain);
4343
+ const tokenInfos = token_infos?.filter((item) => item.swap_enable).map((item) => {
4344
+ const { woofi_dex_precision, ...rest } = item;
4345
+ return {
4346
+ ...rest,
4347
+ precision: woofi_dex_precision
4348
+ };
4349
+ });
4350
+ return {
4351
+ network_infos: networkInfos,
4352
+ token_infos: tokenInfos || []
4353
+ };
4199
4354
  });
4200
- });
4201
- return _chains;
4355
+ }, [enableSwapDeposit, swapChainsRes]);
4356
+ return { swapChains, swapChainsError };
4202
4357
  }
4203
- function filterAndUpdateChains(chains, chainInfos, filter, isTestNet) {
4204
- const chainsMap = /* @__PURE__ */ new Map();
4205
- chains.forEach((chain) => {
4206
- const _chain = { ...chain };
4207
- const networkInfo = chainInfos?.find(
4208
- (item) => item.chain_id == chain.network_infos.chain_id
4358
+ function formatChains({
4359
+ chainInfos = [],
4360
+ tokenChains = [],
4361
+ swapChains = [],
4362
+ filter,
4363
+ mainnet,
4364
+ chainTransformer
4365
+ }) {
4366
+ const chains = [];
4367
+ for (const chainInfo of chainInfos) {
4368
+ const chainId = Number(chainInfo.chain_id);
4369
+ const swapChainInfo = swapChains.find(
4370
+ (item) => item.network_infos.chain_id === chainId
4209
4371
  );
4210
- if (networkInfo) {
4211
- const { name, public_rpc_url, currency_symbol, explorer_base_url } = networkInfo;
4212
- _chain.network_infos = {
4213
- ..._chain.network_infos,
4214
- name,
4215
- shortName: name,
4216
- public_rpc_url,
4217
- currency_symbol,
4218
- bridge_enable: true,
4219
- mainnet: !isTestNet,
4220
- explorer_base_url
4221
- // est_txn_mins: null,
4372
+ const swapNetworkInfo = swapChainInfo?.network_infos;
4373
+ const swapTokenInfos = swapChainInfo?.token_infos || [];
4374
+ const {
4375
+ name,
4376
+ public_rpc_url,
4377
+ currency_symbol,
4378
+ explorer_base_url,
4379
+ vault_address
4380
+ } = chainInfo;
4381
+ const { shortName, cross_chain_router, depositor, est_txn_mins } = swapNetworkInfo || {};
4382
+ const network_infos = {
4383
+ name,
4384
+ chain_id: chainId,
4385
+ bridgeless: true,
4386
+ mainnet,
4387
+ public_rpc_url,
4388
+ currency_symbol,
4389
+ bridge_enable: true,
4390
+ explorer_base_url,
4391
+ // swap field
4392
+ shortName: shortName ?? name,
4393
+ cross_chain_router,
4394
+ depositor,
4395
+ est_txn_mins,
4396
+ vault_address
4397
+ };
4398
+ const tokenInfos = tokenChains.filter(
4399
+ (item) => item.chain_details.some((item2) => Number(item2.chain_id) === chainId)
4400
+ ).map((item) => {
4401
+ const chain = item.chain_details.find(
4402
+ (item2) => Number(item2.chain_id) === chainId
4403
+ );
4404
+ return {
4405
+ symbol: item.token,
4406
+ // if contract_address is not exist, use nativeTokenAddress to place holder
4407
+ address: chain?.contract_address || types.nativeTokenAddress,
4408
+ /** chain decimals */
4409
+ decimals: chain?.decimals,
4410
+ // chain_decimals: chain?.decimals,
4411
+ /** token decimals */
4412
+ token_decimal: item?.decimals,
4413
+ precision: item.decimals,
4414
+ display_name: chain?.display_name,
4415
+ withdrawal_fee: chain?.withdrawal_fee,
4416
+ cross_chain_withdrawal_fee: chain?.cross_chain_withdrawal_fee,
4417
+ minimum_withdraw_amount: item.minimum_withdraw_amount,
4418
+ base_weight: item.base_weight,
4419
+ discount_factor: item.discount_factor,
4420
+ haircut: item.haircut,
4421
+ user_max_qty: item.user_max_qty,
4422
+ is_collateral: item.is_collateral,
4423
+ swap_enable: false
4222
4424
  };
4223
- }
4425
+ });
4426
+ const swapTokens = swapTokenInfos?.filter((item) => {
4427
+ return !tokenInfos?.some((token) => token.symbol === item.symbol);
4428
+ });
4429
+ const _chain = {
4430
+ network_infos,
4431
+ token_infos: [...tokenInfos, ...swapTokens]
4432
+ };
4224
4433
  if (typeof filter === "function") {
4225
4434
  if (!filter(_chain))
4226
- return;
4227
- }
4228
- if (networkInfo) {
4229
- chainsMap.set(chain.network_infos.chain_id, _chain);
4435
+ continue;
4230
4436
  }
4231
- });
4232
- return Array.from(chainsMap.values());
4437
+ chains.push(_chain);
4438
+ }
4439
+ if (typeof chainTransformer === "function") {
4440
+ return chainTransformer({
4441
+ chains,
4442
+ chainInfos,
4443
+ tokenChains,
4444
+ swapChains,
4445
+ mainnet
4446
+ });
4447
+ }
4448
+ return chains;
4233
4449
  }
4234
- function filterByAllowedChains(chains, allowedChains) {
4235
- if (!allowedChains) {
4236
- return chains;
4450
+ function formatTestnetChainInfos(chainInfos, envChainInfos) {
4451
+ if (!chainInfos || !envChainInfos || !Array.isArray(chainInfos) || !Array.isArray(envChainInfos)) {
4452
+ return chainInfos;
4237
4453
  }
4238
- return chains.filter(
4239
- (chain) => allowedChains.some(
4240
- (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
4241
- )
4242
- );
4454
+ return chainInfos.map((chain) => {
4455
+ const info = envChainInfos.find((item) => item.chain_id === chain.chain_id);
4456
+ if (info) {
4457
+ chain.vault_address = info.vault_address;
4458
+ }
4459
+ return chain;
4460
+ });
4243
4461
  }
4244
4462
  function useStorageChain() {
4245
4463
  const [chain, setChain] = useLocalStorage(types.ChainKey, null);
@@ -4261,9 +4479,10 @@ function useStorageChain() {
4261
4479
  var useChain = (token) => {
4262
4480
  const { data, isLoading } = useQuery("/v1/public/token");
4263
4481
  const chains = React.useMemo(() => {
4264
- if (!data)
4482
+ if (!data) {
4265
4483
  return null;
4266
- let item = data.find((chain) => chain.token === token);
4484
+ }
4485
+ const item = data.find((chain) => chain.token === token);
4267
4486
  if (item) {
4268
4487
  item.chain_details = item.chain_details.map((d) => {
4269
4488
  const chain = types.chainsInfoMap.get(Number(d.chain_id));
@@ -4330,19 +4549,72 @@ var useHoldingStream = () => {
4330
4549
  };
4331
4550
  };
4332
4551
 
4552
+ // src/orderly/useMaxWithdrawal.ts
4553
+ var { maxWithdrawalUSDC, maxWithdrawalOtherCollateral, collateralRatio: collateralRatio2 } = perp.account;
4554
+ function useMaxWithdrawal(token) {
4555
+ const { unsettledPnL, freeCollateral } = useCollateral();
4556
+ const tokenInfo = useTokenInfo(token);
4557
+ const { data: indexPrices } = useIndexPricesStream();
4558
+ const { usdc, data: holdings = [] } = useHoldingStream();
4559
+ const holding = React.useMemo(() => {
4560
+ return holdings?.find((item) => item?.token === token);
4561
+ }, [holdings, token]);
4562
+ const usdcBalance = usdc?.holding ?? 0;
4563
+ const indexPrice = React.useMemo(() => {
4564
+ if (token === "USDC") {
4565
+ return 1;
4566
+ }
4567
+ const symbol = `PERP_${token}_USDC`;
4568
+ return indexPrices[symbol] ?? 0;
4569
+ }, [token, indexPrices]);
4570
+ const memoizedCollateralRatio = React.useMemo(() => {
4571
+ const { base_weight = 0, discount_factor = 0 } = tokenInfo || {};
4572
+ const holdingQty = holding?.holding ?? 0;
4573
+ return collateralRatio2({
4574
+ baseWeight: base_weight,
4575
+ discountFactor: discount_factor,
4576
+ collateralQty: holdingQty,
4577
+ collateralCap: tokenInfo?.user_max_qty ?? holdingQty,
4578
+ indexPrice
4579
+ });
4580
+ }, [holdings, tokenInfo, indexPrice, token, holding]);
4581
+ const maxAmount = React.useMemo(() => {
4582
+ if (token === "USDC") {
4583
+ return maxWithdrawalUSDC({
4584
+ USDCBalance: usdcBalance,
4585
+ freeCollateral,
4586
+ upnl: unsettledPnL ?? 0
4587
+ });
4588
+ }
4589
+ return maxWithdrawalOtherCollateral({
4590
+ collateralQty: holding?.holding ?? 0,
4591
+ freeCollateral,
4592
+ indexPrice,
4593
+ weight: memoizedCollateralRatio
4594
+ });
4595
+ }, [
4596
+ usdcBalance,
4597
+ freeCollateral,
4598
+ unsettledPnL,
4599
+ memoizedCollateralRatio,
4600
+ holdings,
4601
+ indexPrice,
4602
+ token,
4603
+ holding
4604
+ ]);
4605
+ return maxAmount;
4606
+ }
4607
+
4333
4608
  // src/orderly/useWithdraw.ts
4334
4609
  var useWithdraw = (options) => {
4335
- const { account: account7, state } = useAccount();
4610
+ const { srcChainId, token, decimals } = options;
4611
+ const { account: account9, state } = useAccount();
4336
4612
  const [isLoading, setIsLoading] = React.useState(false);
4337
4613
  const { unsettledPnL, availableBalance, freeCollateral } = useCollateral();
4338
4614
  const networkId = useConfig("networkId");
4339
4615
  const [_, { findByChainId }] = useChains(void 0);
4340
- useEventEmitter();
4341
4616
  const { track: track2 } = useTrack();
4342
- const { usdc } = useHoldingStream();
4343
- const maxAmount = React.useMemo(() => {
4344
- return freeCollateral;
4345
- }, [freeCollateral]);
4617
+ const maxAmount = useMaxWithdrawal(token);
4346
4618
  const availableWithdraw = React.useMemo(() => {
4347
4619
  if (unsettledPnL < 0) {
4348
4620
  return freeCollateral;
@@ -4354,19 +4626,19 @@ var useWithdraw = (options) => {
4354
4626
  let chain;
4355
4627
  if (networkId === "testnet") {
4356
4628
  chain = findByChainId(
4357
- utils.isTestnet(options?.srcChainId) ? options?.srcChainId : types.ARBITRUM_TESTNET_CHAINID
4629
+ utils.isTestnet(srcChainId) ? srcChainId : types.ARBITRUM_TESTNET_CHAINID
4358
4630
  );
4359
4631
  } else {
4360
- chain = findByChainId(options?.srcChainId);
4632
+ chain = findByChainId(srcChainId);
4361
4633
  if (!chain?.network_infos?.bridgeless) {
4362
4634
  chain = findByChainId(types.ARBITRUM_MAINNET_CHAINID);
4363
4635
  }
4364
4636
  }
4365
4637
  return chain;
4366
- }, [networkId, findByChainId, options?.srcChainId]);
4638
+ }, [networkId, findByChainId, srcChainId]);
4367
4639
  const dst = React.useMemo(() => {
4368
4640
  const USDC = targetChain?.token_infos.find(
4369
- (token) => token.symbol === "USDC"
4641
+ (token2) => token2.symbol === "USDC"
4370
4642
  );
4371
4643
  return {
4372
4644
  symbol: USDC?.display_name || "USDC",
@@ -4378,7 +4650,7 @@ var useWithdraw = (options) => {
4378
4650
  }, [targetChain]);
4379
4651
  const withdraw = React.useCallback(
4380
4652
  (inputs) => {
4381
- return account7.assetsManager.withdraw({ ...inputs, decimals: 6 }).then((res) => {
4653
+ return account9.assetsManager.withdraw({ ...inputs, decimals: decimals ?? 6 }).then((res) => {
4382
4654
  if (res.success) {
4383
4655
  track2(types.TrackerEventName.withdrawSuccess, {
4384
4656
  wallet: state?.connectWallet?.name,
@@ -4397,16 +4669,17 @@ var useWithdraw = (options) => {
4397
4669
  throw err;
4398
4670
  });
4399
4671
  },
4400
- [state, targetChain, state, options?.decimals]
4672
+ [state, targetChain, state, decimals]
4401
4673
  );
4402
4674
  return {
4403
4675
  dst,
4404
4676
  withdraw,
4405
4677
  isLoading,
4406
4678
  maxAmount,
4679
+ unsettledPnL,
4407
4680
  availableBalance,
4408
- availableWithdraw,
4409
- unsettledPnL
4681
+ /** @deprecated use maxAmount instead */
4682
+ availableWithdraw
4410
4683
  };
4411
4684
  };
4412
4685
  var useDeposit = (options) => {
@@ -4419,7 +4692,7 @@ var useDeposit = (options) => {
4419
4692
  const [depositFeeRevalidating, setDepositFeeRevalidating] = React.useState(false);
4420
4693
  const [balance, setBalance] = React.useState("0");
4421
4694
  const [allowance, setAllowance] = React.useState("0");
4422
- const { account: account7, state } = useAccount();
4695
+ const { account: account9, state } = useAccount();
4423
4696
  const { track: track2 } = useTrack();
4424
4697
  const prevAddress = React.useRef();
4425
4698
  const getBalanceListener = React.useRef();
@@ -4445,8 +4718,8 @@ var useDeposit = (options) => {
4445
4718
  symbol: "USDC",
4446
4719
  address: USDC?.address,
4447
4720
  decimals: USDC?.decimals,
4448
- chainId: targetChain?.network_infos?.chain_id,
4449
- network: targetChain?.network_infos?.shortName
4721
+ chainId: targetChain?.network_infos.chain_id,
4722
+ network: targetChain?.network_infos.shortName
4450
4723
  };
4451
4724
  }, [targetChain]);
4452
4725
  const isNativeToken = React.useMemo(
@@ -4456,12 +4729,12 @@ var useDeposit = (options) => {
4456
4729
  const fetchBalanceHandler = React.useCallback(
4457
4730
  async (address, decimals) => {
4458
4731
  let balance2;
4459
- if (!!address && types.isNativeTokenChecker(address)) {
4460
- balance2 = await account7.assetsManager.getNativeBalance({
4732
+ if (address && types.isNativeTokenChecker(address)) {
4733
+ balance2 = await account9.assetsManager.getNativeBalance({
4461
4734
  decimals
4462
4735
  });
4463
4736
  } else {
4464
- balance2 = await account7.assetsManager.getBalance(address, { decimals });
4737
+ balance2 = await account9.assetsManager.getBalance(address, { decimals });
4465
4738
  }
4466
4739
  return balance2;
4467
4740
  },
@@ -4487,29 +4760,30 @@ var useDeposit = (options) => {
4487
4760
  continue;
4488
4761
  }
4489
4762
  tasks.push(
4490
- account7.assetsManager.getBalanceByAddress(token.address, {
4763
+ account9.assetsManager.getBalance(token.address, {
4491
4764
  decimals: token?.decimals
4492
4765
  })
4493
4766
  );
4494
4767
  }
4495
- await Promise.all(tasks);
4768
+ const balances = await Promise.all(tasks);
4769
+ return balances;
4496
4770
  }, []);
4497
4771
  const getAllowance = async (inputs) => {
4498
- const { address, vaultAddress, decimals } = inputs;
4499
- const key = `${address}-${vaultAddress}`;
4772
+ const { address, vaultAddress: vaultAddress2, decimals } = inputs;
4773
+ const key = `${address}-${vaultAddress2}`;
4500
4774
  if (prevAddress.current === key)
4501
4775
  return;
4502
- if (!address || !vaultAddress)
4776
+ if (!address || !vaultAddress2)
4503
4777
  return;
4504
- if (address && types.isNativeTokenChecker(address))
4778
+ if (types.isNativeTokenChecker(address))
4505
4779
  return;
4506
4780
  prevAddress.current = key;
4507
- const allowance2 = await account7.assetsManager.getAllowance({
4781
+ const allowance2 = await account9.assetsManager.getAllowance({
4508
4782
  address,
4509
- vaultAddress,
4783
+ vaultAddress: vaultAddress2,
4510
4784
  decimals
4511
4785
  });
4512
- setAllowance(() => allowance2);
4786
+ setAllowance(allowance2);
4513
4787
  return allowance2;
4514
4788
  };
4515
4789
  const getAllowanceByDefaultAddress = async (inputs) => {
@@ -4519,12 +4793,31 @@ var useDeposit = (options) => {
4519
4793
  if (!address || types.isNativeTokenChecker(address))
4520
4794
  return;
4521
4795
  prevAddress.current = address;
4522
- const allowance2 = await account7.assetsManager.getAllowance({
4796
+ const allowance2 = await account9.assetsManager.getAllowance({
4523
4797
  address,
4524
- decimals
4798
+ decimals,
4799
+ vaultAddress
4525
4800
  });
4526
- setAllowance(() => allowance2);
4801
+ setAllowance(allowance2);
4802
+ return allowance2;
4527
4803
  };
4804
+ const vaultAddress = React.useMemo(() => {
4805
+ if (dst.chainId !== options.srcChainId) {
4806
+ return options.crossChainRouteAddress;
4807
+ }
4808
+ if (options.srcToken !== (options.dstToken || dst.symbol)) {
4809
+ return options.depositorAddress;
4810
+ }
4811
+ return targetChain?.network_infos.vault_address;
4812
+ }, [
4813
+ dst,
4814
+ options.srcChainId,
4815
+ options.srcToken,
4816
+ options.dstToken,
4817
+ options.crossChainRouteAddress,
4818
+ options.depositorAddress,
4819
+ targetChain
4820
+ ]);
4528
4821
  const queryBalance = useDebounce.useDebouncedCallback(
4529
4822
  (address, decimals) => {
4530
4823
  fetchBalance(address, decimals).finally(() => {
@@ -4544,89 +4837,113 @@ var useDeposit = (options) => {
4544
4837
  return;
4545
4838
  setBalanceRevalidating(true);
4546
4839
  queryBalance(options.address, options.decimals);
4547
- const params = {
4548
- address: options.address,
4549
- decimals: options.decimals
4550
- };
4551
- if (account7.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4840
+ if (account9.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4552
4841
  setAllowance(
4553
- account7.walletAdapter.formatUnits(types.MaxUint256, options.decimals)
4842
+ account9.walletAdapter.formatUnits(types.MaxUint256, options.decimals)
4554
4843
  );
4555
4844
  return;
4556
4845
  }
4557
- if (dst.chainId !== options.srcChainId) {
4558
- queryAllowance(params);
4846
+ if (vaultAddress && options.address) {
4847
+ queryAllowance({
4848
+ address: options.address,
4849
+ decimals: options.decimals,
4850
+ vaultAddress
4851
+ });
4559
4852
  } else {
4560
- if (dst.symbol !== options.srcToken) {
4561
- queryAllowance(params);
4562
- } else {
4563
- getAllowanceByDefaultAddress(params);
4564
- }
4853
+ getAllowanceByDefaultAddress({
4854
+ address: options.address,
4855
+ decimals: options.decimals
4856
+ });
4565
4857
  }
4566
4858
  }, [
4567
4859
  state.status,
4568
4860
  options.address,
4569
- options.srcChainId,
4570
- options.srcToken,
4571
4861
  options.decimals,
4572
- account7.address,
4573
- dst.chainId,
4574
- dst.symbol
4862
+ account9.address,
4863
+ vaultAddress
4575
4864
  ]);
4576
4865
  const updateAllowanceWhenTxSuccess = React.useCallback(
4577
4866
  (txHash) => {
4578
- return account7.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4867
+ return account9.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4579
4868
  if (receipt.status === 1) {
4580
- account7.assetsManager.getAllowance({ address: options.address }).then((allowance2) => {
4581
- setAllowance(() => allowance2);
4869
+ account9.assetsManager.getAllowance({
4870
+ address: options.address,
4871
+ decimals: options.decimals,
4872
+ vaultAddress
4873
+ }).then((allowance2) => {
4874
+ setAllowance(allowance2);
4582
4875
  });
4583
4876
  }
4584
4877
  });
4585
4878
  },
4586
- [account7, options.address]
4879
+ [account9, options.address, options.decimals, vaultAddress]
4587
4880
  );
4881
+ const enquireAllowance = React.useCallback(async () => {
4882
+ if (isNativeToken) {
4883
+ return;
4884
+ }
4885
+ if (!options.address) {
4886
+ throw new Error("address is required");
4887
+ }
4888
+ const _allowance = await account9.assetsManager.getAllowance({
4889
+ address: options.address,
4890
+ vaultAddress,
4891
+ decimals: options.decimals
4892
+ });
4893
+ setAllowance(_allowance);
4894
+ if (new utils.Decimal(quantity).greaterThan(_allowance)) {
4895
+ throw new types.SDKError("Insufficient allowance");
4896
+ }
4897
+ return _allowance;
4898
+ }, [
4899
+ account9,
4900
+ options.address,
4901
+ options.decimals,
4902
+ vaultAddress,
4903
+ quantity,
4904
+ isNativeToken
4905
+ ]);
4588
4906
  const approve = React.useCallback(
4589
4907
  async (amount) => {
4590
4908
  if (!options.address) {
4591
- throw new types.SDKError("Address is required");
4909
+ throw new Error("address is required");
4592
4910
  }
4593
- return account7.assetsManager.approve({
4911
+ return account9.assetsManager.approve({
4594
4912
  address: options.address,
4595
4913
  amount,
4914
+ vaultAddress,
4596
4915
  decimals: options.decimals
4597
- }).then((res) => {
4598
- return updateAllowanceWhenTxSuccess(res.hash);
4599
- }).catch((e) => {
4600
- throw e;
4916
+ }).then((result) => {
4917
+ return updateAllowanceWhenTxSuccess(result.hash);
4601
4918
  });
4602
4919
  },
4603
- [account7, getAllowance, options.address, options.decimals, dst]
4920
+ [
4921
+ account9,
4922
+ options.address,
4923
+ options.decimals,
4924
+ vaultAddress,
4925
+ updateAllowanceWhenTxSuccess
4926
+ ]
4604
4927
  );
4605
4928
  const deposit = React.useCallback(async () => {
4606
- if (!options.address) {
4607
- throw new types.SDKError("Address is required");
4608
- }
4609
- const _allowance = await account7.assetsManager.getAllowance({
4610
- address: options.address,
4611
- decimals: options.decimals
4612
- });
4613
- setAllowance(() => _allowance);
4614
- if (new utils.Decimal(quantity).greaterThan(_allowance)) {
4615
- throw new types.SDKError("Insufficient allowance");
4616
- }
4617
- return account7.assetsManager.deposit({
4929
+ await enquireAllowance();
4930
+ const inputs = {
4618
4931
  amount: quantity,
4619
4932
  fee: depositFee,
4620
- decimals: options.decimals
4621
- }).then((res) => {
4933
+ decimals: options.decimals,
4934
+ token: options.srcToken,
4935
+ vaultAddress
4936
+ };
4937
+ const depositPromise = isNativeToken ? account9.assetsManager.depositNativeToken(inputs) : account9.assetsManager.deposit(inputs);
4938
+ return depositPromise.then((result) => {
4939
+ updateAllowanceWhenTxSuccess(result.hash);
4940
+ setBalance((value) => new utils.Decimal(value).sub(quantity).toString());
4622
4941
  track2(types.TrackerEventName.depositSuccess, {
4623
4942
  wallet: state?.connectWallet?.name,
4624
4943
  network: targetChain?.network_infos.name,
4625
4944
  quantity
4626
4945
  });
4627
- updateAllowanceWhenTxSuccess(res.hash);
4628
- setBalance((value) => new utils.Decimal(value).sub(quantity).toString());
4629
- return res;
4946
+ return result;
4630
4947
  }).catch((e) => {
4631
4948
  track2(types.TrackerEventName.depositFailed, {
4632
4949
  wallet: state?.connectWallet?.name,
@@ -4636,16 +4953,23 @@ var useDeposit = (options) => {
4636
4953
  throw e;
4637
4954
  });
4638
4955
  }, [
4639
- account7,
4640
- fetchBalance,
4956
+ state,
4957
+ account9,
4641
4958
  quantity,
4642
4959
  depositFee,
4643
- options.address,
4644
- options.decimals
4960
+ targetChain,
4961
+ options.decimals,
4962
+ options.srcToken,
4963
+ enquireAllowance,
4964
+ updateAllowanceWhenTxSuccess,
4965
+ isNativeToken,
4966
+ vaultAddress
4645
4967
  ]);
4646
4968
  const loopGetBalance = async () => {
4647
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
4648
- const time = account7.walletAdapter?.chainNamespace === types.ChainNamespace.solana ? 1e4 : 3e3;
4969
+ if (getBalanceListener.current) {
4970
+ clearTimeout(getBalanceListener.current);
4971
+ }
4972
+ const time = account9.walletAdapter?.chainNamespace === types.ChainNamespace.solana ? 1e4 : 3e3;
4649
4973
  getBalanceListener.current = setTimeout(async () => {
4650
4974
  try {
4651
4975
  const balance2 = await fetchBalanceHandler(
@@ -4660,13 +4984,15 @@ var useDeposit = (options) => {
4660
4984
  };
4661
4985
  const getDepositFee = React.useCallback(
4662
4986
  async (quantity2) => {
4663
- return account7.assetsManager.getDepositFee({
4987
+ return account9.assetsManager.getDepositFee({
4664
4988
  amount: quantity2,
4665
4989
  chain: targetChain?.network_infos,
4666
- decimals: options.decimals
4990
+ decimals: options.decimals,
4991
+ token: options.srcToken,
4992
+ address: options.address
4667
4993
  });
4668
4994
  },
4669
- [account7, targetChain, options.decimals]
4995
+ [account9, targetChain, options.decimals, options.srcToken, options.address]
4670
4996
  );
4671
4997
  const enquiryDepositFee = React.useCallback(() => {
4672
4998
  if (isNaN(Number(quantity)) || !quantity || Number(quantity) === 0) {
@@ -4694,7 +5020,9 @@ var useDeposit = (options) => {
4694
5020
  }
4695
5021
  loopGetBalance();
4696
5022
  return () => {
4697
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
5023
+ if (getBalanceListener.current) {
5024
+ clearTimeout(getBalanceListener.current);
5025
+ }
4698
5026
  };
4699
5027
  }, [options.address, options.decimals]);
4700
5028
  return {
@@ -4713,12 +5041,26 @@ var useDeposit = (options) => {
4713
5041
  depositFeeRevalidating,
4714
5042
  approve,
4715
5043
  deposit,
4716
- fetchBalances,
4717
5044
  fetchBalance: fetchBalanceHandler,
5045
+ fetchBalances,
4718
5046
  /** set input quantity */
4719
5047
  setQuantity
4720
5048
  };
4721
5049
  };
5050
+
5051
+ // src/orderly/useConvert.ts
5052
+ var useConvert = (options) => {
5053
+ const { token = "" } = options;
5054
+ const { account: account9 } = useAccount();
5055
+ const maxAmount = useMaxWithdrawal(token);
5056
+ const convert = async (inputs) => {
5057
+ return account9.assetsManager.convert({
5058
+ ...inputs,
5059
+ converted_asset: token
5060
+ });
5061
+ };
5062
+ return { maxAmount, convert };
5063
+ };
4722
5064
  var fetcher3 = (url, options) => {
4723
5065
  const init2 = {
4724
5066
  method: options.arg.method,
@@ -4742,7 +5084,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4742
5084
  if (!url.startsWith("http")) {
4743
5085
  fullUrl = `${apiBaseUrl}${url}`;
4744
5086
  }
4745
- const account7 = useAccountInstance();
5087
+ const account9 = useAccountInstance();
4746
5088
  const { trigger, reset, data, error, isMutating } = useSWRMutation__default.default(
4747
5089
  fullUrl,
4748
5090
  // method === "POST" ? fetcher : deleteFetcher,
@@ -4762,7 +5104,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4762
5104
  url: newUrl,
4763
5105
  data: data2
4764
5106
  };
4765
- const signer = account7.signer;
5107
+ const signer = account9.signer;
4766
5108
  const signature = await signer.sign(payload, utils.getTimestamp());
4767
5109
  return trigger(
4768
5110
  {
@@ -4771,13 +5113,13 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4771
5113
  method,
4772
5114
  signature: {
4773
5115
  ...signature,
4774
- "orderly-account-id": accountId || _accountId || account7.accountId
5116
+ "orderly-account-id": accountId || _accountId || account9.accountId
4775
5117
  }
4776
5118
  },
4777
5119
  restOptions2
4778
5120
  );
4779
5121
  },
4780
- [trigger, account7, accountId]
5122
+ [trigger, account9, accountId]
4781
5123
  );
4782
5124
  return [
4783
5125
  mutation,
@@ -4792,8 +5134,8 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4792
5134
 
4793
5135
  // src/orderly/useTransfer.ts
4794
5136
  var useTransfer = (options) => {
4795
- const { fromAccountId } = options || {};
4796
- const { unsettledPnL, availableBalance, freeCollateral, holding } = useCollateral();
5137
+ const { fromAccountId, token } = options || {};
5138
+ const { unsettledPnL, holding } = useCollateral();
4797
5139
  const [doTransfer, { isMutating: submitting }] = useSubAccountMutation(
4798
5140
  "/v1/internal_transfer",
4799
5141
  "POST",
@@ -4802,9 +5144,9 @@ var useTransfer = (options) => {
4802
5144
  }
4803
5145
  );
4804
5146
  const transfer = React.useCallback(
4805
- async (token, receivers) => {
5147
+ async (token2, receivers) => {
4806
5148
  return doTransfer({
4807
- token,
5149
+ token: token2,
4808
5150
  receiver_list: Array.isArray(receivers) ? receivers : [receivers]
4809
5151
  }).then((res) => {
4810
5152
  if (res.success) {
@@ -4817,23 +5159,12 @@ var useTransfer = (options) => {
4817
5159
  },
4818
5160
  [doTransfer]
4819
5161
  );
4820
- const maxAmount = React.useMemo(() => {
4821
- return freeCollateral;
4822
- }, [freeCollateral]);
4823
- const availableTransfer = React.useMemo(() => {
4824
- if (unsettledPnL < 0) {
4825
- return freeCollateral;
4826
- } else {
4827
- return freeCollateral - unsettledPnL;
4828
- }
4829
- }, [freeCollateral, unsettledPnL]);
5162
+ const maxAmount = useMaxWithdrawal(token);
4830
5163
  return {
4831
5164
  submitting,
4832
5165
  transfer,
4833
5166
  maxAmount,
4834
5167
  unsettledPnL,
4835
- availableBalance,
4836
- availableTransfer,
4837
5168
  holding
4838
5169
  };
4839
5170
  };
@@ -6435,7 +6766,7 @@ var OrderFactory = class {
6435
6766
  };
6436
6767
  function useSubAccountQuery(query, options) {
6437
6768
  const { formatter, accountId, ...swrOptions } = options || {};
6438
- const { state, account: account7 } = useAccount();
6769
+ const { state, account: account9 } = useAccount();
6439
6770
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
6440
6771
  return useSWR__namespace.default(
6441
6772
  () => accountId && (state.status >= types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected) ? [query, accountId] : null,
@@ -6444,13 +6775,13 @@ function useSubAccountQuery(query, options) {
6444
6775
  },
6445
6776
  {
6446
6777
  ...swrOptions,
6447
- use: [...middleware, signatureMiddleware2(account7, accountId)],
6778
+ use: [...middleware, signatureMiddleware2(account9, accountId)],
6448
6779
  onError: () => {
6449
6780
  }
6450
6781
  }
6451
6782
  );
6452
6783
  }
6453
- function signatureMiddleware2(account7, accountId) {
6784
+ function signatureMiddleware2(account9, accountId) {
6454
6785
  const apiBaseUrl = useConfig("apiBaseUrl");
6455
6786
  return (useSWRNext) => {
6456
6787
  return (key, fetcher4, config) => {
@@ -6458,7 +6789,7 @@ function signatureMiddleware2(account7, accountId) {
6458
6789
  const extendedFetcher = async (args) => {
6459
6790
  const url = Array.isArray(args) ? args[0] : args;
6460
6791
  const fullUrl = `${apiBaseUrl}${url}`;
6461
- const signer = account7.signer;
6792
+ const signer = account9.signer;
6462
6793
  const payload = {
6463
6794
  method: "GET",
6464
6795
  url
@@ -6479,13 +6810,25 @@ function signatureMiddleware2(account7, accountId) {
6479
6810
  };
6480
6811
  }
6481
6812
  function formatPortfolio(inputs) {
6482
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
6483
- if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !accountInfo || symbolsInfo?.isNil) {
6813
+ const {
6814
+ holding,
6815
+ positions: positions3,
6816
+ markPrices,
6817
+ indexPrices,
6818
+ accountInfo,
6819
+ symbolsInfo,
6820
+ tokensInfo
6821
+ } = inputs;
6822
+ if (!holding || !positions3 || !Array.isArray(positions3.rows) || !markPrices || !indexPrices || !accountInfo || symbolsInfo?.isNil) {
6484
6823
  return null;
6485
6824
  }
6486
6825
  const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
6487
6826
  const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
6488
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
6827
+ const [USDC_holding, nonUSDC] = parseHolding(
6828
+ holding,
6829
+ indexPrices,
6830
+ tokensInfo
6831
+ );
6489
6832
  const usdc = holding.find((item) => item.token === "USDC");
6490
6833
  const totalCollateral = perp.account.totalCollateral({
6491
6834
  USDCHolding: USDC_holding,
@@ -6637,7 +6980,7 @@ function calcByPrice(positions3, markPrice, indexPrice) {
6637
6980
  var useSubAccountWS = (options) => {
6638
6981
  const { accountId } = options;
6639
6982
  const { configStore } = React.useContext(OrderlyContext);
6640
- const { state, account: account7 } = useAccount();
6983
+ const { state, account: account9 } = useAccount();
6641
6984
  const websocketClient = React.useRef(
6642
6985
  new net.WS({
6643
6986
  networkId: configStore.get("networkId"),
@@ -6645,7 +6988,7 @@ var useSubAccountWS = (options) => {
6645
6988
  // publicUrl: configStore.get("publicWsUrl"),
6646
6989
  privateUrl: configStore.get("privateWsUrl"),
6647
6990
  onSigntureRequest: async () => {
6648
- const signer = account7.signer;
6991
+ const signer = account9.signer;
6649
6992
  const timestamp = utils.getTimestamp();
6650
6993
  const result = await signer.signText(timestamp.toString());
6651
6994
  return { ...result, timestamp };
@@ -6670,11 +7013,12 @@ var useSubAccountDataObserver = (accountId) => {
6670
7013
  const { data: indexPrices } = useIndexPricesStream();
6671
7014
  const symbolsInfo = useSymbolsInfo();
6672
7015
  const fundingRates = useFundingRatesStore();
7016
+ const tokensInfo = useTokensInfo();
6673
7017
  const [holding, setHolding] = React.useState([]);
6674
7018
  const [positions3, setPositions] = React.useState(
6675
7019
  POSITION_EMPTY
6676
7020
  );
6677
- const [portfolio, setportfolio] = React.useState();
7021
+ const [portfolio, setPortfolio] = React.useState();
6678
7022
  const { data: accountInfo } = useSubAccountQuery(
6679
7023
  "/v1/client/info",
6680
7024
  { accountId, revalidateOnFocus: false }
@@ -6698,11 +7042,21 @@ var useSubAccountDataObserver = (accountId) => {
6698
7042
  holding,
6699
7043
  positions: positions3,
6700
7044
  markPrices,
7045
+ indexPrices,
6701
7046
  accountInfo,
6702
- symbolsInfo
7047
+ symbolsInfo,
7048
+ tokensInfo
6703
7049
  });
6704
- setportfolio(portfolio2);
6705
- }, [holding, positions3, markPrices, accountInfo, symbolsInfo]);
7050
+ setPortfolio(portfolio2);
7051
+ }, [
7052
+ holding,
7053
+ positions3,
7054
+ markPrices,
7055
+ indexPrices,
7056
+ accountInfo,
7057
+ symbolsInfo,
7058
+ tokensInfo
7059
+ ]);
6706
7060
  React.useEffect(() => {
6707
7061
  if (!positionsInfo)
6708
7062
  return;
@@ -6811,6 +7165,63 @@ var useSubAccountDataObserver = (accountId) => {
6811
7165
  }, [accountId]);
6812
7166
  return { portfolio, positions: positions3 };
6813
7167
  };
7168
+ var { maxWithdrawalUSDC: maxWithdrawalUSDC2, maxWithdrawalOtherCollateral: maxWithdrawalOtherCollateral2, collateralRatio: collateralRatio3 } = perp.account;
7169
+ function useSubAccountMaxWithdrawal(options) {
7170
+ const { token, unsettledPnL, freeCollateral, holdings } = options;
7171
+ const tokenInfo = useTokenInfo(token);
7172
+ const { data: indexPrices } = useIndexPricesStream();
7173
+ const usdc = React.useMemo(() => {
7174
+ const usdc2 = holdings?.find((item) => item.token === "USDC");
7175
+ return usdc2;
7176
+ }, [holdings]);
7177
+ const holding = React.useMemo(() => {
7178
+ return holdings?.find((item) => item?.token === token);
7179
+ }, [holdings, token]);
7180
+ const usdcBalance = usdc?.holding ?? 0;
7181
+ const indexPrice = React.useMemo(() => {
7182
+ if (token === "USDC") {
7183
+ return 1;
7184
+ }
7185
+ const symbol = `PERP_${token}_USDC`;
7186
+ return indexPrices[symbol] ?? 0;
7187
+ }, [token, indexPrices]);
7188
+ const memoizedCollateralRatio = React.useMemo(() => {
7189
+ const { base_weight = 0, discount_factor = 0 } = tokenInfo || {};
7190
+ const holdingQty = holding?.holding ?? 0;
7191
+ return collateralRatio3({
7192
+ baseWeight: base_weight,
7193
+ discountFactor: discount_factor,
7194
+ collateralQty: holdingQty,
7195
+ collateralCap: tokenInfo?.user_max_qty ?? holdingQty,
7196
+ indexPrice
7197
+ });
7198
+ }, [holdings, tokenInfo, indexPrice, token, holding]);
7199
+ const maxAmount = React.useMemo(() => {
7200
+ if (token === "USDC") {
7201
+ return maxWithdrawalUSDC2({
7202
+ USDCBalance: usdcBalance,
7203
+ freeCollateral,
7204
+ upnl: unsettledPnL ?? 0
7205
+ });
7206
+ }
7207
+ return maxWithdrawalOtherCollateral2({
7208
+ collateralQty: holding?.holding ?? 0,
7209
+ freeCollateral,
7210
+ indexPrice,
7211
+ weight: memoizedCollateralRatio
7212
+ });
7213
+ }, [
7214
+ usdcBalance,
7215
+ freeCollateral,
7216
+ unsettledPnL,
7217
+ memoizedCollateralRatio,
7218
+ holdings,
7219
+ indexPrice,
7220
+ token,
7221
+ holding
7222
+ ]);
7223
+ return maxAmount;
7224
+ }
6814
7225
  function offsetToPrice(inputs) {
6815
7226
  const { offset, entryPrice, orderType, orderSide } = inputs;
6816
7227
  if (!offset)
@@ -7610,7 +8021,7 @@ var useStorageLedgerAddress = () => {
7610
8021
  var usePrivateDataObserver = (options) => {
7611
8022
  const ws = useWS();
7612
8023
  const ee = useEventEmitter();
7613
- const { state, account: account7 } = useAccount();
8024
+ const { state, account: account9 } = useAccount();
7614
8025
  const { setAccountInfo, restoreHolding, cleanAll } = useAppStore(
7615
8026
  (state2) => state2.actions
7616
8027
  );
@@ -7643,9 +8054,9 @@ var usePrivateDataObserver = (options) => {
7643
8054
  positionsActions.clearAll();
7644
8055
  }
7645
8056
  };
7646
- account7.on(core.EVENT_NAMES.statusChanged, handler);
8057
+ account9.on(core.EVENT_NAMES.statusChanged, handler);
7647
8058
  return () => {
7648
- account7.off(core.EVENT_NAMES.statusChanged, handler);
8059
+ account9.off(core.EVENT_NAMES.statusChanged, handler);
7649
8060
  };
7650
8061
  }, []);
7651
8062
  React.useEffect(() => {
@@ -7666,7 +8077,7 @@ var usePrivateDataObserver = (options) => {
7666
8077
  }
7667
8078
  );
7668
8079
  React.useEffect(() => {
7669
- if (!account7.accountId)
8080
+ if (!account9.accountId)
7670
8081
  return;
7671
8082
  const unsubscribe = ws.privateSubscribe(
7672
8083
  {
@@ -7685,11 +8096,11 @@ var usePrivateDataObserver = (options) => {
7685
8096
  }
7686
8097
  );
7687
8098
  return () => unsubscribe?.();
7688
- }, [account7.accountId]);
8099
+ }, [account9.accountId]);
7689
8100
  const isHoldingInit = React.useRef(false);
7690
8101
  React.useEffect(() => {
7691
8102
  isHoldingInit.current = false;
7692
- }, [state.accountId]);
8103
+ }, [state.address]);
7693
8104
  React.useEffect(() => {
7694
8105
  if (!holding) {
7695
8106
  return;
@@ -7858,6 +8269,7 @@ var usePublicDataObserver = () => {
7858
8269
  (state) => state.actions
7859
8270
  );
7860
8271
  const { updateMarket } = useMarketStore((state) => state.actions);
8272
+ const setTokensInfo = useTokensInfoStore((state) => state.setTokensInfo);
7861
8273
  useQuery(`/v1/public/info`, {
7862
8274
  ...publicQueryOptions,
7863
8275
  onSuccess(data) {
@@ -7910,6 +8322,16 @@ var usePublicDataObserver = () => {
7910
8322
  updateMarket(data);
7911
8323
  }
7912
8324
  });
8325
+ useQuery(`/v1/public/token`, {
8326
+ // revalidateOnFocus: false,
8327
+ ...publicQueryOptions,
8328
+ onSuccess(data) {
8329
+ if (!data || !data.length) {
8330
+ return [];
8331
+ }
8332
+ setTokensInfo(data);
8333
+ }
8334
+ });
7913
8335
  };
7914
8336
  function getEstFundingRate(data) {
7915
8337
  if (!data)
@@ -8024,7 +8446,7 @@ var ExtendedConfigStore = class extends core.DefaultConfigStore {
8024
8446
  }
8025
8447
  };
8026
8448
  var OrderlyConfigProvider = (props) => {
8027
- const [account7, setAccount] = React__default.default.useState(null);
8449
+ const [account9, setAccount] = React__default.default.useState(null);
8028
8450
  const {
8029
8451
  configStore,
8030
8452
  keyStore,
@@ -8035,7 +8457,9 @@ var OrderlyConfigProvider = (props) => {
8035
8457
  networkId,
8036
8458
  contracts,
8037
8459
  chainFilter,
8038
- customChains
8460
+ customChains,
8461
+ enableSwapDeposit = true,
8462
+ chainTransformer
8039
8463
  } = props;
8040
8464
  if (typeof configStore !== "undefined" && !configStore.get("brokerId")) {
8041
8465
  throw new types.SDKError(
@@ -8061,10 +8485,13 @@ var OrderlyConfigProvider = (props) => {
8061
8485
  new defaultSolanaAdapter.DefaultSolanaWalletAdapter()
8062
8486
  ];
8063
8487
  }, [walletAdapters]);
8488
+ const defaultOrderbookTickSizes = React.useMemo(() => {
8489
+ return props.orderbookDefaultTickSizes || DEFAULT_TICK_SIZES;
8490
+ }, [props.orderbookDefaultTickSizes]);
8064
8491
  React.useLayoutEffect(() => {
8065
- let account8 = core.SimpleDI.get(core.Account.instanceName);
8066
- if (!account8) {
8067
- account8 = new core.Account(
8492
+ let account10 = core.SimpleDI.get(core.Account.instanceName);
8493
+ if (!account10) {
8494
+ account10 = new core.Account(
8068
8495
  innerConfigStore,
8069
8496
  innerKeyStore,
8070
8497
  // innerGetWalletAdapter,
@@ -8073,9 +8500,9 @@ var OrderlyConfigProvider = (props) => {
8073
8500
  contracts
8074
8501
  }
8075
8502
  );
8076
- core.SimpleDI.registerByName(core.Account.instanceName, account8);
8503
+ core.SimpleDI.registerByName(core.Account.instanceName, account10);
8077
8504
  }
8078
- setAccount(account8);
8505
+ setAccount(account10);
8079
8506
  }, []);
8080
8507
  const filteredChains = React.useMemo(() => {
8081
8508
  if (typeof chainFilter === "function") {
@@ -8083,7 +8510,7 @@ var OrderlyConfigProvider = (props) => {
8083
8510
  }
8084
8511
  return chainFilter;
8085
8512
  }, [props.chainFilter, innerConfigStore]);
8086
- if (!account7) {
8513
+ if (!account9) {
8087
8514
  return null;
8088
8515
  }
8089
8516
  return /* @__PURE__ */ jsxRuntime.jsx(
@@ -8097,7 +8524,10 @@ var OrderlyConfigProvider = (props) => {
8097
8524
  filteredChains,
8098
8525
  walletAdapters: innerWalletAdapters,
8099
8526
  // apiBaseUrl,
8100
- customChains
8527
+ customChains,
8528
+ enableSwapDeposit,
8529
+ chainTransformer,
8530
+ defaultOrderbookTickSizes
8101
8531
  },
8102
8532
  children: /* @__PURE__ */ jsxRuntime.jsx(StatusProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(DataCenterProvider, { children: props.children }) })
8103
8533
  }
@@ -9922,9 +10352,9 @@ var useAllBrokers = () => {
9922
10352
  };
9923
10353
  var useCurEpochEstimate = (type) => {
9924
10354
  const [data, setData] = React.useState(void 0);
9925
- const { account: account7 } = useAccount();
10355
+ const { account: account9 } = useAccount();
9926
10356
  const brokers = useAllBrokers();
9927
- const address = account7.address;
10357
+ const address = account9.address;
9928
10358
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/current_epoch_estimate?address=${address}` : `/v1/public/market_making_rewards/current_epoch_estimate?address=${address}`;
9929
10359
  const { data: estimateData } = useQuery(address !== void 0 ? path2 : "", {
9930
10360
  formatter: (res) => {
@@ -14884,14 +15314,14 @@ var DistributionId = /* @__PURE__ */ ((DistributionId2) => {
14884
15314
  })(DistributionId || {});
14885
15315
  var useGetClaimed = (id) => {
14886
15316
  const [data, setData] = React.useState(0);
14887
- const { account: account7 } = useAccount();
14888
- const address = account7.address;
15317
+ const { account: account9 } = useAccount();
15318
+ const address = account9.address;
14889
15319
  const env = useGetEnv();
14890
15320
  const refresh = React.useCallback(() => {
14891
15321
  const params = getContractByEnv(env);
14892
15322
  if (typeof address === "undefined")
14893
15323
  return;
14894
- account7.walletAdapter?.callOnChain(
15324
+ account9.walletAdapter?.callOnChain(
14895
15325
  // @ts-ignore
14896
15326
  { public_rpc_url: params.orderlyChainRpcUrl },
14897
15327
  params.orderlyContract,
@@ -14916,8 +15346,8 @@ var useGetClaimed = (id) => {
14916
15346
 
14917
15347
  // src/trading-rewards/useWalletRewardsHistory.ts
14918
15348
  var useWalletRewardsHistory = (type) => {
14919
- const { account: account7 } = useAccount();
14920
- const address = account7.address;
15349
+ const { account: account9 } = useAccount();
15350
+ const address = account9.address;
14921
15351
  const path2 = type === "normal" /* normal */ ? `/v1/public/trading_rewards/wallet_rewards_history?address=${address}` : `/v1/public/market_making_rewards/group_rewards_history?address=${address}`;
14922
15352
  const {
14923
15353
  data,
@@ -14965,7 +15395,7 @@ function useTradingRewardsStatus(isMMRewards) {
14965
15395
  };
14966
15396
  }
14967
15397
  var useApiKeyManager = (queryParams) => {
14968
- const { account: account7, state, isSubAccount } = useAccount();
15398
+ const { account: account9, state, isSubAccount } = useAccount();
14969
15399
  const { keyInfo } = queryParams || {};
14970
15400
  const keyInfoPrams = getQueryParamsFromObject(keyInfo);
14971
15401
  const { data, mutate: mutate5, error, isLoading } = usePrivateQuery(
@@ -15002,13 +15432,13 @@ var useApiKeyManager = (queryParams) => {
15002
15432
  }, []);
15003
15433
  const generateOrderlyKey = (scope) => {
15004
15434
  if (isSubAccount) {
15005
- return account7?.createSubAccountApiKey(365, {
15435
+ return account9?.createSubAccountApiKey(365, {
15006
15436
  tag: "manualCreated",
15007
15437
  scope,
15008
15438
  subAccountId: state.accountId
15009
15439
  });
15010
15440
  }
15011
- return account7?.createApiKey(365, {
15441
+ return account9?.createApiKey(365, {
15012
15442
  tag: "manualCreated",
15013
15443
  scope
15014
15444
  });
@@ -16102,7 +16532,9 @@ exports.useChains = useChains;
16102
16532
  exports.useCheckReferralCode = useCheckReferralCode;
16103
16533
  exports.useCollateral = useCollateral;
16104
16534
  exports.useCommission = useCommission;
16535
+ exports.useComputedLTV = useComputedLTV;
16105
16536
  exports.useConfig = useConfig;
16537
+ exports.useConvert = useConvert;
16106
16538
  exports.useCurEpochEstimate = useCurEpochEstimate;
16107
16539
  exports.useDaily = useDaily;
16108
16540
  exports.useDeposit = useDeposit;
@@ -16140,6 +16572,7 @@ exports.useMaxQty = useMaxQty;
16140
16572
  exports.useMediaQuery = useMediaQuery;
16141
16573
  exports.useMutation = useMutation;
16142
16574
  exports.useNetworkInfo = useNetworkInfo;
16575
+ exports.useOdosQuote = useOdosQuote;
16143
16576
  exports.useOrderEntity = useOrderEntity;
16144
16577
  exports.useOrderEntry = useOrderEntry2;
16145
16578
  exports.useOrderEntry_deprecated = useOrderEntry;
@@ -16168,6 +16601,7 @@ exports.useStatisticsDaily = useStatisticsDaily;
16168
16601
  exports.useStorageChain = useStorageChain;
16169
16602
  exports.useStorageLedgerAddress = useStorageLedgerAddress;
16170
16603
  exports.useSubAccountDataObserver = useSubAccountDataObserver;
16604
+ exports.useSubAccountMaxWithdrawal = useSubAccountMaxWithdrawal;
16171
16605
  exports.useSubAccountMutation = useSubAccountMutation;
16172
16606
  exports.useSubAccountQuery = useSubAccountQuery;
16173
16607
  exports.useSubAccountWS = useSubAccountWS;
@@ -16177,6 +16611,8 @@ exports.useSymbolsInfo = useSymbolsInfo;
16177
16611
  exports.useSymbolsInfoStore = useSymbolsInfoStore;
16178
16612
  exports.useTPSLOrder = useTPSLOrder;
16179
16613
  exports.useTickerStream = useTickerStream;
16614
+ exports.useTokenInfo = useTokenInfo;
16615
+ exports.useTokensInfo = useTokensInfo;
16180
16616
  exports.useTrack = useTrack;
16181
16617
  exports.useTrackingInstance = useTrackingInstance;
16182
16618
  exports.useTradingRewardsStatus = useTradingRewardsStatus;