@agg-build/hooks 4.26.1 → 4.27.0
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/deposit.d.mts +142 -138
- package/dist/deposit.d.mts.map +1 -0
- package/dist/deposit.d.ts +142 -138
- package/dist/deposit.d.ts.map +1 -0
- package/dist/deposit.js +751 -2414
- package/dist/deposit.mjs +744 -727
- package/dist/deposit.mjs.map +1 -0
- package/dist/index-CbNR3EIA.d.mts +341 -0
- package/dist/index-CbNR3EIA.d.mts.map +1 -0
- package/dist/index-CsP1jRMD.d.ts +341 -0
- package/dist/index-CsP1jRMD.d.ts.map +1 -0
- package/dist/index-D0fXU85a.d.mts +743 -0
- package/dist/index-D0fXU85a.d.mts.map +1 -0
- package/dist/index-D0fXU85a.d.ts +743 -0
- package/dist/index-D0fXU85a.d.ts.map +1 -0
- package/dist/index.d.mts +6458 -7515
- package/dist/index.d.mts.map +1 -0
- package/dist/index.d.ts +6458 -7515
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7451 -11417
- package/dist/index.mjs +7154 -5221
- package/dist/index.mjs.map +1 -0
- package/dist/use-ramp-session-7RAG9tvY.js +30 -0
- package/dist/use-ramp-session-BFWHCtuc.mjs +21 -0
- package/dist/use-ramp-session-BFWHCtuc.mjs.map +1 -0
- package/dist/use-sync-balances-BkcqInJh.mjs +1779 -0
- package/dist/use-sync-balances-BkcqInJh.mjs.map +1 -0
- package/dist/{use-sync-balances-CeD8qZWP.d.ts → use-sync-balances-CVEg__2V.d.mts} +7 -8
- package/dist/use-sync-balances-CVEg__2V.d.mts.map +1 -0
- package/dist/{use-sync-balances-CeD8qZWP.d.mts → use-sync-balances-CVEg__2V.d.ts} +7 -8
- package/dist/use-sync-balances-CVEg__2V.d.ts.map +1 -0
- package/dist/use-sync-balances-HryB8Q7F.js +1974 -0
- package/dist/withdraw--f5kYKJA.mjs +1474 -0
- package/dist/withdraw--f5kYKJA.mjs.map +1 -0
- package/dist/withdraw-BXWZYmJa.js +1591 -0
- package/dist/withdraw.d.mts +3 -351
- package/dist/withdraw.d.ts +3 -351
- package/dist/withdraw.js +10 -2229
- package/dist/withdraw.mjs +3 -20
- package/package.json +7 -6
- package/dist/chunk-JFJNW2PD.mjs +0 -5649
- package/dist/chunk-LNIAMJTZ.mjs +0 -505
- package/dist/chunk-OZQ3K47U.mjs +0 -31
- package/dist/use-deposit-addresses-B9ICS-3U.d.mts +0 -236
- package/dist/use-deposit-addresses-B9ICS-3U.d.ts +0 -236
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deposit.mjs","names":["SupportedChain","chainId","name","tokens","Array","symbol","address","decimals","normalizeWalletError","error","supportedChains","message","tone","Error","String","lower","toLowerCase","includes","chainMismatch","match","targetChainId","Number","undefined","targetChainName","find","chain","DEFAULT_SOLANA_RPC_ENDPOINTS","DEFAULT_SOLANA_RPC_ENDPOINT","SVM_CHAIN_IDS","ReadonlySet","Set","MULTI_CHAIN_SOLANA_WALLET_NAMES","useEffect","useState","useWallet","PhantomProvider","isPhantom","publicKey","toBase58","isConnected","connect","opts","onlyIfTrusted","Promise","toString","on","event","handler","args","getPhantomProvider","window","undefined","w","phantom","solana","useSvmAddress","adapterPublicKey","phantomAddress","setPhantomAddress","provider","existing","then","res","catch","getPhantomProvider","Connection","Commitment","useMemo","useQuery","useAggUiConfig","useOptionalAggClient","DEFAULT_SOLANA_RPC_ENDPOINTS","resolveSvmRpcEndpoints","partnerUrl","seen","Set","out","candidates","url","has","add","push","useSvmConnections","commitment","solanaRpcUrl","client","data","tokenData","queryKey","queryFn","getRpcToken","Promise","resolve","token","expiresAt","enabled","staleTime","endpoints","map","headers","Record","includes","httpHeaders","Object","keys","length","undefined","withSvmFailover","connections","operation","connection","T","Error","lastError","err","Connection","PublicKey","useQuery","formatUnits","useAccount","useReadContract","SVM_CHAIN_IDS","useSvmAddress","useSvmConnections","withSvmFailover","ERC20_BALANCE_OF_ABI","name","type","stateMutability","inputs","outputs","const","UseWalletTokenBalanceParams","isOpen","chainId","tokenAddress","decimals","svmAddress","UseWalletTokenBalanceResult","balance","isLoading","SVM_BALANCE_RPC_TIMEOUT_MS","SVM_BALANCE_STALE_TIME_MS","SvmBalanceTimeoutError","Error","constructor","withTimeout","promise","Promise","T","timeoutMs","resolve","reject","timer","setTimeout","then","value","clearTimeout","err","fetchSvmTokenBalance","connections","owner","mint","accounts","connection","getParsedTokenAccountsByOwner","total","entry","uiAmount","account","data","parsed","info","tokenAmount","Number","isFinite","useWalletTokenBalance","isSvm","undefined","has","address","evmAddress","evmEnabled","rawEvmBalance","evmLoading","abi","functionName","args","query","enabled","staleTime","refetchOnMount","detectedSvmAddress","resolvedSvmAddress","svmEnabled","svmConnections","svmQuery","queryKey","retry","refetchOnWindowFocus","refetchOnReconnect","queryFn","awaitingSelection","isFetching","evmBalance","useCallback","parseUnits","useWriteContract","useWallet","Keypair","PublicKey","SystemProgram","Transaction","TransactionInstruction","SVM_CHAIN_IDS","useSvmConnections","withSvmFailover","PhantomProvider","publicKey","toString","toBase58","isConnected","connect","opts","onlyIfTrusted","Promise","signAndSendTransaction","tx","signature","getPhantomProvider","window","undefined","w","phantom","solana","ERC20_TRANSFER_ABI","constant","inputs","name","type","outputs","const","UseWalletSendTokenParams","chainId","token","symbol","address","decimals","to","amount","useWalletSendToken","params","txId","svmConnections","writeContractAsync","sendTransaction","isSvm","has","tokenAddress","Error","value","txHash","abi","functionName","args","ownerBase58","res","err","message","String","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","owner","mint","destinationOwner","getAta","walletPk","mintPk","ata","findProgramAddressSync","toBuffer","sourceAta","destinationAta","sendConnection","destinationTokenAccountSigner","destinationOwnerInfo","getAccountInfo","destinationInfo","destinationTokenAccount","rentExemptLamports","getMinimumBalanceForRentExemption","payerLamports","getBalance","feeBufferLamports","requiredLamports","requiredSol","toFixed","currentSol","canCreateAta","equals","programId","createIx","keys","pubkey","isSigner","isWritable","data","Buffer","alloc","add","generate","createAccount","fromPubkey","newAccountPubkey","lamports","space","initAccountData","concat","from","factor","BigInt","i","amountRaw","Math","trunc","Number","Uint8Array","remaining","mask","transferIx","feePayer","blockhash","getLatestBlockhash","recentBlockhash","partialSign","useQuery","formatEther","useWaitForTransactionReceipt","SVM_CHAIN_IDS","useSvmConnections","withSvmFailover","WalletTransactionStatus","UseWalletTransactionStatusParams","chainId","txId","UseWalletTransactionStatusResult","status","gasFee","useWalletTransactionStatus","isSvm","undefined","has","evmHash","evmReceipt","hash","query","enabled","refetchInterval","svmConnections","svmQuery","queryKey","state","data","queryFn","Promise","connection","getSignatureStatuses","searchTransactionHistory","value","err","confirmationStatus","isError","isPending","effectiveGasPrice","gasFeeWei","gasUsed","gasFeeEth","Number","toFixed","useCallback","useEffect","useMemo","useRef","useState","useAccount","useSwitchChain","useWallet","useSolanaWallet","useAggAuthState","useAggBalanceState","useAggClient","useAggUiConfig","useDepositAddresses","useSyncBalances","useRampQuotes","useRampSession","normalizeWalletError","useWalletSendToken","useWalletTokenBalance","useSvmAddress","useWalletTransactionStatus","WalletTransactionStatus","MULTI_CHAIN_SOLANA_WALLET_NAMES","SVM_CHAIN_IDS","DEFAULT_WALLET_CHAIN_ID","DEFAULT_WALLET_TOKEN_SYMBOL","CardProviderOption","id","name","quote","fee","badge","CardPurchaseSummary","amountReceived","network","fees","WalletDepositConfirmParams","address","amount","chainId","token","DepositSelectOption","value","label","UseDepositFlowResult","open","onOpenChange","pendingCardPurchaseSummary","walletFlow","balance","walletLabel","walletBalance","isWalletBalanceLoading","formErrorMessage","formErrorTone","transactionStatus","transactionErrorMessage","successSummary","fromWallet","gasFee","onWalletAmountChange","onWalletMax","onConfirmWalletDeposit","params","Promise","onCancelWalletDeposit","onWalletNetworkChange","onWalletTokenChange","tokenSymbol","initialWalletChainId","connectedWalletKind","sendCryptoConfig","minDeposit","eta","onDoneSendCrypto","cardFlow","currency","tokenOptions","selectedToken","selectedNetwork","providers","purchaseSummary","minAmount","onCardAmountChange","onCardNetworkChange","onDoneCardPurchase","cardRedirectUrl","onGetCardQuotes","sourceAmount","sourceCurrencyCode","destinationCurrencyCode","onCreateCardSession","serviceProvider","walletAddress","redirectUrl","widgetUrl","serviceProviderWidgetUrl","UseDepositFlowOptions","useDepositFlow","options","client","user","walletActions","totalBalance","deposit","enabled","supportedChains","mutate","syncBalancesMutate","defaultSendToken","sendToken","mutateAsync","getRampQuotes","createRampSession","depositAmount","setDepositAmount","cardAmount","setCardAmount","cardNetwork","setCardNetwork","walletModalChainId","setWalletModalChainId","walletModalTokenSymbol","setWalletModalTokenSymbol","walletTransaction","setWalletTransaction","txId","walletTransactionError","setWalletTransactionError","walletTransactionErrorTone","setWalletTransactionErrorTone","setPendingCardPurchaseSummary","rampRedirectHandled","current","window","url","URL","location","href","cryptoAmount","searchParams","get","cryptoCurrency","totalFee","charAt","toUpperCase","slice","connectedChainId","connectedAddress","switchChainAsync","wallet","solanaWallet","resolvedSvmAddress","solanaAdapterName","adapter","isMultiChainSolanaWallet","Boolean","has","hasSolanaCapability","hasEvmCapability","defaultBalanceChainId","some","chain","balanceChainId","Number","selectedChainTokens","find","c","tokens","selectedTokenMeta","preferredTokenSymbol","match","t","symbol","decimals","undefined","isSvmBalanceChain","isLoading","isOpen","tokenAddress","status","observedWalletTransactionStatus","walletTransactionGasFee","walletTransactionStatus","syncedDepositTxIdRef","handleDepositModalOpenChange","handleCancelWalletDeposit","handleConfirmWalletDeposit","tokenMeta","isEvmTarget","to","recordDepositIntent","txHash","catch","err","normalizedError","message","tone","handleGetCardQuotes","quotes","map","q","i","destinationAmount","toFixed","lowKyc","handleCreateCardSession","Error","session","origin","String","history","replaceState","pathname","useSolanaWallet"],"sources":["../src/deposit/normalize-wallet-error.ts","../src/deposit/constants.ts","../src/deposit/use-svm-address.ts","../src/deposit/svm-connections.ts","../src/deposit/use-wallet-token-balance.ts","../src/deposit/use-wallet-send-token.ts","../src/deposit/use-wallet-transaction-status.ts","../src/deposit/use-deposit-flow.ts"],"sourcesContent":["type SupportedChain = {\n chainId: number;\n name: string;\n tokens: Array<{ symbol: string; address: string; decimals: number }>;\n};\n\nexport function normalizeWalletError(\n error: unknown,\n supportedChains: SupportedChain[] | undefined,\n): { message: string; tone: \"warning\" | \"error\" } {\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n\n if (\n lower.includes(\"user rejected\") ||\n lower.includes(\"user denied\") ||\n lower.includes(\"rejected the request\") ||\n lower.includes(\"denied transaction signature\")\n ) {\n return { message: \"Wallet request rejected.\", tone: \"error\" };\n }\n\n const chainMismatch =\n message.includes(\"does not match the target chain\") || message.includes(\"Expected Chain ID:\");\n\n if (chainMismatch) {\n const match = message.match(/Expected Chain ID:\\s*(\\d+)/i);\n const targetChainId = match ? Number(match[1]) : undefined;\n const targetChainName =\n supportedChains?.find((chain) => chain.chainId === targetChainId)?.name ??\n (targetChainId ? `chain ${targetChainId}` : \"the selected chain\");\n\n return {\n message: `Wallet chain does not match. Please switch your wallet to ${targetChainName}.`,\n tone: \"warning\",\n };\n }\n\n return { message, tone: \"error\" };\n}\n","/**\n * Priority-ordered list of Solana RPC endpoints the deposit hooks fall back\n * through when the previous endpoint errors or times out. The partner-supplied\n * `solanaRpcUrl` (when present) is prepended at runtime; these are the\n * always-on safety net so a single provider outage never strands users on a\n * \"0 balance\" screen.\n */\nexport const DEFAULT_SOLANA_RPC_ENDPOINTS: readonly string[] = [\n \"https://solana-mainnet.g.alchemy.com/v2\",\n \"https://solana-rpc.publicnode.com\",\n \"https://api.mainnet.solana.com\",\n \"https://rpc.ankr.com/solana\",\n];\n\n/**\n * Back-compat alias for callers that still want a single default endpoint.\n * New code should prefer the full list and the failover helper.\n */\nexport const DEFAULT_SOLANA_RPC_ENDPOINT = \"https://solana-rpc.publicnode.com\";\n\nexport const SVM_CHAIN_IDS: ReadonlySet<number> = new Set<number>([792703809]);\n\nexport const MULTI_CHAIN_SOLANA_WALLET_NAMES: ReadonlySet<string> = new Set<string>([\"Phantom\"]);\n","import { useEffect, useState } from \"react\";\nimport { useWallet } from \"@solana/wallet-adapter-react\";\n\ninterface PhantomProvider {\n isPhantom?: boolean;\n publicKey?: { toBase58(): string } | null;\n isConnected?: boolean;\n connect: (opts?: { onlyIfTrusted?: boolean }) => Promise<{ publicKey: { toString(): string } }>;\n on?: (event: string, handler: (...args: unknown[]) => void) => void;\n}\n\nfunction getPhantomProvider(): PhantomProvider | undefined {\n if (typeof window === \"undefined\") return undefined;\n const w = window as unknown as {\n phantom?: { solana?: PhantomProvider };\n solana?: PhantomProvider;\n };\n return w.phantom?.solana ?? w.solana;\n}\n\nexport function useSvmAddress(): string | undefined {\n const { publicKey: adapterPublicKey } = useWallet();\n const [phantomAddress, setPhantomAddress] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n const provider = getPhantomProvider();\n if (!provider) return;\n\n const existing = provider.publicKey?.toBase58();\n if (existing) {\n setPhantomAddress(existing);\n return;\n }\n\n provider\n .connect({ onlyIfTrusted: true })\n .then((res) => setPhantomAddress(res.publicKey.toString()))\n .catch(() => {\n // Not trusted yet — leave phantomAddress undefined and rely on\n // the wallet-adapter publicKey if/when it hydrates.\n });\n }, []);\n\n return adapterPublicKey?.toBase58() ?? phantomAddress;\n}\n","import { Connection, type Commitment } from \"@solana/web3.js\";\nimport { useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useAggUiConfig, useOptionalAggClient } from \"../core/provider\";\nimport { DEFAULT_SOLANA_RPC_ENDPOINTS } from \"./constants\";\n\n/**\n * Resolves the priority-ordered list of Solana RPC URLs to try, with the\n * partner-supplied URL first (when present) and the built-in defaults as a\n * safety net. De-duplicated so we never hit the same endpoint twice in a\n * single failover round.\n */\nexport function resolveSvmRpcEndpoints(partnerUrl: string | undefined): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n const candidates = partnerUrl\n ? [partnerUrl, ...DEFAULT_SOLANA_RPC_ENDPOINTS]\n : DEFAULT_SOLANA_RPC_ENDPOINTS;\n for (const url of candidates) {\n if (!seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n return out;\n}\n\n/**\n * Returns a memoized list of `Connection` instances, one per resolved RPC\n * endpoint, in failover priority order. The primary connection is\n * `connections[0]`; subsequent entries are tried only when an operation\n * against the previous entry throws.\n *\n * `new Connection(...)` is lazy (no socket is opened), so eagerly building\n * fallback connections has negligible cost.\n */\nexport function useSvmConnections(commitment?: Commitment): readonly Connection[] {\n const { solanaRpcUrl } = useAggUiConfig();\n const client = useOptionalAggClient();\n\n const { data: tokenData } = useQuery({\n queryKey: [\"alchemy-rpc-token\"],\n queryFn: () => (client ? client.getRpcToken() : Promise.resolve({ token: \"\", expiresAt: 0 })),\n enabled: !!client,\n staleTime: 50 * 60 * 1000, // 50 minutes cache (token is valid for 1h)\n });\n\n const token = tokenData?.token;\n\n return useMemo(() => {\n const endpoints = resolveSvmRpcEndpoints(solanaRpcUrl);\n return endpoints.map((url) => {\n const headers: Record<string, string> = {};\n if (url.includes(\"alchemy.com\") && token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n return new Connection(url, {\n commitment,\n httpHeaders: Object.keys(headers).length > 0 ? headers : undefined,\n });\n });\n }, [solanaRpcUrl, commitment, token]);\n}\n\n/**\n * Runs `operation` against the first connection that returns successfully.\n * Connections are tried in priority order; on any thrown error (network\n * failure, timeout, RPC error) we advance to the next.\n *\n * The happy path issues exactly one underlying RPC call — we only fan out\n * when the previous endpoint failed. If every endpoint fails, the last\n * error is rethrown so the caller (and `useQuery`) sees the real cause.\n */\nexport async function withSvmFailover<T>(\n connections: readonly Connection[],\n operation: (connection: Connection) => Promise<T>,\n): Promise<T> {\n if (connections.length === 0) {\n throw new Error(\"No Solana RPC connections configured\");\n }\n let lastError: unknown;\n for (const connection of connections) {\n try {\n return await operation(connection);\n } catch (err) {\n lastError = err;\n }\n }\n throw lastError instanceof Error\n ? lastError\n : new Error(typeof lastError === \"string\" ? lastError : \"All Solana RPC endpoints failed\");\n}\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { formatUnits } from \"viem\";\nimport { useAccount, useReadContract } from \"wagmi\";\nimport { SVM_CHAIN_IDS } from \"./constants\";\nimport { useSvmAddress } from \"./use-svm-address\";\nimport { useSvmConnections, withSvmFailover } from \"./svm-connections\";\n\nconst ERC20_BALANCE_OF_ABI = [\n {\n name: \"balanceOf\",\n type: \"function\",\n stateMutability: \"view\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n] as const;\n\nexport interface UseWalletTokenBalanceParams {\n isOpen?: boolean;\n chainId: number | undefined;\n tokenAddress: string | undefined;\n decimals: number | undefined;\n /**\n * Explicit Solana wallet address (base58) fallback — used when the\n * wallet-adapter and Phantom injected provider haven't hydrated yet.\n */\n svmAddress?: string;\n}\n\nexport interface UseWalletTokenBalanceResult {\n balance: number;\n isLoading: boolean;\n}\n\nconst SVM_BALANCE_RPC_TIMEOUT_MS = 2_000;\nconst SVM_BALANCE_STALE_TIME_MS = 30_000;\n\nclass SvmBalanceTimeoutError extends Error {\n constructor() {\n super(\"Solana balance request timed out\");\n this.name = \"SvmBalanceTimeoutError\";\n }\n}\n\nfunction withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new SvmBalanceTimeoutError()), timeoutMs);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\n/**\n * Reads the connected wallet's SPL token balance for `mint`.\n *\n * A Solana wallet routinely owns multiple SPL accounts for the same mint —\n * the canonical ATA plus dust accounts created by dApps (each with their\n * own `closeAuthority`). The RPC does not order them deterministically, so\n * picking `accounts.value[0]` and calling `getTokenAccountBalance` for it\n * (the previous implementation) frequently returned 0 even when the user\n * was funded on a sibling account. Phantom/Solflare display the sum across\n * every account on the mint; we match that here.\n *\n * Uses `getParsedTokenAccountsByOwner` so `uiAmount` arrives on the first\n * response — one RPC round-trip per refetch instead of two. The per-endpoint\n * timeout caps how long we wait before falling over to the next RPC.\n */\nasync function fetchSvmTokenBalance(\n connections: readonly Connection[],\n owner: PublicKey,\n mint: PublicKey,\n): Promise<number> {\n const accounts = await withSvmFailover(connections, (connection) =>\n withTimeout(\n connection.getParsedTokenAccountsByOwner(owner, { mint }),\n SVM_BALANCE_RPC_TIMEOUT_MS,\n ),\n );\n let total = 0;\n for (const entry of accounts.value) {\n const uiAmount = entry.account.data.parsed?.info?.tokenAmount?.uiAmount;\n if (typeof uiAmount === \"number\" && Number.isFinite(uiAmount)) {\n total += uiAmount;\n }\n }\n return total;\n}\n\n/**\n * Reads the connected wallet's on-chain balance for a given token on a given chain.\n * Dispatches to wagmi (EVM) or @solana/web3.js (SVM) based on chainId.\n */\nexport function useWalletTokenBalance({\n isOpen = true,\n chainId,\n tokenAddress,\n decimals,\n svmAddress,\n}: UseWalletTokenBalanceParams): UseWalletTokenBalanceResult {\n const isSvm = chainId !== undefined && SVM_CHAIN_IDS.has(chainId);\n\n // ── EVM path ─────────────────────────────────────────────────────\n const { address: evmAddress } = useAccount();\n const evmEnabled =\n isOpen && !isSvm && !!chainId && !!tokenAddress && !!evmAddress && decimals !== undefined;\n\n const { data: rawEvmBalance, isLoading: evmLoading } = useReadContract({\n address: tokenAddress as `0x${string}` | undefined,\n chainId,\n abi: ERC20_BALANCE_OF_ABI,\n functionName: \"balanceOf\",\n args: evmAddress ? [evmAddress] : undefined,\n query: { enabled: evmEnabled, staleTime: 0, refetchOnMount: true },\n });\n\n // ── SVM address resolution ───────────────────────────────────────\n const detectedSvmAddress = useSvmAddress();\n const resolvedSvmAddress = detectedSvmAddress ?? svmAddress;\n\n const svmEnabled = isOpen && isSvm && !!resolvedSvmAddress && !!tokenAddress;\n\n // Failover chain: partner URL first (when set), then built-in defaults.\n // Connections are memoized by `useSvmConnections` so refetches reuse them.\n const svmConnections = useSvmConnections();\n\n const svmQuery = useQuery<number>({\n queryKey: [\"svm-token-balance\", resolvedSvmAddress ?? null, tokenAddress ?? null, isOpen],\n enabled: svmEnabled,\n staleTime: SVM_BALANCE_STALE_TIME_MS,\n retry: false,\n refetchOnWindowFocus: \"always\",\n refetchOnReconnect: \"always\",\n queryFn: async () => {\n if (!resolvedSvmAddress || !tokenAddress) return 0;\n const owner = new PublicKey(resolvedSvmAddress);\n const mint = new PublicKey(tokenAddress);\n return await fetchSvmTokenBalance(svmConnections, owner, mint);\n },\n });\n\n if (isSvm) {\n const awaitingSelection = isOpen && !!chainId && !tokenAddress;\n return {\n balance: svmQuery.data ?? 0,\n isLoading: awaitingSelection || svmQuery.isLoading || svmQuery.isFetching,\n };\n }\n\n const evmBalance =\n rawEvmBalance !== undefined && decimals !== undefined\n ? Number(formatUnits(rawEvmBalance as bigint, decimals))\n : 0;\n\n const awaitingSelection = isOpen && !!chainId && !tokenAddress;\n\n return { balance: evmBalance, isLoading: awaitingSelection || evmLoading };\n}\n","import { useCallback } from \"react\";\nimport { parseUnits } from \"viem\";\nimport { useWriteContract } from \"wagmi\";\nimport { useWallet } from \"@solana/wallet-adapter-react\";\nimport {\n Keypair,\n PublicKey,\n SystemProgram,\n Transaction,\n TransactionInstruction,\n} from \"@solana/web3.js\";\nimport { SVM_CHAIN_IDS } from \"./constants\";\nimport { useSvmConnections, withSvmFailover } from \"./svm-connections\";\n\ninterface PhantomProvider {\n publicKey?: { toString(): string; toBase58?(): string } | null;\n isConnected?: boolean;\n connect: (opts?: { onlyIfTrusted?: boolean }) => Promise<{ publicKey: { toString(): string } }>;\n signAndSendTransaction: (tx: unknown) => Promise<{ signature: string }>;\n}\n\nfunction getPhantomProvider(): PhantomProvider | undefined {\n if (typeof window === \"undefined\") return undefined;\n const w = window as unknown as {\n phantom?: { solana?: PhantomProvider };\n solana?: PhantomProvider;\n };\n return w.phantom?.solana ?? w.solana;\n}\n\n// Minimal ERC20 ABI for transfer(to, amount)\nconst ERC20_TRANSFER_ABI = [\n {\n constant: false,\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n name: \"transfer\",\n outputs: [{ name: \"\", type: \"bool\" }],\n type: \"function\",\n },\n] as const;\n\nexport interface UseWalletSendTokenParams {\n chainId: number;\n token: { symbol: string; address?: string; decimals: number };\n to: string;\n amount: string;\n}\n\n/**\n * Dual-chain sendToken implementation:\n * - EVM: uses wagmi writeContract to call ERC-20 transfer\n * - SVM: uses wallet-adapter (or injected Phantom) to submit an SPL TransferChecked tx\n *\n * Matches the `WalletActions.sendToken` signature so it can be passed into\n * `AggProvider` config directly, or composed inside `useDepositFlow`.\n */\nexport function useWalletSendToken(): (\n params: UseWalletSendTokenParams,\n) => Promise<{ txId: string }> {\n const svmConnections = useSvmConnections(\"confirmed\");\n\n const { writeContractAsync } = useWriteContract();\n const { publicKey, sendTransaction } = useWallet();\n\n return useCallback(\n async (params: UseWalletSendTokenParams) => {\n const isSvm = SVM_CHAIN_IDS.has(params.chainId);\n\n if (!isSvm) {\n // ── EVM path ───────────────────────────────────────────────────\n const tokenAddress = params.token.address as `0x${string}` | undefined;\n if (!tokenAddress) {\n throw new Error(\"Missing ERC-20 token address for EVM transfer\");\n }\n\n const value = parseUnits(params.amount || \"0\", params.token.decimals);\n\n const txHash = await writeContractAsync({\n chainId: params.chainId,\n address: tokenAddress,\n abi: ERC20_TRANSFER_ABI,\n functionName: \"transfer\",\n args: [params.to as `0x${string}`, value],\n });\n return { txId: txHash as string };\n }\n\n // ── SVM path ─────────────────────────────────────────────────────\n if (!params.token.address) {\n throw new Error(\"Missing SPL token mint address for Solana transfer\");\n }\n\n const phantom = getPhantomProvider();\n let ownerBase58: string | undefined = publicKey?.toBase58();\n if (!ownerBase58 && phantom) {\n try {\n const res = await phantom.connect();\n ownerBase58 = res.publicKey.toString();\n } catch (err) {\n throw new Error(\n `Failed to connect Phantom: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n if (!ownerBase58) {\n throw new Error(\"No Solana wallet connected\");\n }\n\n const TOKEN_PROGRAM_ID = new PublicKey(\"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\");\n const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey(\n \"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\",\n );\n\n const owner = new PublicKey(ownerBase58);\n const mint = new PublicKey(params.token.address);\n const destinationOwner = new PublicKey(params.to);\n\n const getAta = (walletPk: PublicKey, mintPk: PublicKey) => {\n const [ata] = PublicKey.findProgramAddressSync(\n [walletPk.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mintPk.toBuffer()],\n ASSOCIATED_TOKEN_PROGRAM_ID,\n );\n return ata;\n };\n const sourceAta = getAta(owner, mint);\n const destinationAta = getAta(destinationOwner, mint);\n\n // Whole prep + broadcast runs against one RPC. If that RPC fails at\n // any step we fall over to the next endpoint; reads are re-issued and\n // the wallet may re-prompt for signature. This is rare (only when an\n // RPC outage hits mid-flight) and recoverable for the user.\n const signature = await withSvmFailover(svmConnections, async (sendConnection) => {\n const tx = new Transaction();\n let destinationTokenAccountSigner: Keypair | null = null;\n\n const destinationOwnerInfo = await sendConnection.getAccountInfo(destinationOwner);\n const destinationInfo = await sendConnection.getAccountInfo(destinationAta);\n let destinationTokenAccount = destinationAta;\n if (!destinationInfo) {\n const rentExemptLamports = await sendConnection.getMinimumBalanceForRentExemption(165);\n const payerLamports = await sendConnection.getBalance(owner, \"confirmed\");\n const feeBufferLamports = 10_000;\n const requiredLamports = rentExemptLamports + feeBufferLamports;\n\n if (payerLamports < requiredLamports) {\n const requiredSol = (requiredLamports / 1_000_000_000).toFixed(6);\n const currentSol = (payerLamports / 1_000_000_000).toFixed(6);\n throw new Error(\n `This Solana deposit needs about ${requiredSol} SOL to create the destination token account, but the connected wallet only has ${currentSol} SOL available.`,\n );\n }\n\n const canCreateAta =\n destinationOwnerInfo?.owner?.equals(SystemProgram.programId) ?? false;\n\n if (canCreateAta) {\n const createIx = new TransactionInstruction({\n programId: ASSOCIATED_TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: owner, isSigner: true, isWritable: true },\n { pubkey: destinationAta, isSigner: false, isWritable: true },\n { pubkey: destinationOwner, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: Buffer.alloc(0),\n });\n tx.add(createIx);\n } else {\n destinationTokenAccountSigner = Keypair.generate();\n destinationTokenAccount = destinationTokenAccountSigner.publicKey;\n tx.add(\n SystemProgram.createAccount({\n fromPubkey: owner,\n newAccountPubkey: destinationTokenAccount,\n lamports: rentExemptLamports,\n space: 165,\n programId: TOKEN_PROGRAM_ID,\n }),\n );\n\n const initAccountData = Buffer.concat([\n Buffer.from([18]), // InitializeAccount3\n destinationOwner.toBuffer(),\n ]);\n tx.add(\n new TransactionInstruction({\n programId: TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: destinationTokenAccount, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n ],\n data: initAccountData,\n }),\n );\n }\n }\n\n // Build TransferChecked instruction (index 12)\n // Layout: [tag u8 | amount u64 LE | decimals u8] = 10 bytes\n let factor = BigInt(1);\n for (let i = 0; i < params.token.decimals; i += 1) {\n factor *= BigInt(10);\n }\n const amountRaw = BigInt(Math.trunc(Number(params.amount || \"0\") * Number(factor)));\n const data = new Uint8Array(10);\n data[0] = 12; // TransferChecked tag\n let remaining = amountRaw;\n const mask = BigInt(0xff);\n for (let i = 0; i < 8; i += 1) {\n data[1 + i] = Number(remaining & mask);\n remaining >>= BigInt(8);\n }\n data[9] = params.token.decimals;\n\n const transferIx = new TransactionInstruction({\n programId: TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: sourceAta, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: destinationTokenAccount, isSigner: false, isWritable: true },\n { pubkey: owner, isSigner: true, isWritable: false },\n ],\n data: Buffer.from(data),\n });\n tx.add(transferIx);\n\n tx.feePayer = owner;\n const { blockhash } = await sendConnection.getLatestBlockhash(\"confirmed\");\n tx.recentBlockhash = blockhash;\n if (destinationTokenAccountSigner) {\n tx.partialSign(destinationTokenAccountSigner);\n }\n\n if (publicKey && sendTransaction) {\n return await sendTransaction(tx, sendConnection);\n }\n if (phantom) {\n const res = await phantom.signAndSendTransaction(tx);\n return res.signature;\n }\n throw new Error(\"No Solana signer available\");\n });\n\n return { txId: signature };\n },\n [publicKey, sendTransaction, svmConnections, writeContractAsync],\n );\n}\n","import { useQuery } from \"@tanstack/react-query\";\nimport { formatEther } from \"viem\";\nimport { useWaitForTransactionReceipt } from \"wagmi\";\nimport { SVM_CHAIN_IDS } from \"./constants\";\nimport { useSvmConnections, withSvmFailover } from \"./svm-connections\";\n\nexport type WalletTransactionStatus = \"submitted\" | \"confirming\" | \"settled\" | \"error\";\n\nexport interface UseWalletTransactionStatusParams {\n chainId: number | undefined;\n txId: string | null;\n}\n\nexport interface UseWalletTransactionStatusResult {\n status: WalletTransactionStatus | null;\n gasFee: string;\n}\n\nexport function useWalletTransactionStatus({\n chainId,\n txId,\n}: UseWalletTransactionStatusParams): UseWalletTransactionStatusResult {\n const isSvm = chainId !== undefined && SVM_CHAIN_IDS.has(chainId);\n const evmHash = !isSvm && txId ? (txId as `0x${string}`) : undefined;\n\n const evmReceipt = useWaitForTransactionReceipt({\n chainId,\n hash: evmHash,\n query: {\n enabled: !!evmHash && !!chainId,\n refetchInterval: 2_000,\n },\n });\n\n const svmConnections = useSvmConnections(\"confirmed\");\n const svmQuery = useQuery({\n queryKey: [\"wallet-transaction-status\", chainId ?? null, txId ?? null],\n enabled: isSvm && !!txId,\n refetchInterval: (query) =>\n query.state.data === \"settled\" || query.state.data === \"error\" ? false : 2_000,\n queryFn: async (): Promise<WalletTransactionStatus> => {\n if (!txId) return \"submitted\";\n\n const [status] = (\n await withSvmFailover(svmConnections, (connection) =>\n connection.getSignatureStatuses([txId], { searchTransactionHistory: true }),\n )\n ).value;\n\n if (!status) return \"submitted\";\n if (status.err) return \"error\";\n if (status.confirmationStatus === \"confirmed\" || status.confirmationStatus === \"finalized\") {\n return \"settled\";\n }\n return \"confirming\";\n },\n });\n\n if (isSvm) {\n return { status: txId ? (svmQuery.data ?? \"submitted\") : null, gasFee: \"\" };\n }\n\n if (!txId) {\n return { status: null, gasFee: \"\" };\n }\n\n if (evmReceipt.isError) {\n return { status: \"error\", gasFee: \"\" };\n }\n\n if (!evmReceipt.data) {\n return { status: evmReceipt.isPending ? \"confirming\" : \"submitted\", gasFee: \"\" };\n }\n\n const effectiveGasPrice = evmReceipt.data.effectiveGasPrice;\n const gasFeeWei = effectiveGasPrice * evmReceipt.data.gasUsed;\n const gasFeeEth = Number(formatEther(gasFeeWei));\n const gasFee = gasFeeEth > 0 ? `${gasFeeEth.toFixed(6)} ETH` : \"\";\n\n return { status: \"settled\", gasFee };\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAccount, useSwitchChain } from \"wagmi\";\nimport { useWallet as useSolanaWallet } from \"@solana/wallet-adapter-react\";\nimport {\n useAggAuthState,\n useAggBalanceState,\n useAggClient,\n useAggUiConfig,\n} from \"../core/provider\";\nimport { useDepositAddresses, useSyncBalances } from \"../execution\";\nimport { useRampQuotes } from \"../use-ramp-quotes\";\nimport { useRampSession } from \"../use-ramp-session\";\nimport { normalizeWalletError } from \"./normalize-wallet-error\";\nimport { useWalletSendToken } from \"./use-wallet-send-token\";\nimport { useWalletTokenBalance } from \"./use-wallet-token-balance\";\nimport { useSvmAddress } from \"./use-svm-address\";\nimport {\n useWalletTransactionStatus,\n type WalletTransactionStatus,\n} from \"./use-wallet-transaction-status\";\nimport { MULTI_CHAIN_SOLANA_WALLET_NAMES, SVM_CHAIN_IDS } from \"./constants\";\n\nconst DEFAULT_WALLET_CHAIN_ID = 1;\nconst DEFAULT_WALLET_TOKEN_SYMBOL = \"USDC\";\n\ntype CardProviderOption = {\n id: string;\n name: string;\n quote: string;\n fee: string;\n badge?: \"best\" | \"low-kyc\";\n};\n\ntype CardPurchaseSummary = {\n amountReceived: string;\n network: string;\n fees: string;\n};\n\ntype WalletDepositConfirmParams = {\n address: string;\n amount: string;\n chainId: number;\n token: string;\n};\n\ntype DepositSelectOption = { value: string; label: string };\n\n/**\n * Subset of `DepositModalProps` populated by {@link useDepositFlow}. Callers\n * spread this onto `<DepositModal>`; any prop the caller passes explicitly\n * overrides the orchestrator. Typed loosely here so `@agg-build/hooks`\n * doesn't take a build-time dependency on `@agg-build/ui`.\n */\nexport interface UseDepositFlowResult {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n pendingCardPurchaseSummary: CardPurchaseSummary | null;\n walletFlow: {\n balance: number;\n walletLabel: string;\n walletBalance: number;\n isWalletBalanceLoading: boolean;\n amount: string;\n formErrorMessage?: string;\n formErrorTone: \"warning\" | \"error\";\n transactionStatus: WalletTransactionStatus | undefined;\n transactionErrorMessage?: string;\n successSummary: {\n fromWallet: string;\n gasFee: string;\n };\n };\n onWalletAmountChange: (amount: string) => void;\n onWalletMax: () => void;\n onConfirmWalletDeposit: (params: WalletDepositConfirmParams) => Promise<void>;\n /**\n * Clears any in-flight wallet-transaction state so the deposit modal can\n * return the user to the wallet form. Called from the processing step's\n * Cancel affordance when a wallet popup was dismissed silently or a\n * broadcast tx was canceled/replaced without a clean error.\n */\n onCancelWalletDeposit: () => void;\n onWalletNetworkChange: (chainId: string) => void;\n onWalletTokenChange: (tokenSymbol: string) => void;\n initialWalletChainId: string | undefined;\n /** External wallet kind, when only one is connected. Lets the modal filter\n * wallet-flow network options to chains compatible with that wallet.\n * `undefined` when neither or both are connected — modal shows all chains. */\n connectedWalletKind?: \"evm\" | \"solana\";\n sendCryptoConfig: { minDeposit: string; eta: string };\n onDoneSendCrypto: () => void;\n cardFlow: {\n amount: string;\n currency: string;\n tokenOptions: DepositSelectOption[];\n selectedToken: string;\n selectedNetwork: string;\n providers: CardProviderOption[];\n purchaseSummary: CardPurchaseSummary;\n minAmount: number;\n };\n onCardAmountChange: (amount: string) => void;\n onCardNetworkChange: (network: string) => void;\n onDoneCardPurchase: () => void;\n cardRedirectUrl: string | undefined;\n onGetCardQuotes: (params: {\n sourceAmount: string;\n sourceCurrencyCode: string;\n destinationCurrencyCode: string;\n }) => Promise<CardProviderOption[]>;\n onCreateCardSession: (params: {\n serviceProvider: string;\n sourceAmount: string;\n sourceCurrencyCode: string;\n destinationCurrencyCode: string;\n walletAddress: string;\n redirectUrl?: string;\n }) => Promise<{ id: string; widgetUrl: string; serviceProviderWidgetUrl: string }>;\n}\n\nexport interface UseDepositFlowOptions {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n}\n\n/**\n * Orchestrator hook that encapsulates all wallet + card deposit state and\n * glue previously hand-wired inside partner apps. Spread the return value\n * onto `<DepositModal>` to get the full plug-and-play deposit experience.\n *\n * Requires wagmi + @solana/wallet-adapter-react providers in the React tree.\n */\nexport function useDepositFlow(options: UseDepositFlowOptions): UseDepositFlowResult {\n const { open, onOpenChange } = options;\n const client = useAggClient();\n const { user } = useAggAuthState();\n const { walletActions } = useAggUiConfig();\n const { totalBalance } = useAggBalanceState();\n const deposit = useDepositAddresses({ enabled: !!user });\n const { supportedChains } = deposit;\n const { mutate: syncBalancesMutate } = useSyncBalances();\n const defaultSendToken = useWalletSendToken();\n const sendToken = walletActions?.sendToken ?? defaultSendToken;\n const { mutateAsync: getRampQuotes } = useRampQuotes();\n const { mutateAsync: createRampSession } = useRampSession();\n\n const [depositAmount, setDepositAmount] = useState(\"\");\n const [cardAmount, setCardAmount] = useState(\"\");\n const [cardNetwork, setCardNetwork] = useState(\"solana\");\n const [walletModalChainId, setWalletModalChainId] = useState<string | null>(null);\n const [walletModalTokenSymbol, setWalletModalTokenSymbol] = useState<string | null>(null);\n const [walletTransaction, setWalletTransaction] = useState<{\n chainId: number;\n txId: string;\n } | null>(null);\n const [walletTransactionError, setWalletTransactionError] = useState<string | null>(null);\n const [walletTransactionErrorTone, setWalletTransactionErrorTone] = useState<\"warning\" | \"error\">(\n \"error\",\n );\n const [pendingCardPurchaseSummary, setPendingCardPurchaseSummary] =\n useState<CardPurchaseSummary | null>(null);\n\n // Auto-open deposit modal if returning from a ramp redirect.\n const rampRedirectHandled = useRef(false);\n useEffect(() => {\n if (rampRedirectHandled.current) return;\n if (typeof window === \"undefined\") return;\n\n const url = new URL(window.location.href);\n const cryptoAmount = url.searchParams.get(\"cryptoAmount\");\n const cryptoCurrency = url.searchParams.get(\"cryptoCurrency\");\n if (!cryptoAmount) return;\n\n rampRedirectHandled.current = true;\n\n const network = url.searchParams.get(\"network\") ?? \"\";\n const totalFee = url.searchParams.get(\"totalFeeInFiat\") ?? \"\";\n\n setPendingCardPurchaseSummary({\n amountReceived: `+${cryptoAmount} ${cryptoCurrency ?? \"USDC\"}`,\n network: network.charAt(0).toUpperCase() + network.slice(1),\n fees: totalFee ? `$${totalFee}` : \"\",\n });\n onOpenChange(true);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const { chainId: connectedChainId, address: connectedAddress } = useAccount();\n const { switchChainAsync } = useSwitchChain();\n const { wallet: solanaWallet } = useSolanaWallet();\n\n const resolvedSvmAddress = useSvmAddress();\n\n const solanaAdapterName = solanaWallet?.adapter?.name;\n\n const isMultiChainSolanaWallet = Boolean(\n solanaAdapterName && MULTI_CHAIN_SOLANA_WALLET_NAMES.has(solanaAdapterName),\n );\n const hasSolanaCapability = Boolean(resolvedSvmAddress || solanaWallet?.adapter);\n const hasEvmCapability = Boolean(connectedAddress) || isMultiChainSolanaWallet;\n\n const defaultBalanceChainId =\n hasEvmCapability && supportedChains?.some((chain) => chain.chainId === DEFAULT_WALLET_CHAIN_ID)\n ? DEFAULT_WALLET_CHAIN_ID\n : connectedChainId;\n const balanceChainId = walletModalChainId ? Number(walletModalChainId) : defaultBalanceChainId;\n\n const selectedChainTokens = useMemo(() => {\n if (!supportedChains || !balanceChainId) return [];\n const chain = supportedChains.find((c) => c.chainId === balanceChainId);\n return chain?.tokens ?? [];\n }, [supportedChains, balanceChainId]);\n\n const selectedTokenMeta = useMemo(() => {\n const preferredTokenSymbol = walletModalTokenSymbol ?? DEFAULT_WALLET_TOKEN_SYMBOL;\n const match = selectedChainTokens.find((t) => t.symbol === preferredTokenSymbol);\n return match ? { address: match.address, decimals: match.decimals } : undefined;\n }, [selectedChainTokens, walletModalTokenSymbol]);\n\n const isSvmBalanceChain = balanceChainId !== undefined && SVM_CHAIN_IDS.has(balanceChainId);\n const walletAddress = useMemo(() => {\n if (isSvmBalanceChain) {\n return resolvedSvmAddress ?? \"\";\n }\n return connectedAddress ?? \"\";\n }, [connectedAddress, isSvmBalanceChain, resolvedSvmAddress]);\n\n const walletLabel = useMemo(() => {\n return walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : \"—\";\n }, [walletAddress]);\n\n const { balance: walletBalance, isLoading: isWalletBalanceLoading } = useWalletTokenBalance({\n isOpen: open,\n chainId: balanceChainId,\n tokenAddress: selectedTokenMeta?.address,\n decimals: selectedTokenMeta?.decimals,\n });\n\n const { status: observedWalletTransactionStatus, gasFee: walletTransactionGasFee } =\n useWalletTransactionStatus({\n chainId: walletTransaction?.chainId,\n txId: walletTransaction?.txId ?? null,\n });\n\n const walletTransactionStatus: WalletTransactionStatus | undefined = walletTransactionError\n ? \"error\"\n : walletTransaction\n ? (observedWalletTransactionStatus ?? \"submitted\")\n : undefined;\n\n const syncedDepositTxIdRef = useRef<string | null>(null);\n useEffect(() => {\n if (walletTransactionStatus !== \"settled\" || !walletTransaction?.txId) return;\n if (syncedDepositTxIdRef.current === walletTransaction.txId) return;\n\n syncedDepositTxIdRef.current = walletTransaction.txId;\n syncBalancesMutate();\n }, [syncBalancesMutate, walletTransaction?.txId, walletTransactionStatus]);\n\n const handleDepositModalOpenChange = useCallback(\n (isOpen: boolean) => {\n if (!isOpen) {\n setDepositAmount(\"\");\n setCardAmount(\"\");\n setCardNetwork(\"solana\");\n setWalletModalChainId(null);\n setWalletModalTokenSymbol(null);\n setWalletTransaction(null);\n setWalletTransactionError(null);\n setWalletTransactionErrorTone(\"error\");\n setPendingCardPurchaseSummary(null);\n syncedDepositTxIdRef.current = null;\n }\n onOpenChange(isOpen);\n },\n [onOpenChange],\n );\n\n // Clear every piece of wallet-transaction state so the modal can return\n // to the form and a subsequent retry starts fresh. Called by the\n // processing step's \"Cancel deposit\" button — covers the cases where the\n // wallet promise never resolves (popup dismissed silently) or the tx was\n // broadcast and later canceled/replaced from the wallet UI without the\n // receipt query erroring out.\n const handleCancelWalletDeposit = useCallback(() => {\n setWalletTransaction(null);\n setWalletTransactionError(null);\n setWalletTransactionErrorTone(\"error\");\n syncedDepositTxIdRef.current = null;\n }, []);\n\n const handleConfirmWalletDeposit = useCallback(\n async (params: WalletDepositConfirmParams) => {\n const { address, amount, chainId, token } = params;\n const chain = supportedChains?.find((c) => c.chainId === chainId) ?? null;\n const tokenMeta = chain?.tokens.find((t) => t.symbol === token) ?? null;\n try {\n setWalletTransactionError(null);\n setWalletTransactionErrorTone(\"error\");\n const isEvmTarget = !SVM_CHAIN_IDS.has(chainId);\n if (isEvmTarget && connectedChainId && connectedChainId !== chainId) {\n await switchChainAsync({ chainId });\n }\n const { txId } = await sendToken({\n chainId,\n token: {\n symbol: token,\n address: tokenMeta?.address,\n decimals: tokenMeta?.decimals ?? 6,\n },\n to: address,\n amount,\n });\n setWalletTransaction({ chainId, txId });\n // SNA-2834: tell the API this deposit came from the in-app connected\n // wallet flow so the activity feed labels it connected_wallet. The\n // txId equals the on-chain transfer hash the deposit webhook records.\n // Best-effort: never let attribution break the deposit UX.\n void client.recordDepositIntent({ chainId, txHash: txId }).catch(() => {});\n } catch (err) {\n setWalletTransaction(null);\n const normalizedError = normalizeWalletError(err, supportedChains);\n setWalletTransactionError(normalizedError.message);\n setWalletTransactionErrorTone(normalizedError.tone);\n throw err;\n }\n },\n [client, connectedChainId, sendToken, supportedChains, switchChainAsync],\n );\n\n const handleGetCardQuotes = useCallback(\n async (params: {\n sourceAmount: string;\n sourceCurrencyCode: string;\n destinationCurrencyCode: string;\n }): Promise<CardProviderOption[]> => {\n const quotes = await getRampQuotes(params);\n return quotes.map(\n (q, i): CardProviderOption => ({\n id: q.serviceProvider,\n name: q.serviceProvider,\n quote: `~ ${q.destinationAmount.toFixed(2)} USDC`,\n fee: `$${q.totalFee.toFixed(2)}`,\n badge: i === 0 ? \"best\" : q.lowKyc ? \"low-kyc\" : undefined,\n }),\n );\n },\n [getRampQuotes],\n );\n\n const handleCreateCardSession = useCallback(\n async (params: {\n serviceProvider: string;\n sourceAmount: string;\n sourceCurrencyCode: string;\n destinationCurrencyCode: string;\n walletAddress: string;\n redirectUrl?: string;\n }) => {\n if (!params.walletAddress) {\n throw new Error(\"Deposit address not available for the selected network\");\n }\n const session = await createRampSession(params);\n return {\n id: session.id,\n widgetUrl: session.widgetUrl,\n serviceProviderWidgetUrl: session.serviceProviderWidgetUrl,\n };\n },\n [createRampSession],\n );\n\n const cardRedirectUrl =\n typeof window !== \"undefined\" ? `${window.location.origin}/profile?tab=activity` : undefined;\n\n return {\n open,\n onOpenChange: handleDepositModalOpenChange,\n pendingCardPurchaseSummary,\n walletFlow: {\n balance: totalBalance ?? 0,\n walletLabel,\n walletBalance,\n isWalletBalanceLoading,\n amount: depositAmount,\n formErrorMessage: walletTransaction ? undefined : (walletTransactionError ?? undefined),\n formErrorTone: walletTransactionErrorTone,\n transactionStatus: walletTransactionStatus,\n transactionErrorMessage: walletTransactionError ?? undefined,\n successSummary: {\n fromWallet: walletLabel,\n gasFee: walletTransactionGasFee,\n },\n },\n onWalletAmountChange: setDepositAmount,\n onWalletMax: useCallback(() => setDepositAmount(String(walletBalance)), [walletBalance]),\n onConfirmWalletDeposit: handleConfirmWalletDeposit,\n onCancelWalletDeposit: handleCancelWalletDeposit,\n onWalletNetworkChange: setWalletModalChainId,\n onWalletTokenChange: setWalletModalTokenSymbol,\n initialWalletChainId: connectedChainId ? String(connectedChainId) : undefined,\n\n connectedWalletKind:\n hasEvmCapability && !hasSolanaCapability\n ? \"evm\"\n : hasSolanaCapability && !hasEvmCapability\n ? \"solana\"\n : undefined,\n sendCryptoConfig: { minDeposit: \"$1\", eta: \"~30s\" },\n onDoneSendCrypto: useCallback(\n () => handleDepositModalOpenChange(false),\n [handleDepositModalOpenChange],\n ),\n cardFlow: {\n amount: cardAmount,\n currency: \"USD\",\n tokenOptions: [{ value: \"USDC\", label: \"USDC\" }],\n selectedToken: \"USDC\",\n selectedNetwork: cardNetwork,\n providers: [],\n purchaseSummary: { amountReceived: \"\", network: \"\", fees: \"\" },\n minAmount: 11,\n },\n onCardAmountChange: setCardAmount,\n onCardNetworkChange: setCardNetwork,\n onDoneCardPurchase: useCallback(() => {\n syncBalancesMutate();\n if (typeof window !== \"undefined\") {\n window.history.replaceState({}, \"\", window.location.pathname);\n }\n }, [syncBalancesMutate]),\n cardRedirectUrl,\n onGetCardQuotes: handleGetCardQuotes,\n onCreateCardSession: handleCreateCardSession,\n };\n}\n"],"mappings":";;;;;;;;;AAMA,SAAgBQ,qBACdC,OACAC,iBACgD;CAChD,MAAMC,UAAUF,iBAAiBI,QAAQJ,MAAME,UAAUG,OAAOL,KAAK;CACrE,MAAMM,QAAQJ,QAAQK,YAAY;CAElC,IACED,MAAME,SAAS,eAAe,KAC9BF,MAAME,SAAS,aAAa,KAC5BF,MAAME,SAAS,sBAAsB,KACrCF,MAAME,SAAS,8BAA8B,GAE7C,OAAO;EAAEN,SAAS;EAA4BC,MAAM;CAAQ;CAM9D,IAFED,QAAQM,SAAS,iCAAiC,KAAKN,QAAQM,SAAS,oBAAoB,GAE3E;EACjB,MAAME,QAAQR,QAAQQ,MAAM,6BAA6B;EACzD,MAAMC,gBAAgBD,QAAQE,OAAOF,MAAM,EAAE,IAAIG,KAAA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341 @@
|
|
|
1
|
+
import "./index-D0fXU85a.mjs";
|
|
2
|
+
import { WithdrawPreviewResponse, WsWithdrawalLifecycleLeg, WsWithdrawalLifecycleStatus } from "@agg-build/sdk";
|
|
3
|
+
//#region src/execution/use-managed-balances.d.ts
|
|
4
|
+
interface UseManagedBalancesOptions {
|
|
5
|
+
enabled?: boolean;
|
|
6
|
+
mode?: "live" | "paper";
|
|
7
|
+
/**
|
|
8
|
+
* `"self"` fetches the balances of the wallets linked to this account rather
|
|
9
|
+
* than the managed wallet. Its own query key, so both can be held at once.
|
|
10
|
+
*/
|
|
11
|
+
custody?: "managed" | "self";
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Query hook for fetching unified managed wallet balances across all chains.
|
|
15
|
+
*/
|
|
16
|
+
declare function useManagedBalances(options?: UseManagedBalancesOptions): {
|
|
17
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
18
|
+
data: import("@agg-build/sdk").UnifiedBalanceResponse;
|
|
19
|
+
error: Error;
|
|
20
|
+
isError: true;
|
|
21
|
+
isPending: false;
|
|
22
|
+
isLoading: false;
|
|
23
|
+
isLoadingError: false;
|
|
24
|
+
isRefetchError: true;
|
|
25
|
+
isSuccess: false;
|
|
26
|
+
isPlaceholderData: false;
|
|
27
|
+
status: "error";
|
|
28
|
+
dataUpdatedAt: number;
|
|
29
|
+
errorUpdatedAt: number;
|
|
30
|
+
failureCount: number;
|
|
31
|
+
failureReason: Error | null;
|
|
32
|
+
errorUpdateCount: number;
|
|
33
|
+
isFetched: boolean;
|
|
34
|
+
isFetchedAfterMount: boolean;
|
|
35
|
+
isFetching: boolean;
|
|
36
|
+
isInitialLoading: boolean;
|
|
37
|
+
isPaused: boolean;
|
|
38
|
+
isRefetching: boolean;
|
|
39
|
+
isStale: boolean;
|
|
40
|
+
isEnabled: boolean;
|
|
41
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
42
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
43
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
44
|
+
} | {
|
|
45
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
46
|
+
data: import("@agg-build/sdk").UnifiedBalanceResponse;
|
|
47
|
+
error: null;
|
|
48
|
+
isError: false;
|
|
49
|
+
isPending: false;
|
|
50
|
+
isLoading: false;
|
|
51
|
+
isLoadingError: false;
|
|
52
|
+
isRefetchError: false;
|
|
53
|
+
isSuccess: true;
|
|
54
|
+
isPlaceholderData: false;
|
|
55
|
+
status: "success";
|
|
56
|
+
dataUpdatedAt: number;
|
|
57
|
+
errorUpdatedAt: number;
|
|
58
|
+
failureCount: number;
|
|
59
|
+
failureReason: Error | null;
|
|
60
|
+
errorUpdateCount: number;
|
|
61
|
+
isFetched: boolean;
|
|
62
|
+
isFetchedAfterMount: boolean;
|
|
63
|
+
isFetching: boolean;
|
|
64
|
+
isInitialLoading: boolean;
|
|
65
|
+
isPaused: boolean;
|
|
66
|
+
isRefetching: boolean;
|
|
67
|
+
isStale: boolean;
|
|
68
|
+
isEnabled: boolean;
|
|
69
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
70
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
71
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
72
|
+
} | {
|
|
73
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
74
|
+
data: undefined;
|
|
75
|
+
error: Error;
|
|
76
|
+
isError: true;
|
|
77
|
+
isPending: false;
|
|
78
|
+
isLoading: false;
|
|
79
|
+
isLoadingError: true;
|
|
80
|
+
isRefetchError: false;
|
|
81
|
+
isSuccess: false;
|
|
82
|
+
isPlaceholderData: false;
|
|
83
|
+
status: "error";
|
|
84
|
+
dataUpdatedAt: number;
|
|
85
|
+
errorUpdatedAt: number;
|
|
86
|
+
failureCount: number;
|
|
87
|
+
failureReason: Error | null;
|
|
88
|
+
errorUpdateCount: number;
|
|
89
|
+
isFetched: boolean;
|
|
90
|
+
isFetchedAfterMount: boolean;
|
|
91
|
+
isFetching: boolean;
|
|
92
|
+
isInitialLoading: boolean;
|
|
93
|
+
isPaused: boolean;
|
|
94
|
+
isRefetching: boolean;
|
|
95
|
+
isStale: boolean;
|
|
96
|
+
isEnabled: boolean;
|
|
97
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
98
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
99
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
100
|
+
} | {
|
|
101
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
102
|
+
data: undefined;
|
|
103
|
+
error: null;
|
|
104
|
+
isError: false;
|
|
105
|
+
isPending: true;
|
|
106
|
+
isLoading: true;
|
|
107
|
+
isLoadingError: false;
|
|
108
|
+
isRefetchError: false;
|
|
109
|
+
isSuccess: false;
|
|
110
|
+
isPlaceholderData: false;
|
|
111
|
+
status: "pending";
|
|
112
|
+
dataUpdatedAt: number;
|
|
113
|
+
errorUpdatedAt: number;
|
|
114
|
+
failureCount: number;
|
|
115
|
+
failureReason: Error | null;
|
|
116
|
+
errorUpdateCount: number;
|
|
117
|
+
isFetched: boolean;
|
|
118
|
+
isFetchedAfterMount: boolean;
|
|
119
|
+
isFetching: boolean;
|
|
120
|
+
isInitialLoading: boolean;
|
|
121
|
+
isPaused: boolean;
|
|
122
|
+
isRefetching: boolean;
|
|
123
|
+
isStale: boolean;
|
|
124
|
+
isEnabled: boolean;
|
|
125
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
126
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
127
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
128
|
+
} | {
|
|
129
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
130
|
+
data: undefined;
|
|
131
|
+
error: null;
|
|
132
|
+
isError: false;
|
|
133
|
+
isPending: true;
|
|
134
|
+
isLoadingError: false;
|
|
135
|
+
isRefetchError: false;
|
|
136
|
+
isSuccess: false;
|
|
137
|
+
isPlaceholderData: false;
|
|
138
|
+
status: "pending";
|
|
139
|
+
dataUpdatedAt: number;
|
|
140
|
+
errorUpdatedAt: number;
|
|
141
|
+
failureCount: number;
|
|
142
|
+
failureReason: Error | null;
|
|
143
|
+
errorUpdateCount: number;
|
|
144
|
+
isFetched: boolean;
|
|
145
|
+
isFetchedAfterMount: boolean;
|
|
146
|
+
isFetching: boolean;
|
|
147
|
+
isLoading: boolean;
|
|
148
|
+
isInitialLoading: boolean;
|
|
149
|
+
isPaused: boolean;
|
|
150
|
+
isRefetching: boolean;
|
|
151
|
+
isStale: boolean;
|
|
152
|
+
isEnabled: boolean;
|
|
153
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
154
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
155
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
156
|
+
} | {
|
|
157
|
+
balances: import("@agg-build/sdk").UnifiedBalanceResponse | undefined;
|
|
158
|
+
data: import("@agg-build/sdk").UnifiedBalanceResponse;
|
|
159
|
+
isError: false;
|
|
160
|
+
error: null;
|
|
161
|
+
isPending: false;
|
|
162
|
+
isLoading: false;
|
|
163
|
+
isLoadingError: false;
|
|
164
|
+
isRefetchError: false;
|
|
165
|
+
isSuccess: true;
|
|
166
|
+
isPlaceholderData: true;
|
|
167
|
+
status: "success";
|
|
168
|
+
dataUpdatedAt: number;
|
|
169
|
+
errorUpdatedAt: number;
|
|
170
|
+
failureCount: number;
|
|
171
|
+
failureReason: Error | null;
|
|
172
|
+
errorUpdateCount: number;
|
|
173
|
+
isFetched: boolean;
|
|
174
|
+
isFetchedAfterMount: boolean;
|
|
175
|
+
isFetching: boolean;
|
|
176
|
+
isInitialLoading: boolean;
|
|
177
|
+
isPaused: boolean;
|
|
178
|
+
isRefetching: boolean;
|
|
179
|
+
isStale: boolean;
|
|
180
|
+
isEnabled: boolean;
|
|
181
|
+
refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<import("@agg-build/sdk").UnifiedBalanceResponse, Error>>;
|
|
182
|
+
fetchStatus: import("@tanstack/react-query").FetchStatus;
|
|
183
|
+
promise: Promise<import("@agg-build/sdk").UnifiedBalanceResponse>;
|
|
184
|
+
};
|
|
185
|
+
//#endregion
|
|
186
|
+
//#region src/withdraw/use-withdraw-flow.d.ts
|
|
187
|
+
type WithdrawSelectOption = {
|
|
188
|
+
value: string;
|
|
189
|
+
label: string;
|
|
190
|
+
disabled?: boolean;
|
|
191
|
+
};
|
|
192
|
+
type WithdrawSummary = {
|
|
193
|
+
/**
|
|
194
|
+
* The amount the user submitted for withdrawal — NOT a confirmed payout
|
|
195
|
+
* figure. A preflight quote can still fail or settle partially later, so
|
|
196
|
+
* labeling this "received" was misleading.
|
|
197
|
+
*/
|
|
198
|
+
amountReceived: string;
|
|
199
|
+
network: string;
|
|
200
|
+
toWallet: string;
|
|
201
|
+
fees: string;
|
|
202
|
+
};
|
|
203
|
+
interface UseWithdrawFlowResult {
|
|
204
|
+
open: boolean;
|
|
205
|
+
onOpenChange: (open: boolean) => void;
|
|
206
|
+
withdrawFlow: {
|
|
207
|
+
balance: number;
|
|
208
|
+
balanceDisplay: string;
|
|
209
|
+
amount: string;
|
|
210
|
+
destinationWallet: string;
|
|
211
|
+
tokenOptions: WithdrawSelectOption[];
|
|
212
|
+
networkOptions: WithdrawSelectOption[];
|
|
213
|
+
selectedToken: string;
|
|
214
|
+
selectedNetwork: string;
|
|
215
|
+
purchaseSummary: WithdrawSummary;
|
|
216
|
+
/**
|
|
217
|
+
* The id returned by `POST /execution/withdraw-managed` once the user
|
|
218
|
+
* has submitted the flow — used by the success step to subscribe to
|
|
219
|
+
* `withdrawal_lifecycle` WS events. `null` until submission succeeds
|
|
220
|
+
* and reset to `null` when the modal closes.
|
|
221
|
+
*/
|
|
222
|
+
withdrawalId: string | null;
|
|
223
|
+
/**
|
|
224
|
+
* True when the user clicked Max — the backend should apply its own cap
|
|
225
|
+
* rather than rejecting an over-balance request. Reset to false when the
|
|
226
|
+
* user manually edits the amount field afterward.
|
|
227
|
+
*/
|
|
228
|
+
isMax: boolean;
|
|
229
|
+
};
|
|
230
|
+
onWithdrawDestinationChange: (address: string) => void;
|
|
231
|
+
onWithdrawAmountChange: (amount: string) => void;
|
|
232
|
+
onWithdrawTokenChange: (token: string) => void;
|
|
233
|
+
onWithdrawNetworkChange: (network: string) => void;
|
|
234
|
+
onMaxClick: () => void;
|
|
235
|
+
onSelectWithdrawProvider: (providerId: string) => Promise<void>;
|
|
236
|
+
onDoneWithdraw: () => void;
|
|
237
|
+
}
|
|
238
|
+
interface UseWithdrawFlowOptions {
|
|
239
|
+
open: boolean;
|
|
240
|
+
onOpenChange: (open: boolean) => void;
|
|
241
|
+
}
|
|
242
|
+
declare function useWithdrawFlow(options: UseWithdrawFlowOptions): UseWithdrawFlowResult;
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/withdraw/use-withdraw-estimate.d.ts
|
|
245
|
+
interface WithdrawFeeEstimate {
|
|
246
|
+
estimatedFees: string;
|
|
247
|
+
networkReserve: string;
|
|
248
|
+
youReceive: string;
|
|
249
|
+
}
|
|
250
|
+
interface UseWithdrawEstimateParams {
|
|
251
|
+
amount: string;
|
|
252
|
+
selectedToken: string;
|
|
253
|
+
selectedNetwork: string;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Natively estimates withdrawal fees, network reserves, and the expected net
|
|
257
|
+
* amount to be received based on the selected token, destination network,
|
|
258
|
+
* and transfer amount.
|
|
259
|
+
*/
|
|
260
|
+
declare function useWithdrawEstimate({ amount, selectedToken, selectedNetwork }: UseWithdrawEstimateParams): WithdrawFeeEstimate | null;
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/withdraw/use-withdrawal-lifecycle.d.ts
|
|
263
|
+
/**
|
|
264
|
+
* Latest lifecycle snapshot for a single withdrawal, materialized from the
|
|
265
|
+
* most recent `WsWithdrawalLifecycleEvent` whose `withdrawalId` matches.
|
|
266
|
+
*
|
|
267
|
+
* The wire format is intentionally additive (legs may arrive partial), so
|
|
268
|
+
* `legs` reflects the latest snapshot the server emitted — earlier per-leg
|
|
269
|
+
* deltas are not re-merged on the client. Consumers should treat `legs` as
|
|
270
|
+
* "last known truth" rather than a derived rollup.
|
|
271
|
+
*/
|
|
272
|
+
interface WithdrawalLifecycleState {
|
|
273
|
+
/** True until the first lifecycle event for this withdrawal arrives. */
|
|
274
|
+
pending: boolean;
|
|
275
|
+
/** Top-level status, or `null` until the first event arrives. */
|
|
276
|
+
status: WsWithdrawalLifecycleStatus | null;
|
|
277
|
+
/** Requested withdrawal amount in destination-token native decimals. */
|
|
278
|
+
requestedAmountRaw: string | null;
|
|
279
|
+
/** Terminal settled amount in destination-token native decimals. */
|
|
280
|
+
completedAmountRaw: string | null;
|
|
281
|
+
/** Realized platform fee in destination-token native decimals. Only present on terminal events; null until then. */
|
|
282
|
+
feeRaw: string | null;
|
|
283
|
+
/** Whether `status` is a terminal state (`completed` / `partial` / `failed`). */
|
|
284
|
+
terminal: boolean;
|
|
285
|
+
/** Last leg delta (the leg whose flip triggered the most recent event). */
|
|
286
|
+
lastLeg: WsWithdrawalLifecycleLeg | null;
|
|
287
|
+
/** All legs at the moment of the most recent event (server snapshot). */
|
|
288
|
+
legs: WsWithdrawalLifecycleLeg[];
|
|
289
|
+
/** Failure reason for terminal `failed` / `partial`. */
|
|
290
|
+
errorMessage: string | null;
|
|
291
|
+
/** Server timestamp (ms) of the most recent event. */
|
|
292
|
+
timestamp: number | null;
|
|
293
|
+
}
|
|
294
|
+
interface UseWithdrawalLifecycleResult {
|
|
295
|
+
/** Latest lifecycle snapshot for the watched `withdrawalId`. */
|
|
296
|
+
state: WithdrawalLifecycleState;
|
|
297
|
+
/** Reset to the initial pre-event state — call when the modal is closed or a new flow starts. */
|
|
298
|
+
reset: () => void;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Subscribes to `withdrawal_lifecycle` WS events for a single `withdrawalId`
|
|
302
|
+
* and exposes the latest snapshot. Returns a stable `pending` initial state
|
|
303
|
+
* until the first matching event arrives.
|
|
304
|
+
*
|
|
305
|
+
* Pass `null` for `withdrawalId` to disable the subscription (e.g. before
|
|
306
|
+
* the user has submitted a withdrawal). Switching the `withdrawalId` resets
|
|
307
|
+
* the state so a stale snapshot from a prior withdrawal can never bleed
|
|
308
|
+
* across.
|
|
309
|
+
*
|
|
310
|
+
* **Backfill behavior**: on mount with a non-null `withdrawalId`, and again
|
|
311
|
+
* whenever the WS connection re-opens, the hook calls
|
|
312
|
+
* `GET /execution/withdrawals/:id` to recover any lifecycle events that fired
|
|
313
|
+
* before the listener was attached or while the socket was disconnected. WS
|
|
314
|
+
* events always win over REST snapshots (REST stamps as `timestamp: 0`), so a
|
|
315
|
+
* race between the two never regresses to a stale state.
|
|
316
|
+
*/
|
|
317
|
+
declare function useWithdrawalLifecycle(withdrawalId: string | null): UseWithdrawalLifecycleResult;
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/withdraw/use-withdraw-preview.d.ts
|
|
320
|
+
interface UseWithdrawPreviewParams {
|
|
321
|
+
amountRaw: string | null;
|
|
322
|
+
tokenSymbol: string | null;
|
|
323
|
+
destinationChainId: number | null;
|
|
324
|
+
destinationAddress: string | null;
|
|
325
|
+
/**
|
|
326
|
+
* When `true`, the backend caps the withdrawal to the maximum deliverable amount.
|
|
327
|
+
* Included in the query key so max vs non-max are distinct cache entries.
|
|
328
|
+
*/
|
|
329
|
+
max?: boolean;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Live withdrawal preview backed by the API (`POST /execution/withdraw/preview`).
|
|
333
|
+
* Disabled until amount/token/chain/address are present and amount is non-zero.
|
|
334
|
+
* The backend caches identical previews for 15s; FE debounce keeps Relay calls
|
|
335
|
+
* bounded. Returns the real fee + receive amount, replacing the hardcoded
|
|
336
|
+
* `useWithdrawEstimate`.
|
|
337
|
+
*/
|
|
338
|
+
declare function useWithdrawPreview({ amountRaw, tokenSymbol, destinationChainId, destinationAddress, max }: UseWithdrawPreviewParams): import("@tanstack/react-query").UseQueryResult<WithdrawPreviewResponse, Error>;
|
|
339
|
+
//#endregion
|
|
340
|
+
export { useWithdrawalLifecycle as a, useWithdrawEstimate as c, useWithdrawFlow as d, UseManagedBalancesOptions as f, WithdrawalLifecycleState as i, UseWithdrawFlowOptions as l, useWithdrawPreview as n, UseWithdrawEstimateParams as o, useManagedBalances as p, UseWithdrawalLifecycleResult as r, WithdrawFeeEstimate as s, UseWithdrawPreviewParams as t, UseWithdrawFlowResult as u };
|
|
341
|
+
//# sourceMappingURL=index-CbNR3EIA.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-CbNR3EIA.d.mts","names":[],"sources":["../src/execution/use-managed-balances.ts","../src/withdraw/use-withdraw-flow.ts","../src/withdraw/use-withdraw-estimate.ts","../src/withdraw/use-withdrawal-lifecycle.ts","../src/withdraw/use-withdraw-preview.ts"],"mappings":";;;UAIiB;EACf;EACA;;;;;EAKA;;;;;iBAMc,mBAAmB,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KCNxC;EAAyB;EAAe;EAAe;;KAKvD;;;;;;EAMH;EACA;EACA;EACA;;UAkDe;EACf;EACA,eAAe;EACf;IACE;IACA;IACA;IACA;IACA,cAAc;IACd,gBAAgB;IAChB;IACA;IACA,iBAAiB;;;;;;;IAOjB;;;;;;IAMA;;EAEF,8BAA8B;EAC9B,yBAAyB;EACzB,wBAAwB;EACxB,0BAA0B;EAC1B;EACA,2BAA2B,uBAAuB;EAClD;;UAGe;EACf;EACA,eAAe;;iBAoDD,gBAAgB,SAAS,yBAAyB;;;UCnKjD;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;;;;;;;iBAQc,sBACd,QACA,eACA,mBACC,4BAA4B;;;;;;;;;;;;UCGd;;EAEf;;EAEA,QAAQ;;EAER;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;EAET,MAAM;;EAEN;;EAEA;;UA4Fe;;EAEf,OAAO;;EAEP;;;;;;;;;;;;;;;;;;;iBAoBc,uBAAuB,8BAA8B;;;UC9JpD;EACf;EACA;EACA;EACA;;;;;EAKA;;;;;;;;;iBAUc,qBACd,WACA,aACA,oBACA,oBACA,OACC,2DAAwB,eAAA,yBAAA"}
|