@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.js CHANGED
@@ -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.2-alpha.0";
64
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.5.0-alpha.1";
65
65
  }
66
- var version_default = "2.4.2-alpha.0";
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,
@@ -1187,6 +1187,24 @@ var useAppStore = zustand.create()(
1187
1187
  }))
1188
1188
  );
1189
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
+ };
1190
1208
 
1191
1209
  // src/orderly/calculator/baseCalculator.ts
1192
1210
  var BaseCalculator = class {
@@ -1254,6 +1272,7 @@ var CalculatorContext = class _CalculatorContext {
1254
1272
  this.accountInfo = useAppStore.getState().accountInfo;
1255
1273
  this.symbolsInfo = useAppStore.getState().symbolsInfo;
1256
1274
  this.fundingRates = useAppStore.getState().fundingRates;
1275
+ this.tokensInfo = useTokensInfoStore.getState().tokensInfo;
1257
1276
  }
1258
1277
  get(fn) {
1259
1278
  return fn(this.output);
@@ -1770,25 +1789,68 @@ function createGetter(data, depth = 2) {
1770
1789
  }
1771
1790
  });
1772
1791
  }
1773
-
1774
- // src/utils/parseHolding.ts
1775
- var parseHolding = (holding, markPrices) => {
1792
+ var parseHolding = (holding, indexPrices, tokensInfo) => {
1776
1793
  const nonUSDC = [];
1777
1794
  let USDC_holding = 0;
1778
1795
  holding.forEach((item) => {
1779
1796
  if (item.token === "USDC") {
1780
1797
  USDC_holding = item.holding;
1781
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
+ });
1782
1814
  nonUSDC.push({
1783
- holding: item.holding,
1784
- markPrice: markPrices[item.token] ?? 0,
1785
- // markPrice: 0,
1786
- discount: 0
1815
+ holding: holdingQty,
1816
+ indexPrice,
1817
+ collateralCap: user_max_qty,
1818
+ collateralRatio: collateralRatio4
1787
1819
  });
1788
1820
  }
1789
1821
  });
1790
1822
  return [USDC_holding, nonUSDC];
1791
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
+ };
1792
1854
 
1793
1855
  // src/orderly/calculator/portfolio.ts
1794
1856
  var PortfolioCalculatorName = "portfolio";
@@ -1798,7 +1860,8 @@ var PortfolioCalculator = class extends BaseCalculator {
1798
1860
  this.name = PortfolioCalculatorName;
1799
1861
  }
1800
1862
  calc(scope, data, ctx) {
1801
- let markPrices, positions3;
1863
+ let markPrices;
1864
+ let indexPrices;
1802
1865
  const portfolio = this.getPortfolio(ctx);
1803
1866
  if (scope === "markPrice" /* MARK_PRICE */) {
1804
1867
  markPrices = data;
@@ -1807,7 +1870,14 @@ var PortfolioCalculator = class extends BaseCalculator {
1807
1870
  (cache) => cache[MarketCalculatorName]
1808
1871
  );
1809
1872
  }
1810
- 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(
1811
1881
  (output) => output.positionCalculator_all
1812
1882
  );
1813
1883
  let holding = portfolio.holding;
@@ -1829,25 +1899,40 @@ var PortfolioCalculator = class extends BaseCalculator {
1829
1899
  }
1830
1900
  const accountInfo = ctx.accountInfo;
1831
1901
  const symbolsInfo = ctx.symbolsInfo;
1902
+ const tokensInfo = ctx.tokensInfo;
1832
1903
  return this.format({
1833
1904
  holding,
1834
1905
  positions: positions3,
1835
1906
  markPrices,
1836
1907
  accountInfo,
1837
- symbolsInfo
1908
+ symbolsInfo,
1909
+ indexPrices,
1910
+ tokensInfo: tokensInfo ?? []
1838
1911
  });
1839
1912
  }
1840
1913
  getPortfolio(ctx) {
1841
1914
  return ctx.get((output) => output[this.name]) || useAppStore.getState().portfolio;
1842
1915
  }
1843
1916
  format(inputs) {
1844
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
1845
- 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) {
1846
1927
  return null;
1847
1928
  }
1848
1929
  const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
1849
1930
  const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
1850
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1931
+ const [USDC_holding, nonUSDC] = parseHolding(
1932
+ holding,
1933
+ indexPrices,
1934
+ tokensInfo
1935
+ );
1851
1936
  const usdc = holding.find((item) => item.token === "USDC");
1852
1937
  const totalCollateral = perp.account.totalCollateral({
1853
1938
  USDCHolding: USDC_holding,
@@ -1902,36 +1987,6 @@ var PortfolioCalculator = class extends BaseCalculator {
1902
1987
  }
1903
1988
  }
1904
1989
  };
1905
- var useIndexPriceStore = zustand.create((set) => ({
1906
- indexPrices: {},
1907
- actions: {
1908
- updateIndexPrice: (indexPrice) => {
1909
- set({
1910
- indexPrices: indexPrice
1911
- });
1912
- }
1913
- }
1914
- }));
1915
-
1916
- // src/orderly/calculator/indexPrice.ts
1917
- var IndexPriceCalculatorName = "indexPriceCalculator";
1918
- var IndexPriceCalculator = class extends BaseCalculator {
1919
- constructor() {
1920
- super(...arguments);
1921
- this.name = IndexPriceCalculatorName;
1922
- }
1923
- calc(scope, data, ctx) {
1924
- return data;
1925
- }
1926
- update(data) {
1927
- if (!data)
1928
- return;
1929
- useIndexPriceStore.getState().actions.updateIndexPrice(data);
1930
- }
1931
- static getValue() {
1932
- return useIndexPriceStore.getState().indexPrices;
1933
- }
1934
- };
1935
1990
 
1936
1991
  // src/useCalculatorService.ts
