@agg-build/hooks 1.2.0 → 1.2.11

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  __async,
3
- invalidateBalanceQueries,
3
+ invalidateUserMoneyState,
4
4
  useAggBalanceState,
5
5
  useAggClient,
6
6
  useAggWebSocket,
@@ -10,7 +10,7 @@ import {
10
10
  useOnWithdrawalLifecycle,
11
11
  useSyncBalances,
12
12
  useWithdrawManaged
13
- } from "./chunk-U3DRHUR5.mjs";
13
+ } from "./chunk-553OI6M2.mjs";
14
14
 
15
15
  // src/withdraw/use-withdraw-flow.ts
16
16
  import { useCallback, useEffect, useMemo, useState } from "react";
@@ -28,7 +28,9 @@ var WITHDRAWAL_SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([
28
28
  // Base
29
29
  56,
30
30
  // BNB
31
- SOLANA_CHAIN_ID
31
+ SOLANA_CHAIN_ID,
32
+ 1337
33
+ // Hyperliquid
32
34
  ]);
33
35
  var isValidDestinationAddress = (address, chainId) => {
34
36
  if (chainId === SOLANA_CHAIN_ID) return SOLANA_ADDRESS_REGEX.test(address);
@@ -265,12 +267,60 @@ function useWithdrawFlow(options) {
265
267
  };
266
268
  }
267
269
 
270
+ // src/withdraw/use-withdraw-estimate.ts
271
+ import { useMemo as useMemo2 } from "react";
272
+ function useWithdrawEstimate({
273
+ amount,
274
+ selectedToken,
275
+ selectedNetwork
276
+ }) {
277
+ return useMemo2(() => {
278
+ const numAmount = Number(amount);
279
+ if (!amount || isNaN(numAmount) || numAmount <= 0 || !selectedToken || !selectedNetwork) {
280
+ return null;
281
+ }
282
+ const network = selectedNetwork.toLowerCase();
283
+ let feeVal = 0.1;
284
+ let reserveVal = 0.2;
285
+ if (network === "1" || network === "mainnet" || network === "ethereum") {
286
+ feeVal = 1.22;
287
+ reserveVal = 0.3;
288
+ } else if (network === "137" || network === "polygon") {
289
+ feeVal = 0.05;
290
+ reserveVal = 0.15;
291
+ } else if (network === "42161" || network === "arbitrum") {
292
+ feeVal = 0.05;
293
+ reserveVal = 0.15;
294
+ } else if (network === "8453" || network === "base") {
295
+ feeVal = 0.05;
296
+ reserveVal = 0.15;
297
+ } else if (network === "56" || network === "bnb" || network === "bsc") {
298
+ feeVal = 0.1;
299
+ reserveVal = 0.2;
300
+ } else if (network === "792703809" || network === "solana") {
301
+ feeVal = 0.01;
302
+ reserveVal = 0.04;
303
+ } else if (network === "1337" || network === "hyperliquid") {
304
+ feeVal = 0.02;
305
+ reserveVal = 0.08;
306
+ }
307
+ const youReceiveVal = Math.max(0, numAmount - feeVal);
308
+ return {
309
+ estimatedFees: `~$${feeVal.toFixed(2)}`,
310
+ networkReserve: `~$${reserveVal.toFixed(2)}`,
311
+ youReceive: `~${youReceiveVal.toFixed(2)} ${selectedToken}`
312
+ };
313
+ }, [amount, selectedToken, selectedNetwork]);
314
+ }
315
+
268
316
  // src/withdraw/use-withdrawal-lifecycle.ts
269
- import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2 } from "react";
317
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo3, useRef, useState as useState2 } from "react";
270
318
  import { useQueryClient } from "@tanstack/react-query";