1937
1992
  var useCalculatorService = () => {
@@ -3272,6 +3327,68 @@ var useLeverage = () => {
3272
3327
  maxLeverage: memoizedMaxLeverage
3273
3328
  };
3274
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
+ };
3275
3392
  var useFundingRate = (symbol) => {
3276
3393
  if (!symbol) {
3277
3394
  throw new types.SDKError("Symbol is required");
@@ -4028,7 +4145,8 @@ function useChains(networkId, options = {}) {
4028
4145
  const {
4029
4146
  filteredChains: allowedChains,
4030
4147
  configStore,
4031
- customChains
4148
+ customChains,
4149
+ chainTransformer
4032
4150
  } = React.useContext(OrderlyContext);
4033
4151
  const filterFun = React.useRef(options?.filter);
4034
4152
  filterFun.current = options?.filter;
@@ -4039,7 +4157,7 @@ function useChains(networkId, options = {}) {
4039
4157
  revalidateOnReconnect: false,
4040
4158
  // If false, undefined data gets cached against the key.
4041
4159
  revalidateOnMount: true,
4042
- // dont duplicate a request w/ same key for 1hr
4160
+ // don't duplicate a request with the same key for 1hr
4043
4161
  dedupingInterval: 36e5,
4044
4162
  ...swrOptions
4045
4163
  };
@@ -4055,13 +4173,15 @@ function useChains(networkId, options = {}) {
4055
4173
  }
4056
4174
  );
4057
4175
  const brokerId = configStore.get("brokerId");
4176
+ const env = configStore.get("env");
4177
+ const brokerIdQuery = brokerId !== "orderly" ? `?broker_id=${brokerId}` : "";
4058
4178
  const needFetchFromAPI = options.forceAPI || !customChains;
4059
4179
  const { data: chainInfos, error: chainInfoErr } = useQuery(
4060
- 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,
4061
4181
  { ...commonSwrOpts }
4062
4182
  );
4063
4183
  const { data: testChainInfos, error: testChainInfoError } = useQuery(
4064
- 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,
4065
4185
  {
4066
4186
  ...commonSwrOpts,
4067
4187
  fallbackData: testnetChainFallback,
@@ -4069,35 +4189,34 @@ function useChains(networkId, options = {}) {
4069
4189
  }
4070
4190
  }
4071
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();
4072
4197
  const chains = React.useMemo(() => {
4073
- const tokenChains = fillChainsInfo(
4074
- tokenChainsRes,
4075
- filterFun.current,
4076
- chainInfos
4077
- );
4078
- const testTokenChains = fillChainsInfo(
4079
- testTokenChainsRes,
4080
- void 0,
4081
- testChainInfos
4082
- );
4083
- let testnetArr = needFetchFromAPI ? filterAndUpdateChains(testTokenChains, testChainInfos, void 0, true) : customChains?.testnet;
4084
- tokenChains?.forEach((item) => {
4085
- const chainId = item.network_infos?.chain_id;
4086
- 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
4087
4205
  });
4088
- 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) => {
4089
4216
  chainsMap.current.set(chain.network_infos?.chain_id, chain);
4090
4217
  });
4091
- let mainnetArr = [];
4092
- mainnetArr = filterAndUpdateChains(
4093
- tokenChains,
4094
- chainInfos,
4095
- filterFun.current
4096
- );
4097
- mainnetArr = needFetchFromAPI ? mainnetArr : customChains?.mainnet;
4098
- mainnetArr.forEach((item) => {
4099
- const chainId = item.network_infos?.chain_id;
4100
- chainsMap.current.set(chainId, item);
4218
+ mainnetArr?.forEach((chain) => {
4219
+ chainsMap.current.set(chain.network_infos?.chain_id, chain);
4101
4220
  });
4102
4221
  mainnetArr = filterByAllowedChains(mainnetArr, allowedChains?.mainnet);
4103
4222
  testnetArr = filterByAllowedChains(
@@ -4126,7 +4245,10 @@ function useChains(networkId, options = {}) {
4126
4245
  testTokenChainsRes,
4127
4246
  customChains,
4128
4247
  pickField,
4129
- allowedChains
4248
+ allowedChains,
4249
+ swapChains,
4250
+ chainTransformer,
4251
+ envChainInfos
4130
4252
  ]);
4131
4253
  const findByChainId = React.useCallback(
4132
4254
  (chainId, field) => {
@@ -4157,7 +4279,7 @@ function useChains(networkId, options = {}) {
4157
4279
  {
4158
4280
  findByChainId,
4159
4281
  checkChainSupport,
4160
- error: tokenError
4282
+ error: tokenError || swapChainsError
4161
4283
  }
4162
4284
  ];
4163
4285
  }
@@ -4169,80 +4291,173 @@ function _checkChainSupport(chainId, chains) {
4169
4291
  return chain.network_infos.chain_id === chainId;
4170
4292
  });
4171
4293
  }
4172
- function fillChainsInfo(chains, filter, chainInfos) {
4173
- const _chains = [];
4174
- chains?.forEach((item) => {
4175
- item.chain_details.forEach((chain) => {
4176
- const chainId = Number(chain.chain_id);
4177
- const chainInfo = chainInfos?.find(
4178
- (item2) => item2.chain_id == chainId
4179
- );
4180
- const _chain = {
4181
- network_infos: {
4182
- name: chain.chain_name ?? chainInfo?.name ?? "--",
4183
- chain_id: chainId,
4184
- withdrawal_fee: chain.withdrawal_fee,
4185
- cross_chain_withdrawal_fee: chain.cross_chain_withdrawal_fee,
4186
- bridgeless: true
4187
- },
4188
- token_infos: [
4189
- {
4190
- symbol: item.token,
4191
- address: chain.contract_address,
4192
- decimals: chain.decimals,
4193
- display_name: chain.display_name
4194
- }
4195
- ]
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
4196
4334
  };
4197
- if (typeof filter === "function") {
4198
- if (!filter(_chain))
4199
- 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;
4200
4342
  }
4201
- _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
+ };
4202
4354
  });
4203
- });
4204
- return _chains;
4355
+ }, [enableSwapDeposit, swapChainsRes]);
4356
+ return { swapChains, swapChainsError };
4205
4357
  }
4206
- function filterAndUpdateChains(chains, chainInfos, filter, isTestNet) {
4207
- const chainsMap = /* @__PURE__ */ new Map();
4208
- chains.forEach((chain) => {
4209
- const _chain = { ...chain };
4210
- const networkInfo = chainInfos?.find(
4211
- (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
4212
4371
  );
4213
- if (networkInfo) {
4214
- const { name, public_rpc_url, currency_symbol, explorer_base_url } = networkInfo;
4215
- _chain.network_infos = {
4216
- ..._chain.network_infos,
4217
- name,
4218
- shortName: name,
4219
- public_rpc_url,
4220
- currency_symbol,
4221
- bridge_enable: true,
4222
- mainnet: !isTestNet,
4223
- explorer_base_url
4224
- // 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
4225
4424
  };
4226
- }
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
+ };
4227
4433
  if (typeof filter === "function") {
4228
4434
  if (!filter(_chain))
4229
- return;
4230
- }
4231
- if (networkInfo) {
4232
- chainsMap.set(chain.network_infos.chain_id, _chain);
4435
+ continue;
4233
4436
  }
4234
- });
4235
- 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;
4236
4449
  }
4237
- function filterByAllowedChains(chains, allowedChains) {
4238
- if (!allowedChains) {
4239
- return chains;
4450
+ function formatTestnetChainInfos(chainInfos, envChainInfos) {
4451
+ if (!chainInfos || !envChainInfos || !Array.isArray(chainInfos) || !Array.isArray(envChainInfos)) {
4452
+ return chainInfos;
4240
4453
  }
4241
- return chains.filter(
4242
- (chain) => allowedChains.some(
4243
- (allowedChain) => allowedChain.id === parseInt(chain?.network_infos?.chain_id)
4244
- )
4245
- );
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
+ });
4246
4461
  }
4247
4462
  function useStorageChain() {
4248
4463
  const [chain, setChain] = useLocalStorage(types.ChainKey, null);
@@ -4264,9 +4479,10 @@ function useStorageChain() {
4264
4479
  var useChain = (token) => {
4265
4480
  const { data, isLoading } = useQuery("/v1/public/token");
4266
4481
  const chains = React.useMemo(() => {
4267
- if (!data)
4482
+ if (!data) {
4268
4483
  return null;
4269
- let item = data.find((chain) => chain.token === token);
4484
+ }
4485
+ const item = data.find((chain) => chain.token === token);
4270
4486
  if (item) {
4271
4487
  item.chain_details = item.chain_details.map((d) => {
4272
4488
  const chain = types.chainsInfoMap.get(Number(d.chain_id));
@@ -4333,19 +4549,72 @@ var useHoldingStream = () => {
4333
4549
  };
4334
4550
  };
4335
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
+
4336
4608
  // src/orderly/useWithdraw.ts
4337
4609
  var useWithdraw = (options) => {
4338
- const { account: account7, state } = useAccount();
4610
+ const { srcChainId, token, decimals } = options;
4611
+ const { account: account9, state } = useAccount();
4339
4612
  const [isLoading, setIsLoading] = React.useState(false);
4340
4613
  const { unsettledPnL, availableBalance, freeCollateral } = useCollateral();
4341
4614
  const networkId = useConfig("networkId");
4342
4615
  const [_, { findByChainId }] = useChains(void 0);
4343
- useEventEmitter();
4344
4616
  const { track: track2 } = useTrack();
4345
- const { usdc } = useHoldingStream();
4346
- const maxAmount = React.useMemo(() => {
4347
- return freeCollateral;
4348
- }, [freeCollateral]);
4617
+ const maxAmount = useMaxWithdrawal(token);
4349
4618
  const availableWithdraw = React.useMemo(() => {
4350
4619
  if (unsettledPnL < 0) {
4351
4620
  return freeCollateral;
@@ -4357,19 +4626,19 @@ var useWithdraw = (options) => {
4357
4626
  let chain;
4358
4627
  if (networkId === "testnet") {
4359
4628
  chain = findByChainId(
4360
- utils.isTestnet(options?.srcChainId) ? options?.srcChainId : types.ARBITRUM_TESTNET_CHAINID
4629
+ utils.isTestnet(srcChainId) ? srcChainId : types.ARBITRUM_TESTNET_CHAINID
4361
4630
  );
4362
4631
  } else {
4363
- chain = findByChainId(options?.srcChainId);
4632
+ chain = findByChainId(srcChainId);
4364
4633
  if (!chain?.network_infos?.bridgeless) {
4365
4634
  chain = findByChainId(types.ARBITRUM_MAINNET_CHAINID);
4366
4635
  }
4367
4636
  }
4368
4637
  return chain;
4369
- }, [networkId, findByChainId, options?.srcChainId]);
4638
+ }, [networkId, findByChainId, srcChainId]);
4370
4639
  const dst = React.useMemo(() => {
4371
4640
  const USDC = targetChain?.token_infos.find(
4372
- (token) => token.symbol === "USDC"
4641
+ (token2) => token2.symbol === "USDC"
4373
4642
  );
4374
4643
  return {
4375
4644
  symbol: USDC?.display_name || "USDC",
@@ -4381,7 +4650,7 @@ var useWithdraw = (options) => {
4381
4650
  }, [targetChain]);
4382
4651
  const withdraw = React.useCallback(
4383
4652
  (inputs) => {
4384
- return account7.assetsManager.withdraw({ ...inputs, decimals: 6 }).then((res) => {
4653
+ return account9.assetsManager.withdraw({ ...inputs, decimals: decimals ?? 6 }).then((res) => {
4385
4654
  if (res.success) {
4386
4655
  track2(types.TrackerEventName.withdrawSuccess, {
4387
4656
  wallet: state?.connectWallet?.name,
@@ -4400,16 +4669,17 @@ var useWithdraw = (options) => {
4400
4669
  throw err;
4401
4670
  });
4402
4671
  },
4403
- [state, targetChain, state, options?.decimals]
4672
+ [state, targetChain, state, decimals]
4404
4673
  );
4405
4674
  return {
4406
4675
  dst,
4407
4676
  withdraw,
4408
4677
  isLoading,
4409
4678
  maxAmount,
4679
+ unsettledPnL,
4410
4680
  availableBalance,
4411
- availableWithdraw,
4412
- unsettledPnL
4681
+ /** @deprecated use maxAmount instead */
4682
+ availableWithdraw
4413
4683
  };
4414
4684
  };
4415
4685
  var useDeposit = (options) => {
@@ -4422,7 +4692,7 @@ var useDeposit = (options) => {
4422
4692
  const [depositFeeRevalidating, setDepositFeeRevalidating] = React.useState(false);
4423
4693
  const [balance, setBalance] = React.useState("0");
4424
4694
  const [allowance, setAllowance] = React.useState("0");
4425
- const { account: account7, state } = useAccount();
4695
+ const { account: account9, state } = useAccount();
4426
4696
  const { track: track2 } = useTrack();
4427
4697
  const prevAddress = React.useRef();
4428
4698
  const getBalanceListener = React.useRef();
@@ -4448,8 +4718,8 @@ var useDeposit = (options) => {
4448
4718
  symbol: "USDC",
4449
4719
  address: USDC?.address,
4450
4720
  decimals: USDC?.decimals,
4451
- chainId: targetChain?.network_infos?.chain_id,
4452
- network: targetChain?.network_infos?.shortName
4721
+ chainId: targetChain?.network_infos.chain_id,
4722
+ network: targetChain?.network_infos.shortName
4453
4723
  };
4454
4724
  }, [targetChain]);
4455
4725
  const isNativeToken = React.useMemo(
@@ -4459,12 +4729,12 @@ var useDeposit = (options) => {
4459
4729
  const fetchBalanceHandler = React.useCallback(
4460
4730
  async (address, decimals) => {
4461
4731
  let balance2;
4462
- if (!!address && types.isNativeTokenChecker(address)) {
4463
- balance2 = await account7.assetsManager.getNativeBalance({
4732
+ if (address && types.isNativeTokenChecker(address)) {
4733
+ balance2 = await account9.assetsManager.getNativeBalance({
4464
4734
  decimals
4465
4735
  });
4466
4736
  } else {
4467
- balance2 = await account7.assetsManager.getBalance(address, { decimals });
4737
+ balance2 = await account9.assetsManager.getBalance(address, { decimals });
4468
4738
  }
4469
4739
  return balance2;
4470
4740
  },
@@ -4490,29 +4760,30 @@ var useDeposit = (options) => {
4490
4760
  continue;
4491
4761
  }
4492
4762
  tasks.push(
4493
- account7.assetsManager.getBalanceByAddress(token.address, {
4763
+ account9.assetsManager.getBalance(token.address, {
4494
4764
  decimals: token?.decimals
4495
4765
  })
4496
4766
  );
4497
4767
  }
4498
- await Promise.all(tasks);
4768
+ const balances = await Promise.all(tasks);
4769
+ return balances;
4499
4770
  }, []);
4500
4771
  const getAllowance = async (inputs) => {
4501
- const { address, vaultAddress, decimals } = inputs;
4502
- const key = `${address}-${vaultAddress}`;
4772
+ const { address, vaultAddress: vaultAddress2, decimals } = inputs;
4773
+ const key = `${address}-${vaultAddress2}`;
4503
4774
  if (prevAddress.current === key)
4504
4775
  return;
4505
- if (!address || !vaultAddress)
4776
+ if (!address || !vaultAddress2)
4506
4777
  return;
4507
- if (address && types.isNativeTokenChecker(address))
4778
+ if (types.isNativeTokenChecker(address))
4508
4779
  return;
4509
4780
  prevAddress.current = key;
4510
- const allowance2 = await account7.assetsManager.getAllowance({
4781
+ const allowance2 = await account9.assetsManager.getAllowance({
4511
4782
  address,
4512
- vaultAddress,
4783
+ vaultAddress: vaultAddress2,
4513
4784
  decimals
4514
4785
  });
4515
- setAllowance(() => allowance2);
4786
+ setAllowance(allowance2);
4516
4787
  return allowance2;
4517
4788
  };
4518
4789
  const getAllowanceByDefaultAddress = async (inputs) => {
@@ -4522,12 +4793,31 @@ var useDeposit = (options) => {
4522
4793
  if (!address || types.isNativeTokenChecker(address))
4523
4794
  return;
4524
4795
  prevAddress.current = address;
4525
- const allowance2 = await account7.assetsManager.getAllowance({
4796
+ const allowance2 = await account9.assetsManager.getAllowance({
4526
4797
  address,
4527
- decimals
4798
+ decimals,
4799
+ vaultAddress
4528
4800
  });
4529
- setAllowance(() => allowance2);
4801
+ setAllowance(allowance2);
4802
+ return allowance2;
4530
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
+ ]);
4531
4821
  const queryBalance = useDebounce.useDebouncedCallback(
4532
4822
  (address, decimals) => {
4533
4823
  fetchBalance(address, decimals).finally(() => {
@@ -4547,89 +4837,113 @@ var useDeposit = (options) => {
4547
4837
  return;
4548
4838
  setBalanceRevalidating(true);
4549
4839
  queryBalance(options.address, options.decimals);
4550
- const params = {
4551
- address: options.address,
4552
- decimals: options.decimals
4553
- };
4554
- if (account7.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4840
+ if (account9.walletAdapter?.chainNamespace === types.ChainNamespace.solana) {
4555
4841
  setAllowance(
4556
- account7.walletAdapter.formatUnits(types.MaxUint256, options.decimals)
4842
+ account9.walletAdapter.formatUnits(types.MaxUint256, options.decimals)
4557
4843
  );
4558
4844
  return;
4559
4845
  }
4560
- if (dst.chainId !== options.srcChainId) {
4561
- queryAllowance(params);
4846
+ if (vaultAddress && options.address) {
4847
+ queryAllowance({
4848
+ address: options.address,
4849
+ decimals: options.decimals,
4850
+ vaultAddress
4851
+ });
4562
4852
  } else {
4563
- if (dst.symbol !== options.srcToken) {
4564
- queryAllowance(params);
4565
- } else {
4566
- getAllowanceByDefaultAddress(params);
4567
- }
4853
+ getAllowanceByDefaultAddress({
4854
+ address: options.address,
4855
+ decimals: options.decimals
4856
+ });
4568
4857
  }
4569
4858
  }, [
4570
4859
  state.status,
4571
4860
  options.address,
4572
- options.srcChainId,
4573
- options.srcToken,
4574
4861
  options.decimals,
4575
- account7.address,
4576
- dst.chainId,
4577
- dst.symbol
4862
+ account9.address,
4863
+ vaultAddress
4578
4864
  ]);
4579
4865
  const updateAllowanceWhenTxSuccess = React.useCallback(
4580
4866
  (txHash) => {
4581
- return account7.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4867
+ return account9.walletAdapter?.pollTransactionReceiptWithBackoff(txHash).then((receipt) => {
4582
4868
  if (receipt.status === 1) {
4583
- account7.assetsManager.getAllowance({ address: options.address }).then((allowance2) => {
4584
- setAllowance(() => allowance2);
4869
+ account9.assetsManager.getAllowance({
4870
+ address: options.address,
4871
+ decimals: options.decimals,
4872
+ vaultAddress
4873
+ }).then((allowance2) => {
4874
+ setAllowance(allowance2);
4585
4875
  });
4586
4876
  }
4587
4877
  });
4588
4878
  },
4589
- [account7, options.address]
4879
+ [account9, options.address, options.decimals, vaultAddress]
4590
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
+ ]);
4591
4906
  const approve = React.useCallback(
4592
4907
  async (amount) => {
4593
4908
  if (!options.address) {
4594
- throw new types.SDKError("Address is required");
4909
+ throw new Error("address is required");
4595
4910
  }
4596
- return account7.assetsManager.approve({
4911
+ return account9.assetsManager.approve({
4597
4912
  address: options.address,
4598
4913
  amount,
4914
+ vaultAddress,
4599
4915
  decimals: options.decimals
4600
- }).then((res) => {
4601
- return updateAllowanceWhenTxSuccess(res.hash);
4602
- }).catch((e) => {
4603
- throw e;
4916
+ }).then((result) => {
4917
+ return updateAllowanceWhenTxSuccess(result.hash);
4604
4918
  });
4605
4919
  },
4606
- [account7, getAllowance, options.address, options.decimals, dst]
4920
+ [
4921
+ account9,
4922
+ options.address,
4923
+ options.decimals,
4924
+ vaultAddress,
4925
+ updateAllowanceWhenTxSuccess
4926
+ ]
4607
4927
  );
4608
4928
  const deposit = React.useCallback(async () => {
4609
- if (!options.address) {
4610
- throw new types.SDKError("Address is required");
4611
- }
4612
- const _allowance = await account7.assetsManager.getAllowance({
4613
- address: options.address,
4614
- decimals: options.decimals
4615
- });
4616
- setAllowance(() => _allowance);
4617
- if (new utils.Decimal(quantity).greaterThan(_allowance)) {
4618
- throw new types.SDKError("Insufficient allowance");
4619
- }
4620
- return account7.assetsManager.deposit({
4929
+ await enquireAllowance();
4930
+ const inputs = {
4621
4931
  amount: quantity,
4622
4932
  fee: depositFee,
4623
- decimals: options.decimals
4624
- }).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());
4625
4941
  track2(types.TrackerEventName.depositSuccess, {
4626
4942
  wallet: state?.connectWallet?.name,
4627
4943
  network: targetChain?.network_infos.name,
4628
4944
  quantity
4629
4945
  });
4630
- updateAllowanceWhenTxSuccess(res.hash);
4631
- setBalance((value) => new utils.Decimal(value).sub(quantity).toString());
4632
- return res;
4946
+ return result;
4633
4947
  }).catch((e) => {
4634
4948
  track2(types.TrackerEventName.depositFailed, {
4635
4949
  wallet: state?.connectWallet?.name,
@@ -4639,16 +4953,23 @@ var useDeposit = (options) => {
4639
4953
  throw e;
4640
4954
  });
4641
4955
  }, [
4642
- account7,
4643
- fetchBalance,
4956
+ state,
4957
+ account9,
4644
4958
  quantity,
4645
4959
  depositFee,
4646
- options.address,
4647
- options.decimals
4960
+ targetChain,
4961
+ options.decimals,
4962
+ options.srcToken,
4963
+ enquireAllowance,
4964
+ updateAllowanceWhenTxSuccess,
4965
+ isNativeToken,
4966
+ vaultAddress
4648
4967
  ]);
4649
4968
  const loopGetBalance = async () => {
4650
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
4651
- 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;
4652
4973
  getBalanceListener.current = setTimeout(async () => {
4653
4974
  try {
4654
4975
  const balance2 = await fetchBalanceHandler(
@@ -4663,13 +4984,15 @@ var useDeposit = (options) => {
4663
4984
  };
4664
4985
  const getDepositFee = React.useCallback(
4665
4986
  async (quantity2) => {
4666
- return account7.assetsManager.getDepositFee({
4987
+ return account9.assetsManager.getDepositFee({
4667
4988
  amount: quantity2,
4668
4989
  chain: targetChain?.network_infos,
4669
- decimals: options.decimals
4990
+ decimals: options.decimals,
4991
+ token: options.srcToken,
4992
+ address: options.address
4670
4993
  });
4671
4994
  },
4672
- [account7, targetChain, options.decimals]
4995
+ [account9, targetChain, options.decimals, options.srcToken, options.address]
4673
4996
  );
4674
4997
  const enquiryDepositFee = React.useCallback(() => {
4675
4998
  if (isNaN(Number(quantity)) || !quantity || Number(quantity) === 0) {
@@ -4697,7 +5020,9 @@ var useDeposit = (options) => {
4697
5020
  }
4698
5021
  loopGetBalance();
4699
5022
  return () => {
4700
- getBalanceListener.current && clearTimeout(getBalanceListener.current);
5023
+ if (getBalanceListener.current) {
5024
+ clearTimeout(getBalanceListener.current);
5025
+ }
4701
5026
  };
4702
5027
  }, [options.address, options.decimals]);
4703
5028
  return {
@@ -4716,12 +5041,26 @@ var useDeposit = (options) => {
4716
5041
  depositFeeRevalidating,
4717
5042
  approve,
4718
5043
  deposit,
4719
- fetchBalances,
4720
5044
  fetchBalance: fetchBalanceHandler,
5045
+ fetchBalances,
4721
5046
  /** set input quantity */
4722
5047
  setQuantity
4723
5048
  };
4724
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
+ };
4725
5064
  var fetcher3 = (url, options) => {
4726
5065
  const init2 = {
4727
5066
  method: options.arg.method,
@@ -4745,7 +5084,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4745
5084
  if (!url.startsWith("http")) {
4746
5085
  fullUrl = `${apiBaseUrl}${url}`;
4747
5086
  }
4748
- const account7 = useAccountInstance();
5087
+ const account9 = useAccountInstance();
4749
5088
  const { trigger, reset, data, error, isMutating } = useSWRMutation__default.default(
4750
5089
  fullUrl,
4751
5090
  // method === "POST" ? fetcher : deleteFetcher,
@@ -4765,7 +5104,7 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4765
5104
  url: newUrl,
4766
5105
  data: data2
4767
5106
  };
4768
- const signer = account7.signer;
5107
+ const signer = account9.signer;
4769
5108
  const signature = await signer.sign(payload, utils.getTimestamp());
4770
5109
  return trigger(
4771
5110
  {
@@ -4774,13 +5113,13 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4774
5113
  method,
4775
5114
  signature: {
4776
5115
  ...signature,
4777
- "orderly-account-id": accountId || _accountId || account7.accountId
5116
+ "orderly-account-id": accountId || _accountId || account9.accountId
4778
5117
  }
4779
5118
  },
4780
5119
  restOptions2
4781
5120
  );
4782
5121
  },
4783
- [trigger, account7, accountId]
5122
+ [trigger, account9, accountId]
4784
5123
  );
4785
5124
  return [
4786
5125
  mutation,
@@ -4795,8 +5134,8 @@ var useSubAccountMutation = (url, method = "POST", options) => {
4795
5134
 
4796
5135
  // src/orderly/useTransfer.ts
4797
5136
  var useTransfer = (options) => {
4798
- const { fromAccountId } = options || {};
4799
- const { unsettledPnL, availableBalance, freeCollateral, holding } = useCollateral();
5137
+ const { fromAccountId, token } = options || {};
5138
+ const { unsettledPnL, holding } = useCollateral();
4800
5139
  const [doTransfer, { isMutating: submitting }] = useSubAccountMutation(
4801
5140
  "/v1/internal_transfer",
4802
5141
  "POST",
@@ -4805,9 +5144,9 @@ var useTransfer = (options) => {
4805
5144
  }
4806
5145
  );
4807
5146
  const transfer = React.useCallback(
4808
- async (token, receivers) => {
5147
+ async (token2, receivers) => {
4809
5148
  return doTransfer({
4810
- token,
5149
+ token: token2,
4811
5150
  receiver_list: Array.isArray(receivers) ? receivers : [receivers]
4812
5151
  }).then((res) => {
4813
5152
  if (res.success) {
@@ -4820,23 +5159,12 @@ var useTransfer = (options) => {
4820
5159
  },
4821
5160
  [doTransfer]
4822
5161
  );
4823
- const maxAmount = React.useMemo(() => {
4824
- return freeCollateral;
4825
- }, [freeCollateral]);
4826
- const availableTransfer = React.useMemo(() => {
4827
- if (unsettledPnL < 0) {
4828
- return freeCollateral;
4829
- } else {
4830
- return freeCollateral - unsettledPnL;
4831
- }
4832
- }, [freeCollateral, unsettledPnL]);
5162
+ const maxAmount = useMaxWithdrawal(token);
4833
5163
  return {
4834
5164
  submitting,
4835
5165
  transfer,
4836
5166
  maxAmount,
4837
5167
  unsettledPnL,
4838
- availableBalance,
4839
- availableTransfer,
4840
5168
  holding
4841
5169
  };
4842
5170
  };
@@ -6438,7 +6766,7 @@ var OrderFactory = class {
6438
6766
  };
6439
6767
  function useSubAccountQuery(query, options) {
6440
6768
  const { formatter, accountId, ...swrOptions } = options || {};
6441
- const { state, account: account7 } = useAccount();
6769
+ const { state, account: account9 } = useAccount();
6442
6770
  const middleware = Array.isArray(options?.use) ? options?.use ?? [] : [];
6443
6771
  return useSWR__namespace.default(
6444
6772
  () => accountId && (state.status >= types.AccountStatusEnum.EnableTrading || state.status === types.AccountStatusEnum.EnableTradingWithoutConnected) ? [query, accountId] : null,
@@ -6447,13 +6775,13 @@ function useSubAccountQuery(query, options) {
6447
6775
  },
6448
6776
  {
6449
6777
  ...swrOptions,
6450
- use: [...middleware, signatureMiddleware2(account7, accountId)],
6778
+ use: [...middleware, signatureMiddleware2(account9, accountId)],
6451
6779
  onError: () => {
6452
6780
  }
6453
6781
  }
6454
6782
  );
6455
6783
  }
6456
- function signatureMiddleware2(account7, accountId) {
6784
+ function signatureMiddleware2(account9, accountId) {
6457
6785
  const apiBaseUrl = useConfig("apiBaseUrl");
6458
6786
  return (useSWRNext) => {
6459
6787
  return (key, fetcher4, config) => {
@@ -6461,7 +6789,7 @@ function signatureMiddleware2(account7, accountId) {
6461
6789
  const extendedFetcher = async (args) => {
6462
6790
  const url = Array.isArray(args) ? args[0] : args;
6463
6791
  const fullUrl = `${apiBaseUrl}${url}`;
6464
- const signer = account7.signer;
6792
+ const signer = account9.signer;
6465
6793
  const payload = {
6466
6794
  method: "GET",
6467
6795
  url
@@ -6482,13 +6810,25 @@ function signatureMiddleware2(account7, accountId) {
6482
6810
  };
6483
6811
  }
6484
6812
  function formatPortfolio(inputs) {
6485
- const { holding, positions: positions3, markPrices, accountInfo, symbolsInfo } = inputs;
6486
- 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) {
6487
6823
  return null;
6488
6824
  }
6489
6825
  const unsettledPnL = ramda.pathOr(0, ["total_unsettled_pnl"])(positions3);
6490
6826
  const unrealizedPnL = ramda.pathOr(0, ["total_unreal_pnl"])(positions3);
6491
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
6827
+ const [USDC_holding, nonUSDC] = parseHolding(
6828
+ holding,
6829
+ indexPrices,
6830
+ tokensInfo
6831
+ );
6492
6832
  const usdc = holding.find((item) => item.token === "USDC");
6493
6833
  const totalCollateral = perp.account.totalCollateral({
6494
6834
  USDCHolding: USDC_holding,
@@ -6640,7 +6980,7 @@ function calcByPrice(positions3, markPrice, indexPrice) {
6640
6980
  var useSubAccountWS = (options) => {
6641
6981
  const { accountId } = options;
6642
6982
  const { configStore } = React.useContext(OrderlyContext);
6643
- const { state, account: account7 } = useAccount();
6983
+ const { state, account: account9 } = useAccount();
6644
6984
  const websocketClient = React.useRef(
6645
6985
  new net.WS({
6646
6986
  networkId: configStore.get("networkId"),
@@ -6648,7 +6988,7 @@ var useSubAccountWS = (options) => {
6648
6988
  // publicUrl: configStore.get("publicWsUrl"),
6649
6989
  privateUrl: configStore.get("privateWsUrl"),
6650
6990
  onSigntureRequest: async () => {
6651
- const signer = account7.signer;
6991
+ const signer = account9.signer;
6652
6992
  const timestamp = utils.getTimestamp();
6653
6993
  const result = await signer.signText(timestamp.toString());
6654
6994
  return { ...result, timestamp };
@@ -6673,11 +7013,12 @@ var useSubAccountDataObserver = (accountId) => {
6673
7013
  const { data: indexPrices } = useIndexPricesStream();
6674
7014
  const symbolsInfo = useSymbolsInfo();
6675
7015
  const fundingRates = useFundingRatesStore();
7016
+ const tokensInfo = useTokensInfo();
6676
7017
  const [holding, setHolding] = React.useState([]);
6677
7018
  const [positions3, setPositions] = React.useState(
6678
7019
  POSITION_EMPTY
6679
7020
  );
6680
- const [portfolio, setportfolio] = React.useState();
7021
+ const [portfolio, setPortfolio] = React.useState();
6681
7022
  const { data: accountInfo } = useSubAccountQuery(
6682
7023
  "/v1/client/info",
6683
7024
  { accountId, revalidateOnFocus: false }
@@ -6701,11 +7042,21 @@ var useSubAccountDataObserver = (accountId) => {
6701
7042
  holding,
6702
7043
  positions: positions3,
6703
7044
  markPrices,
7045
+ indexPrices,
6704
7046
  accountInfo,
6705
- symbolsInfo
7047
+ symbolsInfo,
7048
+ tokensInfo
6706
7049
  });
6707
- setportfolio(portfolio2);
6708
- }, [holding, positions3, markPrices, accountInfo, symbolsInfo]);
7050
+ setPortfolio(portfolio2);
7051
+ }, [
7052
+ holding,
7053
+ positions3,
7054
+ markPrices,
7055
+ indexPrices,
7056
+ accountInfo,
7057
+ symbolsInfo,
7058
+ tokensInfo
7059
+ ]);
6709
7060
  React.useEffect(() => {
6710
7061
  if (!positionsInfo)
6711
7062
  return;
@@ -6814,6 +7165,63 @@ var useSubAccountDataObserver = (accountId) => {
6814
7165
  }, [accountId]);
6815
7166
  return { portfolio, positions: positions3 };
6816
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
+ }
6817
7225
  function offsetToPrice(inputs) {
6818
7226
  const { offset, entryPrice, orderType, orderSide } = inputs;
6819
7227
  if (!offset)
@@ -7613,7 +8021,7 @@ var useStorageLedgerAddress = () => {
7613
8021
  var usePrivateDataObserver = (options) => {
7614
8022
  const ws = useWS();
7615
8023
  const ee = useEventEmitter();
7616
- const { state, account: account7 } = useAccount();
8024
+ const { state, account: account9 } = useAccount();
7617
8025
  const { setAccountInfo, restoreHolding, cleanAll } = useAppStore(
7618
8026
  (state2) => state2.actions
7619
8027
  );
@@ -7646,9 +8054,9 @@ var usePrivateDataObserver = (options) => {
7646
8054
  positionsActions.clearAll();
7647
8055
  }
7648
8056
  };
7649
- account7.on(core.EVENT_NAMES.statusChanged, handler);
8057
+ account9.on(core.EVENT_NAMES.statusChanged, handler);
7650
8058
  return () => {
7651
- account7.off(core.EVENT_NAMES.statusChanged, handler);
8059
+ account9.off(core.EVENT_NAMES.statusChanged, handler);
7652
8060
  };
7653
8061
  }, []);
7654
8062
  React.useEffect(() => {
@@ -7669,7 +8077,7 @@ var usePrivateDataObserver = (options) => {
7669
8077
  }
7670
8078
  );
7671
8079
  React.useEffect(() => {
7672
- if (!account7.accountId)
8080
+ if (!account9.accountId)
7673
8081
  return;
7674
8082
  const unsubscribe = ws.privateSubscribe(
7675
8083
  {
@@ -7688,11 +8096,11 @@ var usePrivateDataObserver = (options) => {
7688
8096
  }
7689
8097
  );
7690
8098
  return () => unsubscribe?.();
7691
- }, [account7.accountId]);
8099
+ }, [account9.accountId]);
7692
8100
  const isHoldingInit = React.useRef(false);
7693
8101
  React.useEffect(() => {
7694
8102
  isHoldingInit.current = false;
7695
- }, [state.accountId]);
8103
+ }, [state.address]);
7696
8104
  React.useEffect(() => {
7697
8105
  if (!holding) {
7698
8106
  return;
@@ -7861,6 +8269,7 @@ var usePublicDataObserver = () => {
7861
8269
  (state) => state.actions
7862
8270
  );
7863
8271
  const { updateMarket } = useMarketStore((state) => state.actions);
8272
+ const setTokensInfo = useTokensInfoStore((state) => state.setTokensInfo);
7864
8273
  useQuery(`/v1/public/info`, {
7865
8274
  ...publicQueryOptions,
7866
8275
  onSuccess(data) {
@@ -7913,6 +8322,16 @@ var usePublicDataObserver = () => {
7913
8322
  updateMarket(data);
7914
8323
  }
7915
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
+ });
7916
8335
  };
7917
8336
  function getEstFundingRate(data) {
7918
8337
  if (!data)
@@ -8027,7 +8446,7 @@ var ExtendedConfigStore = class extends core.DefaultConfigStore {
8027
8446
  }
8028
8447
  };
8029
8448
  var OrderlyConfigProvider = (props) => {
8030
- const [account7, setAccount] = React__default.default.useState(null);
8449
+ const [account9, setAccount] = React__default.default.useState(null);
8031
8450
  const {
8032
8451
  configStore,
8033
8452
  keyStore,
@@ -8038,7 +8457,9 @@ var OrderlyConfigProvider = (props) => {
8038
8457
  networkId,
8039
8458
  contracts,
8040
8459
  chainFilter,
8041
- customChains
8460
+ customChains,
8461
+ enableSwapDeposit = true,
8462
+ chainTransformer
8042
8463
  } = props;
8043
8464
  if (typeof configStore !== "undefined" && !configStore.get("brokerId")) {
8044
8465
  throw new types.SDKError(
@@ -8068,9 +8489,9 @@ var OrderlyConfigProvider = (props) => {
8068
8489
  return props.orderbookDefaultTickSizes || DEFAULT_TICK_SIZES;
8069
8490
  }, [props.orderbookDefaultTickSizes]);
8070
8491
  React.useLayoutEffect(() => {
8071
- let account8 = core.SimpleDI.get(core.Account.instanceName);
8072
- if (!account8) {
8073
- account8 = new core.Account(
8492
+ let account10 = core.SimpleDI.get(core.Account.instanceName);
8493
+ if (!account10) {
8494
+ account10 = new core.Account(
8074
8495
  innerConfigStore,
8075
8496
  innerKeyStore,
8076
8497
  // innerGetWalletAdapter,
@@ -8079,9 +8500,9 @@ var OrderlyConfigProvider = (props) => {
8079
8500
  contracts
8080
8501
  }
8081
8502
  );
8082
- core.SimpleDI.registerByName(core.Account.instanceName, account8);
8503
+ core.SimpleDI.registerByName(core.Account.instanceName, account10);
8083
8504
  }
8084
- setAccount(account8);
8505
+ setAccount(account10);
8085
8506
  }, []);
8086
8507
  const filteredChains = React.useMemo(() => {
8087
8508
  if (typeof chainFilter === "function") {
@@ -8089,7 +8510,7 @@ var OrderlyConfigProvider = (props) => {
8089
8510
  }
8090
8511
  return chainFilter;
8091
8512
  }, [props.chainFilter, innerConfigStore]);
8092
- if (!account7) {
8513
+ if (!account9) {
8093
8514
  return null;
8094
8515
  }
8095
8516
  return /* @__PURE__ */ jsxRuntime.jsx(
@@ -8104,6 +8525,8 @@ var OrderlyConfigProvider = (props) => {
8104
8525
  walletAdapters: innerWalletAdapters,
8105
8526
  // apiBaseUrl,
8106
8527
  customChains,
8528
+ enableSwapDeposit,
8529
+ chainTransformer,
8107
8530
  defaultOrderbookTickSizes
8108
8531
  },
8109
8532
  children: /* @__PURE__ */ jsxRuntime.jsx(StatusProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(DataCenterProvider, { children: props.children }) })
@@ -9929,9 +10352,9 @@ var useAllBrokers = () => {
9929
10352
  };
9930
10353
  var useCurEpochEstimate = (type) => {
9931
10354
  const [data, setData] = React.useState(void 0);
9932
- const { account: account7 } = useAccount();
10355
+ const { account: account9 } = useAccount();
9933
10356
  const brokers = useAllBrokers();
9934
- const address = account7.address;
10357
+ const address = account9.address;
9935
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}`;
9936
10359
  const { data: estimateData } = useQuery(address !== void 0 ? path2 : "", {
9937
10360
  formatter: (res) => {
@@ -14891,14 +15314,14 @@ var DistributionId = /* @__PURE__ */ ((DistributionId2) => {
14891
15314
  })(DistributionId || {});
14892
15315
  var useGetClaimed = (id) => {
14893
15316
  const [data, setData] = React.useState(0);
14894
- const { account: account7 } = useAccount();
14895
- const address = account7.address;
15317
+ const { account: account9 } = useAccount();
15318
+ const address = account9.address;
14896
15319
  const env = useGetEnv();
14897
15320
  const refresh = React.useCallback(() => {
14898
15321
  const params = getContractByEnv(env);
14899
15322
  if (typeof address === "undefined")
14900
15323
  return;
14901
- account7.walletAdapter?.callOnChain(
15324
+ account9.walletAdapter?.callOnChain(
14902
15325
  // @ts-ignore
14903
15326
  { public_rpc_url: params.orderlyChainRpcUrl },
14904
15327
  params.orderlyContract,
@@ -14923,8 +15346,8 @@ var useGetClaimed = (id) => {
14923
15346
 
14924
15347
  // src/trading-rewards/useWalletRewardsHistory.ts
14925
15348
  var useWalletRewardsHistory = (type) => {
14926
- const { account: account7 } = useAccount();
14927
- const address = account7.address;
15349
+ const { account: account9 } = useAccount();
15350
+ const address = account9.address;
14928
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}`;
14929
15352
  const {
14930
15353
  data,
@@ -14972,7 +15395,7 @@ function useTradingRewardsStatus(isMMRewards) {
14972
15395
  };
14973
15396
  }
14974
15397
  var useApiKeyManager = (queryParams) => {
14975
- const { account: account7, state, isSubAccount } = useAccount();
15398
+ const { account: account9, state, isSubAccount } = useAccount();
14976
15399
  const { keyInfo } = queryParams || {};
14977
15400
  const keyInfoPrams = getQueryParamsFromObject(keyInfo);
14978
15401
  const { data, mutate: mutate5, error, isLoading } = usePrivateQuery(
@@ -15009,13 +15432,13 @@ var useApiKeyManager = (queryParams) => {
15009
15432
  }, []);
15010
15433
  const generateOrderlyKey = (scope) => {
15011
15434
  if (isSubAccount) {
15012
- return account7?.createSubAccountApiKey(365, {
15435
+ return account9?.createSubAccountApiKey(365, {
15013
15436
  tag: "manualCreated",
15014
15437
  scope,
15015
15438
  subAccountId: state.accountId
15016
15439
  });
15017
15440
  }
15018
- return account7?.createApiKey(365, {
15441
+ return account9?.createApiKey(365, {
15019
15442
  tag: "manualCreated",
15020
15443
  scope
15021
15444
  });
@@ -16109,7 +16532,9 @@ exports.useChains = useChains;
16109
16532
  exports.useCheckReferralCode = useCheckReferralCode;
16110
16533
  exports.useCollateral = useCollateral;
16111
16534
  exports.useCommission = useCommission;
16535
+ exports.useComputedLTV = useComputedLTV;
16112
16536
  exports.useConfig = useConfig;
16537
+ exports.useConvert = useConvert;
16113
16538
  exports.useCurEpochEstimate = useCurEpochEstimate;
16114
16539
  exports.useDaily = useDaily;
16115
16540
  exports.useDeposit = useDeposit;
@@ -16147,6 +16572,7 @@ exports.useMaxQty = useMaxQty;
16147
16572
  exports.useMediaQuery = useMediaQuery;
16148
16573
  exports.useMutation = useMutation;
16149
16574
  exports.useNetworkInfo = useNetworkInfo;
16575
+ exports.useOdosQuote = useOdosQuote;
16150
16576
  exports.useOrderEntity = useOrderEntity;
16151
16577
  exports.useOrderEntry = useOrderEntry2;
16152
16578
  exports.useOrderEntry_deprecated = useOrderEntry;
@@ -16175,6 +16601,7 @@ exports.useStatisticsDaily = useStatisticsDaily;
16175
16601
  exports.useStorageChain = useStorageChain;
16176
16602
  exports.useStorageLedgerAddress = useStorageLedgerAddress;
16177
16603
  exports.useSubAccountDataObserver = useSubAccountDataObserver;
16604
+ exports.useSubAccountMaxWithdrawal = useSubAccountMaxWithdrawal;
16178
16605
  exports.useSubAccountMutation = useSubAccountMutation;
16179
16606
  exports.useSubAccountQuery = useSubAccountQuery;
16180
16607
  exports.useSubAccountWS = useSubAccountWS;
@@ -16184,6 +16611,8 @@ exports.useSymbolsInfo = useSymbolsInfo;
16184
16611
  exports.useSymbolsInfoStore = useSymbolsInfoStore;
16185
16612
  exports.useTPSLOrder = useTPSLOrder;
16186
16613
  exports.useTickerStream = useTickerStream;
16614
+ exports.useTokenInfo = useTokenInfo;
16615
+ exports.useTokensInfo = useTokensInfo;
16187
16616
  exports.useTrack = useTrack;
16188
16617
  exports.useTrackingInstance = useTrackingInstance;
16189
16618
  exports.useTradingRewardsStatus = useTradingRewardsStatus;