271
319
  var INITIAL_STATE = {
272
320
  pending: true,
273
321
  status: null,
322
+ requestedAmountRaw: null,
323
+ completedAmountRaw: null,
274
324
  terminal: false,
275
325
  lastLeg: null,
276
326
  legs: [],
@@ -301,14 +351,16 @@ var mergeLegs = (prev, snapshot, delta) => {
301
351
  return next;
302
352
  };
303
353
  var restToLifecycleState = (response) => {
304
- var _a;
354
+ var _a, _b;
305
355
  return {
306
356
  pending: false,
307
357
  status: response.status,
358
+ requestedAmountRaw: response.requested.amountRaw,
359
+ completedAmountRaw: (_a = response.completedAmountRaw) != null ? _a : null,
308
360
  terminal: response.status === "completed" || response.status === "partial" || response.status === "failed",
309
361
  lastLeg: null,
310
362
  legs: response.legs.map(restLegToWsLeg),
311
- errorMessage: (_a = response.errorMessage) != null ? _a : null,
363
+ errorMessage: (_b = response.errorMessage) != null ? _b : null,
312
364
  // No server timestamp on the REST response — we use 0 as "older than any
313
365
  // WS timestamp" so a subsequent WS event always wins. Callers that read
314
366
  // `timestamp` should treat 0/null interchangeably as "unset".
@@ -345,17 +397,19 @@ function useWithdrawalLifecycle(withdrawalId) {
345
397
  cancelled = true;
346
398
  };
347
399
  }, [client, withdrawalId, wsConnected]);
348
- const handler = useMemo2(() => {
400
+ const handler = useMemo3(() => {
349
401
  if (!withdrawalId) return null;
350
402
  return (msg) => {
351
403
  if (msg.withdrawalId !== withdrawalId) return;
352
404
  setState((prev) => {
353
- var _a, _b;
405
+ var _a, _b, _c, _d;
354
406
  return {
355
407
  pending: false,
356
408
  status: msg.status,
409
+ requestedAmountRaw: (_a = msg.requestedAmountRaw) != null ? _a : prev.requestedAmountRaw,
410
+ completedAmountRaw: (_b = msg.completedAmountRaw) != null ? _b : prev.completedAmountRaw,
357
411
  terminal: msg.terminal,
358
- lastLeg: (_a = msg.leg) != null ? _a : null,
412
+ lastLeg: (_c = msg.leg) != null ? _c : null,
359
413
  // `legs[]` is the cumulative server-known truth. Snapshots
360
414
  // (`pending` / terminal rollup) carry a full `legs[]` and replace
361
415
  // it. Intermediate per-leg deltas carry only `leg` (no `legs[]`)
@@ -363,7 +417,7 @@ function useWithdrawalLifecycle(withdrawalId) {
363
417
  // (sourceChainId, destChainId, type) so the timeline UI doesn't
364
418
  // collapse to empty between snapshots.
365
419
  legs: mergeLegs(prev.legs, msg.legs, msg.leg),
366
- errorMessage: (_b = msg.errorMessage) != null ? _b : null,
420
+ errorMessage: (_d = msg.errorMessage) != null ? _d : null,
367
421
  timestamp: msg.timestamp
368
422
  };
369
423
  });
@@ -375,7 +429,7 @@ function useWithdrawalLifecycle(withdrawalId) {
375
429
  if (!state.terminal) return;
376
430
  if (balanceRefetchedForRef.current === withdrawalId) return;
377
431
  balanceRefetchedForRef.current = withdrawalId;
378
- invalidateBalanceQueries(queryClient);
432
+ invalidateUserMoneyState(queryClient);
379
433
  client.syncManagedBalances().catch(() => {
380
434
  });
381
435
  }, [client, queryClient, state.terminal, withdrawalId]);
@@ -385,5 +439,6 @@ function useWithdrawalLifecycle(withdrawalId) {
385
439
 
386
440
  export {
387
441
  useWithdrawFlow,
442
+ useWithdrawEstimate,
388
443
  useWithdrawalLifecycle
389
444
  };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  __async,
3
3
  useAggClient
4
- } from "./chunk-U3DRHUR5.mjs";
4
+ } from "./chunk-553OI6M2.mjs";
5
5
 
6
6
  // src/use-ramp-quotes.ts
7
7
  import { useMutation } from "@tanstack/react-query";
@@ -1,5 +1,5 @@
1
1
  export { U as UseDepositAddressesOptions, u as useDepositAddresses } from './use-deposit-addresses-B9ICS-3U.mjs';
2
- export { U as UseSyncBalancesOptions, u as useSyncBalances } from './use-sync-balances-B1_8tBKw.mjs';
2
+ export { U as UseSyncBalancesOptions, u as useSyncBalances } from './use-sync-balances-CeD8qZWP.mjs';
3
3
  import '@tanstack/react-query';
4
4
  import '@agg-build/sdk';
5
5
 
@@ -121,6 +121,13 @@ interface UseDepositFlowResult {
121
121
  onWalletAmountChange: (amount: string) => void;
122
122
  onWalletMax: () => void;
123
123
  onConfirmWalletDeposit: (params: WalletDepositConfirmParams) => Promise<void>;
124
+ /**
125
+ * Clears any in-flight wallet-transaction state so the deposit modal can
126
+ * return the user to the wallet form. Called from the processing step's
127
+ * Cancel affordance when a wallet popup was dismissed silently or a
128
+ * broadcast tx was canceled/replaced without a clean error.
129
+ */
130
+ onCancelWalletDeposit: () => void;
124
131
  onWalletNetworkChange: (chainId: string) => void;
125
132
  onWalletTokenChange: (tokenSymbol: string) => void;
126
133
  initialWalletChainId: string | undefined;
@@ -130,7 +137,6 @@ interface UseDepositFlowResult {
130
137
  connectedWalletKind?: "evm" | "solana";
131
138
  sendCryptoConfig: {
132
139
  minDeposit: string;
133
- feeEstimate: string;
134
140
  eta: string;
135
141
  };
136
142
  onDoneSendCrypto: () => void;
package/dist/deposit.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { U as UseDepositAddressesOptions, u as useDepositAddresses } from './use-deposit-addresses-B9ICS-3U.js';
2
- export { U as UseSyncBalancesOptions, u as useSyncBalances } from './use-sync-balances-B1_8tBKw.js';
2
+ export { U as UseSyncBalancesOptions, u as useSyncBalances } from './use-sync-balances-CeD8qZWP.js';
3
3
  import '@tanstack/react-query';
4
4
  import '@agg-build/sdk';
5
5
 
@@ -121,6 +121,13 @@ interface UseDepositFlowResult {
121
121
  onWalletAmountChange: (amount: string) => void;
122
122
  onWalletMax: () => void;
123
123
  onConfirmWalletDeposit: (params: WalletDepositConfirmParams) => Promise<void>;
124
+ /**
125
+ * Clears any in-flight wallet-transaction state so the deposit modal can
126
+ * return the user to the wallet form. Called from the processing step's
127
+ * Cancel affordance when a wallet popup was dismissed silently or a
128
+ * broadcast tx was canceled/replaced without a clean error.
129
+ */
130
+ onCancelWalletDeposit: () => void;
124
131
  onWalletNetworkChange: (chainId: string) => void;
125
132
  onWalletTokenChange: (tokenSymbol: string) => void;
126
133
  initialWalletChainId: string | undefined;
@@ -130,7 +137,6 @@ interface UseDepositFlowResult {
130
137
  connectedWalletKind?: "evm" | "solana";
131
138
  sendCryptoConfig: {
132
139
  minDeposit: string;
133
- feeEstimate: string;
134
140
  eta: string;
135
141
  };
136
142
  onDoneSendCrypto: () => void;
package/dist/deposit.js CHANGED
@@ -91,23 +91,10 @@ function normalizeWalletError(error, supportedChains) {
91
91
  }
92
92
 
93
93
  // src/deposit/use-wallet-token-balance.ts
94
- var import_react3 = require("react");
94
+ var import_web3 = require("@solana/web3.js");
95
95
  var import_react_query = require("@tanstack/react-query");
96
96
  var import_viem = require("viem");
97
97
  var import_wagmi = require("wagmi");
98
- var import_wallet_adapter_react = require("@solana/wallet-adapter-react");
99
- var import_web3 = require("@solana/web3.js");
100
-
101
- // ../common/src/utils/auth.ts
102
- function getWalletAddressFromUserProfile(user) {
103
- var _a, _b, _c, _d, _e;
104
- const oauthWallet = (_b = (_a = user == null ? void 0 : user.accounts) == null ? void 0 : _a.find(
105
- (a) => a.type === "oauth" /* oauth */ && String(a.provider).toLowerCase() === "wallet"
106
- )) != null ? _b : null;
107
- if (oauthWallet == null ? void 0 : oauthWallet.providerAccountId) return oauthWallet.providerAccountId;
108
- const siweAccount = (_d = (_c = user == null ? void 0 : user.accounts) == null ? void 0 : _c.find((a) => a.type === "siwe" /* siwe */)) != null ? _d : null;
109
- return (_e = siweAccount == null ? void 0 : siweAccount.providerAccountId) != null ? _e : void 0;
110
- }
111
98
 
112
99
  // src/core/providers/contexts.ts
113
100
  var import_react = require("react");
@@ -276,6 +263,12 @@ var enUsLabels = {
276
263
  max: "Max",
277
264
  tokenLabel: "Receive token",
278
265
  networkLabel: "Receive network",
266
+ estimatedFees: "Est. fees",
267
+ networkReserve: "Network reserve",
268
+ networkReserveTooltipAria: "Network reserve details",
269
+ networkReserveTooltipLineOne: "This reserve helps cover network and bridge costs.",
270
+ networkReserveTooltipLineTwo: "Any unused amount stays in your balance.",
271
+ youReceive: "You'll receive",
279
272
  confirm: "Confirm withdrawal",
280
273
  successTitle: "Withdrawal submitted",
281
274
  successDescription: (tokenSymbol) => `Your ${tokenSymbol} withdrawal is being processed and will arrive shortly.`,
@@ -284,12 +277,16 @@ var enUsLabels = {
284
277
  // terminal status — otherwise a finished withdrawal would keep showing
285
278
  // "submitted / processing" forever and force the user to hard-refresh.
286
279
  successTitleCompleted: "Withdrawal complete",
287
- successDescriptionCompleted: (tokenSymbol) => `Your ${tokenSymbol} withdrawal has been delivered.`,
280
+ successDescriptionCompleted: (tokenSymbol) => `Your ${tokenSymbol} has been successfully sent to your wallet.`,
288
281
  successTitlePartial: "Withdrawal partially completed",
289
- successDescriptionPartial: (tokenSymbol) => `Some legs of your ${tokenSymbol} withdrawal completed; see details below.`,
282
+ successDescriptionPartial: () => "Part of your withdrawal was completed successfully, but the remaining funds failed to transfer and were returned to your balance.",
290
283
  successTitleFailed: "Withdrawal failed",
291
- successDescriptionFailed: (tokenSymbol) => `Your ${tokenSymbol} withdrawal could not be completed.`,
284
+ successDescriptionFailed: () => "We couldn't complete your withdrawal. Your funds were returned to your balance.",
285
+ retry: "Try Again",
286
+ close: "Close",
287
+ loadingDescription: "This may take a few minutes. You can safely close this window and check the status later in your activity.",
292
288
  summary: {
289
+ requestedWithdrawal: "Requested withdrawal",
293
290
  // The response is `pricingStatus: "unquoted"` — we don't know net
294
291
  // output until on-chain settlement. Calling this "Amount received"
295
292
  // would imply receipt before the lifecycle has confirmed. Keep it
@@ -307,6 +304,12 @@ var enUsLabels = {
307
304
  completed: "Withdrawal complete.",
308
305
  partial: "Withdrawal partially completed \u2014 see details below.",
309
306
  failed: "Withdrawal failed.",
307
+ loadingSteps: {
308
+ preparing: "Preparing funds",
309
+ bridging: "Bridging between networks",
310
+ sending: "Sending to your wallet",
311
+ confirming: "Waiting for network confirmation"
312
+ },
310
313
  steps: {
311
314
  bridge: (sourceChainName, destChainName) => `Bridging from ${sourceChainName} to ${destChainName}`,
312
315
  transfer: (destChainName) => `Transferring on ${destChainName}`
@@ -362,10 +365,37 @@ var enUsLabels = {
362
365
  externalWallet: "Deposit from external wallet",
363
366
  card: "Deposit with card"
364
367
  },
368
+ depositStatusTitles: {
369
+ connectedWallet: {
370
+ pending: "Processing deposit from connected wallet",
371
+ completed: "Successful deposit from connected wallet",
372
+ failed: "Failed deposit from connected wallet",
373
+ canceled: "Canceled deposit from connected wallet"
374
+ },
375
+ externalWallet: {
376
+ pending: "Processing deposit from external wallet",
377
+ completed: "Successful deposit from external wallet",
378
+ failed: "Failed deposit from external wallet",
379
+ canceled: "Canceled deposit from external wallet"
380
+ },
381
+ card: {
382
+ pending: "Processing deposit with card",
383
+ completed: "Successful deposit with card",
384
+ failed: "Failed deposit with card",
385
+ canceled: "Canceled deposit with card"
386
+ }
387
+ },
388
+ withdrawalStatusTitles: {
389
+ pending: "Processing withdrawal",
390
+ completed: "Successful withdrawal",
391
+ failed: "Failed withdrawal",
392
+ canceled: "Canceled withdrawal"
393
+ },
365
394
  // Activity-row title for any withdrawal regardless of lifecycle
366
- // state (pending / completed / failed) — render the asset rather
367
- // than implying success. The ActivityRow renders a separate status
368
- // chip when the row is failed.
395
+ // state — render the asset rather than implying success. The
396
+ // ActivityRow renders a separate status chip when the row is
397
+ // failed. Retained for partner overrides that still want a
398
+ // status-agnostic title.
369
399
  withdrawalTitle: (tokenSymbol) => `Withdraw ${tokenSymbol}`
370
400
  },
371
401
  positions: {
@@ -586,6 +616,7 @@ var enUsLabels = {
586
616
  noMarketSelected: "Select a market to place an order.",
587
617
  noOrderbooks: "No live orderbooks are available for this market right now.",
588
618
  quoteUnavailable: "Quote temporarily unavailable. Please try again.",
619
+ quoteBalanceMismatch: "Quote balance mismatch. Try a different amount.",
589
620
  selectedVenueUnavailable: "The venue you selected is no longer available on this route. Review the updated options and try again.",
590
621
  engineUnavailable: "The routing engine is temporarily unavailable. Please try again in a moment.",
591
622
  insufficientInputAmount: "Trade amount is too small to cover bridging and execution costs. Increase your spend or deposit funds on the destination chain.",
@@ -623,6 +654,7 @@ var enUsLabels = {
623
654
  buyingOutcome: (label) => `Buying ${label}`,
624
655
  sellingOutcome: (label) => `Selling ${label}`,
625
656
  findingBestRoute: "Finding the best route...",
657
+ checkingBalance: "Checking balance",
626
658
  submittingOrderProgress: "Submitting order...",
627
659
  orderSubmittedProgress: (orderId) => `Order #${orderId.replace(/^#/, "")} submitted`,
628
660
  executingOnVenue: (venueLabel) => `Executing on ${venueLabel}...`,
@@ -861,6 +893,7 @@ var defaultAggUiSearchConfig = {
861
893
  var defaultAggUiConfig = {
862
894
  enableLogs: false,
863
895
  enableWebsocketsLogs: false,
896
+ enableDebug: false,
864
897
  general: {
865
898
  locale: DEFAULT_LOCALE,
866
899
  theme: "light",
@@ -935,6 +968,33 @@ var invalidateBalanceQueries = (queryClient, options) => {
935
968
  refetchType
936
969
  });
937
970
  };
971
+ var invalidatePositionQueries = (queryClient, options) => {
972
+ var _a;
973
+ queryClient.invalidateQueries({
974
+ queryKey: executionKeys.positionsPrefix(),
975
+ refetchType: (_a = options == null ? void 0 : options.refetchType) != null ? _a : "active"
976
+ });
977
+ };
978
+ var userActivityQueryKeys = {
979
+ all: () => ["user-activity"]
980
+ };
981
+ var invalidateUserActivityQueries = (queryClient, options) => {
982
+ var _a;
983
+ const strategy = (_a = options == null ? void 0 : options.strategy) != null ? _a : "remove";
984
+ if (strategy === "remove") {
985
+ queryClient.removeQueries({ queryKey: userActivityQueryKeys.all() });
986
+ return;
987
+ }
988
+ queryClient.invalidateQueries({
989
+ queryKey: userActivityQueryKeys.all(),
990
+ refetchType: "all"
991
+ });
992
+ };
993
+ var invalidateUserMoneyState = (queryClient, options) => {
994
+ invalidateBalanceQueries(queryClient, { refetchType: options == null ? void 0 : options.refetchType });
995
+ invalidatePositionQueries(queryClient, { refetchType: options == null ? void 0 : options.refetchType });
996
+ invalidateUserActivityQueries(queryClient, { strategy: options == null ? void 0 : options.activityStrategy });
997
+ };
938
998
 
939
999
  // src/core/providers/hooks.ts
940
1000
  var import_react2 = require("react");
@@ -968,6 +1028,35 @@ var useAggBalanceState = useAggBalanceContext;
968
1028
  // src/deposit/constants.ts
969
1029
  var DEFAULT_SOLANA_RPC_ENDPOINT = "https://solana-rpc.publicnode.com";
970
1030
  var SVM_CHAIN_IDS = /* @__PURE__ */ new Set([792703809]);
1031
+ var MULTI_CHAIN_SOLANA_WALLET_NAMES = /* @__PURE__ */ new Set(["Phantom"]);
1032
+
1033
+ // src/deposit/use-svm-address.ts
1034
+ var import_react3 = require("react");
1035
+ var import_wallet_adapter_react = require("@solana/wallet-adapter-react");
1036
+ function getPhantomProvider() {
1037
+ var _a, _b;
1038
+ if (typeof window === "undefined") return void 0;
1039
+ const w = window;
1040
+ return (_b = (_a = w.phantom) == null ? void 0 : _a.solana) != null ? _b : w.solana;
1041
+ }
1042
+ function useSvmAddress() {
1043
+ var _a;
1044
+ const { publicKey: adapterPublicKey } = (0, import_wallet_adapter_react.useWallet)();
1045
+ const [phantomAddress, setPhantomAddress] = (0, import_react3.useState)(void 0);
1046
+ (0, import_react3.useEffect)(() => {
1047
+ var _a2;
1048
+ const provider = getPhantomProvider();
1049
+ if (!provider) return;
1050
+ const existing = (_a2 = provider.publicKey) == null ? void 0 : _a2.toBase58();
1051
+ if (existing) {
1052
+ setPhantomAddress(existing);
1053
+ return;
1054
+ }
1055
+ provider.connect({ onlyIfTrusted: true }).then((res) => setPhantomAddress(res.publicKey.toString())).catch(() => {
1056
+ });
1057
+ }, []);
1058
+ return (_a = adapterPublicKey == null ? void 0 : adapterPublicKey.toBase58()) != null ? _a : phantomAddress;
1059
+ }
971
1060
 
972
1061
  // src/deposit/use-wallet-token-balance.ts
973
1062
  var ERC20_BALANCE_OF_ABI = [
@@ -979,11 +1068,46 @@ var ERC20_BALANCE_OF_ABI = [
979
1068
  outputs: [{ name: "", type: "uint256" }]
980
1069
  }
981
1070
  ];
982
- function getPhantomProvider() {
983
- var _a, _b;
984
- if (typeof window === "undefined") return void 0;
985
- const w = window;
986
- return (_b = (_a = w.phantom) == null ? void 0 : _a.solana) != null ? _b : w.solana;
1071
+ var SVM_BALANCE_RPC_TIMEOUT_MS = 2e3;
1072
+ var SVM_BALANCE_STALE_TIME_MS = 3e4;
1073
+ var SvmBalanceTimeoutError = class extends Error {
1074
+ constructor() {
1075
+ super("Solana balance request timed out");
1076
+ this.name = "SvmBalanceTimeoutError";
1077
+ }
1078
+ };
1079
+ function withTimeout(promise, timeoutMs) {
1080
+ return new Promise((resolve, reject) => {
1081
+ const timer = setTimeout(() => reject(new SvmBalanceTimeoutError()), timeoutMs);
1082
+ promise.then(
1083
+ (value) => {
1084
+ clearTimeout(timer);
1085
+ resolve(value);
1086
+ },
1087
+ (err) => {
1088
+ clearTimeout(timer);
1089
+ reject(err);
1090
+ }
1091
+ );
1092
+ });
1093
+ }
1094
+ function fetchSvmTokenBalance(rpcUrl, owner, mint) {
1095
+ return __async(this, null, function* () {
1096
+ var _a;
1097
+ const connection = new import_web3.Connection(rpcUrl);
1098
+ const accounts = yield withTimeout(
1099
+ connection.getTokenAccountsByOwner(owner, { mint }),
1100
+ SVM_BALANCE_RPC_TIMEOUT_MS
1101
+ );
1102
+ if (accounts.value.length === 0) return 0;
1103
+ const first = accounts.value[0];
1104
+ if (!first) return 0;
1105
+ const balance = yield withTimeout(
1106
+ connection.getTokenAccountBalance(first.pubkey),
1107
+ SVM_BALANCE_RPC_TIMEOUT_MS
1108
+ );
1109
+ return (_a = balance.value.uiAmount) != null ? _a : 0;
1110
+ });
987
1111
  }
988
1112
  function useWalletTokenBalance({
989
1113
  isOpen = true,
@@ -992,7 +1116,7 @@ function useWalletTokenBalance({
992
1116
  decimals,
993
1117
  svmAddress
994
1118
  }) {
995
- var _a, _b, _c;
1119
+ var _a;
996
1120
  const { solanaRpcUrl } = useAggUiConfig();
997
1121
  const rpcEndpoint = solanaRpcUrl != null ? solanaRpcUrl : DEFAULT_SOLANA_RPC_ENDPOINT;
998
1122
  const isSvm = chainId !== void 0 && SVM_CHAIN_IDS.has(chainId);
@@ -1006,45 +1130,27 @@ function useWalletTokenBalance({
1006
1130
  args: evmAddress ? [evmAddress] : void 0,
1007
1131
  query: { enabled: evmEnabled, staleTime: 0, refetchOnMount: true }
1008
1132
  });
1009
- const { publicKey: adapterPublicKey } = (0, import_wallet_adapter_react.useWallet)();
1010
- const [phantomAddress, setPhantomAddress] = (0, import_react3.useState)(void 0);
1011
- (0, import_react3.useEffect)(() => {
1012
- var _a2;
1013
- if (!isSvm) return;
1014
- const provider = getPhantomProvider();
1015
- if (!provider) return;
1016
- const existing = (_a2 = provider.publicKey) == null ? void 0 : _a2.toBase58();
1017
- if (existing) {
1018
- setPhantomAddress(existing);
1019
- return;
1020
- }
1021
- provider.connect({ onlyIfTrusted: true }).then((res) => setPhantomAddress(res.publicKey.toString())).catch(() => {
1022
- });
1023
- }, [isSvm]);
1024
- const resolvedSvmAddress = (_b = (_a = adapterPublicKey == null ? void 0 : adapterPublicKey.toBase58()) != null ? _a : phantomAddress) != null ? _b : svmAddress;
1025
- const connection = (0, import_react3.useMemo)(() => new import_web3.Connection(rpcEndpoint), [rpcEndpoint]);
1133
+ const detectedSvmAddress = useSvmAddress();
1134
+ const resolvedSvmAddress = detectedSvmAddress != null ? detectedSvmAddress : svmAddress;
1026
1135
  const svmEnabled = isOpen && isSvm && !!resolvedSvmAddress && !!tokenAddress;
1027
1136
  const svmQuery = (0, import_react_query.useQuery)({
1028
1137
  queryKey: ["svm-token-balance", resolvedSvmAddress != null ? resolvedSvmAddress : null, tokenAddress != null ? tokenAddress : null, isOpen],
1029
1138
  enabled: svmEnabled,
1030
- staleTime: 0,
1139
+ staleTime: SVM_BALANCE_STALE_TIME_MS,
1140
+ retry: false,
1141
+ refetchOnWindowFocus: "always",
1142
+ refetchOnReconnect: "always",
1031
1143
  queryFn: () => __async(null, null, function* () {
1032
- var _a2;
1033
1144
  if (!resolvedSvmAddress || !tokenAddress) return 0;
1034
1145
  const owner = new import_web3.PublicKey(resolvedSvmAddress);
1035
1146
  const mint = new import_web3.PublicKey(tokenAddress);
1036
- const accounts = yield connection.getTokenAccountsByOwner(owner, { mint });
1037
- if (accounts.value.length === 0) return 0;
1038
- const first = accounts.value[0];
1039
- if (!first) return 0;
1040
- const balance = yield connection.getTokenAccountBalance(first.pubkey);
1041
- return (_a2 = balance.value.uiAmount) != null ? _a2 : 0;
1147
+ return yield fetchSvmTokenBalance(rpcEndpoint, owner, mint);
1042
1148
  })
1043
1149
  });
1044
1150
  if (isSvm) {
1045
1151
  const awaitingSelection2 = isOpen && !!chainId && !tokenAddress;
1046
1152
  return {
1047
- balance: (_c = svmQuery.data) != null ? _c : 0,
1153
+ balance: (_a = svmQuery.data) != null ? _a : 0,
1048
1154
  isLoading: awaitingSelection2 || svmQuery.isLoading || svmQuery.isFetching
1049
1155
  };
1050
1156
  }
@@ -1372,7 +1478,7 @@ function useSyncBalances(options) {
1372
1478
  mutationFn: () => client.syncManagedBalances(),
1373
1479
  onSuccess: () => {
1374
1480
  var _a;
1375
- invalidateBalanceQueries(queryClient);
1481
+ invalidateUserMoneyState(queryClient);
1376
1482
  (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options);
1377
1483
  },
1378
1484
  onError: options == null ? void 0 : options.onError
@@ -1402,8 +1508,10 @@ function useRampSession() {
1402
1508
  }
1403
1509
 
1404
1510
  // src/deposit/use-deposit-flow.ts
1511
+ var DEFAULT_WALLET_CHAIN_ID = 1;
1512
+ var DEFAULT_WALLET_TOKEN_SYMBOL = "USDC";
1405
1513
  function useDepositFlow(options) {
1406
- var _a, _b;
1514
+ var _a, _b, _c;
1407
1515
  const { open, onOpenChange } = options;
1408
1516
  const { user } = useAggAuthState();
1409
1517
  const { walletActions } = useAggUiConfig();
@@ -1447,8 +1555,16 @@ function useDepositFlow(options) {
1447
1555
  }, []);
1448
1556
  const { chainId: connectedChainId, address: connectedAddress } = (0, import_wagmi4.useAccount)();
1449
1557
  const { switchChainAsync } = (0, import_wagmi4.useSwitchChain)();
1450
- const { publicKey: solanaPublicKey } = (0, import_wallet_adapter_react3.useWallet)();
1451
- const balanceChainId = walletModalChainId ? Number(walletModalChainId) : connectedChainId;
1558
+ const { wallet: solanaWallet } = (0, import_wallet_adapter_react3.useWallet)();
1559
+ const resolvedSvmAddress = useSvmAddress();
1560
+ const solanaAdapterName = (_b = solanaWallet == null ? void 0 : solanaWallet.adapter) == null ? void 0 : _b.name;
1561
+ const isMultiChainSolanaWallet = Boolean(
1562
+ solanaAdapterName && MULTI_CHAIN_SOLANA_WALLET_NAMES.has(solanaAdapterName)
1563
+ );
1564
+ const hasSolanaCapability = Boolean(resolvedSvmAddress || (solanaWallet == null ? void 0 : solanaWallet.adapter));
1565
+ const hasEvmCapability = Boolean(connectedAddress) || isMultiChainSolanaWallet;
1566
+ const defaultBalanceChainId = hasEvmCapability && (supportedChains == null ? void 0 : supportedChains.some((chain) => chain.chainId === DEFAULT_WALLET_CHAIN_ID)) ? DEFAULT_WALLET_CHAIN_ID : connectedChainId;
1567
+ const balanceChainId = walletModalChainId ? Number(walletModalChainId) : defaultBalanceChainId;
1452
1568
  const selectedChainTokens = (0, import_react7.useMemo)(() => {
1453
1569
  var _a2;
1454
1570
  if (!supportedChains || !balanceChainId) return [];
@@ -1456,23 +1572,17 @@ function useDepositFlow(options) {
1456
1572
  return (_a2 = chain == null ? void 0 : chain.tokens) != null ? _a2 : [];
1457
1573
  }, [supportedChains, balanceChainId]);
1458
1574
  const selectedTokenMeta = (0, import_react7.useMemo)(() => {
1459
- if (!walletModalTokenSymbol) return void 0;
1460
- const match = selectedChainTokens.find((t) => t.symbol === walletModalTokenSymbol);
1575
+ const preferredTokenSymbol = walletModalTokenSymbol != null ? walletModalTokenSymbol : DEFAULT_WALLET_TOKEN_SYMBOL;
1576
+ const match = selectedChainTokens.find((t) => t.symbol === preferredTokenSymbol);
1461
1577
  return match ? { address: match.address, decimals: match.decimals } : void 0;
1462
1578
  }, [selectedChainTokens, walletModalTokenSymbol]);
1463
- const authSvmAddress = (0, import_react7.useMemo)(() => {
1464
- var _a2;
1465
- const wallets = user == null ? void 0 : user.wallets;
1466
- return (_a2 = wallets == null ? void 0 : wallets.find((w) => w.chain === "solana" || w.chain === "svm")) == null ? void 0 : _a2.address;
1467
- }, [user]);
1468
1579
  const isSvmBalanceChain = balanceChainId !== void 0 && SVM_CHAIN_IDS.has(balanceChainId);
1469
1580
  const walletAddress = (0, import_react7.useMemo)(() => {
1470
- var _a2, _b2, _c;
1471
1581
  if (isSvmBalanceChain) {
1472
- return (_b2 = (_a2 = solanaPublicKey == null ? void 0 : solanaPublicKey.toBase58()) != null ? _a2 : authSvmAddress) != null ? _b2 : "";
1582
+ return resolvedSvmAddress != null ? resolvedSvmAddress : "";
1473
1583
  }
1474
- return (_c = connectedAddress != null ? connectedAddress : getWalletAddressFromUserProfile(user)) != null ? _c : "";
1475
- }, [authSvmAddress, connectedAddress, isSvmBalanceChain, solanaPublicKey, user]);
1584
+ return connectedAddress != null ? connectedAddress : "";
1585
+ }, [connectedAddress, isSvmBalanceChain, resolvedSvmAddress]);
1476
1586
  const walletLabel = (0, import_react7.useMemo)(() => {
1477
1587
  return walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : "\u2014";
1478
1588
  }, [walletAddress]);
@@ -1480,12 +1590,11 @@ function useDepositFlow(options) {
1480
1590
  isOpen: open,
1481
1591
  chainId: balanceChainId,
1482
1592
  tokenAddress: selectedTokenMeta == null ? void 0 : selectedTokenMeta.address,
1483
- decimals: selectedTokenMeta == null ? void 0 : selectedTokenMeta.decimals,
1484
- svmAddress: authSvmAddress
1593
+ decimals: selectedTokenMeta == null ? void 0 : selectedTokenMeta.decimals
1485
1594
  });
1486
1595
  const { status: observedWalletTransactionStatus, gasFee: walletTransactionGasFee } = useWalletTransactionStatus({
1487
1596
  chainId: walletTransaction == null ? void 0 : walletTransaction.chainId,
1488
- txId: (_b = walletTransaction == null ? void 0 : walletTransaction.txId) != null ? _b : null
1597
+ txId: (_c = walletTransaction == null ? void 0 : walletTransaction.txId) != null ? _c : null
1489
1598
  });
1490
1599
  const walletTransactionStatus = walletTransactionError ? "error" : walletTransaction ? observedWalletTransactionStatus != null ? observedWalletTransactionStatus : "submitted" : void 0;
1491
1600
  const syncedDepositTxIdRef = (0, import_react7.useRef)(null);
@@ -1513,9 +1622,15 @@ function useDepositFlow(options) {
1513
1622
  },
1514
1623
  [onOpenChange]
1515
1624
  );
1625
+ const handleCancelWalletDeposit = (0, import_react7.useCallback)(() => {
1626
+ setWalletTransaction(null);
1627
+ setWalletTransactionError(null);
1628
+ setWalletTransactionErrorTone("error");
1629
+ syncedDepositTxIdRef.current = null;
1630
+ }, []);
1516
1631
  const handleConfirmWalletDeposit = (0, import_react7.useCallback)(
1517
1632
  (params) => __async(null, null, function* () {
1518
- var _a2, _b2, _c;
1633
+ var _a2, _b2, _c2;
1519
1634
  const { address, amount, chainId, token } = params;
1520
1635
  const chain = (_a2 = supportedChains == null ? void 0 : supportedChains.find((c) => c.chainId === chainId)) != null ? _a2 : null;
1521
1636
  const tokenMeta = (_b2 = chain == null ? void 0 : chain.tokens.find((t) => t.symbol === token)) != null ? _b2 : null;
@@ -1531,7 +1646,7 @@ function useDepositFlow(options) {
1531
1646
  token: {
1532
1647
  symbol: token,
1533
1648
  address: tokenMeta == null ? void 0 : tokenMeta.address,
1534
- decimals: (_c = tokenMeta == null ? void 0 : tokenMeta.decimals) != null ? _c : 6
1649
+ decimals: (_c2 = tokenMeta == null ? void 0 : tokenMeta.decimals) != null ? _c2 : 6
1535
1650
  },
1536
1651
  to: address,
1537
1652
  amount
@@ -1599,11 +1714,12 @@ function useDepositFlow(options) {
1599
1714
  onWalletAmountChange: setDepositAmount,
1600
1715
  onWalletMax: (0, import_react7.useCallback)(() => setDepositAmount(String(walletBalance)), [walletBalance]),
1601
1716
  onConfirmWalletDeposit: handleConfirmWalletDeposit,
1717
+ onCancelWalletDeposit: handleCancelWalletDeposit,
1602
1718
  onWalletNetworkChange: setWalletModalChainId,
1603
1719
  onWalletTokenChange: setWalletModalTokenSymbol,
1604
1720
  initialWalletChainId: connectedChainId ? String(connectedChainId) : void 0,
1605
- connectedWalletKind: connectedChainId && !solanaPublicKey ? "evm" : solanaPublicKey && !connectedChainId ? "solana" : void 0,
1606
- sendCryptoConfig: { minDeposit: "$1", feeEstimate: "~$0.01", eta: "~30s" },
1721
+ connectedWalletKind: hasEvmCapability && !hasSolanaCapability ? "evm" : hasSolanaCapability && !hasEvmCapability ? "solana" : void 0,
1722
+ sendCryptoConfig: { minDeposit: "$1", eta: "~30s" },
1607
1723
  onDoneSendCrypto: (0, import_react7.useCallback)(
1608
1724
  () => handleDepositModalOpenChange(false),
1609
1725
  [handleDepositModalOpenChange]