|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect, useRef } from "react"; |
| 4 | +import { ModuleType } from "@creit.tech/stellar-wallets-kit/types"; |
| 5 | +import { getStellarWalletKit } from "@/lib/helpers/stellar/wallet"; |
| 6 | +import { useStellarWalletStore } from "@/stores/stellarWalletStore"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Silently auto-connects when the dApp is opened inside a wallet's in-app |
| 10 | + * browser (e.g. Lobstr, xBull mobile). The wallet module's `isPlatformWrapper` |
| 11 | + * flag tells the kit it is wrapping the page, so we can skip the modal. |
| 12 | + * |
| 13 | + * Bridge wallets (WalletConnect) are explicitly excluded: their `getAddress()` |
| 14 | + * triggers a QR-code / pairing flow when no session exists, which would pop up |
| 15 | + * uninvited. Only HOT_WALLET modules (Lobstr, xBull, Freighter in-app browsers) |
| 16 | + * can be safely auto-connected. |
| 17 | + * |
| 18 | + * Runs once on mount. No-ops if the user is already connected or no |
| 19 | + * platform-wrapper wallet is detected. |
| 20 | + */ |
| 21 | +export function WalletAutoConnect() { |
| 22 | + const { address, setWallet } = useStellarWalletStore(); |
| 23 | + const attempted = useRef(false); |
| 24 | + |
| 25 | + useEffect(() => { |
| 26 | + if (address || attempted.current) return; |
| 27 | + attempted.current = true; |
| 28 | + |
| 29 | + void (async () => { |
| 30 | + try { |
| 31 | + const Kit = await getStellarWalletKit(); |
| 32 | + const wallets = await Kit.refreshSupportedWallets(); |
| 33 | + const platformWallet = wallets.find( |
| 34 | + (w) => |
| 35 | + w.isPlatformWrapper && |
| 36 | + w.isAvailable && |
| 37 | + w.type !== ModuleType.BRIDGE_WALLET |
| 38 | + ); |
| 39 | + if (!platformWallet) return; |
| 40 | + Kit.setWallet(platformWallet.id); |
| 41 | + const { address: walletAddress } = await Kit.fetchAddress(); |
| 42 | + if (walletAddress) { |
| 43 | + setWallet({ |
| 44 | + address: walletAddress, |
| 45 | + walletName: platformWallet.name, |
| 46 | + }); |
| 47 | + } |
| 48 | + } catch { |
| 49 | + // Silently fail — user can always connect manually via the button. |
| 50 | + } |
| 51 | + })(); |
| 52 | + }, [address, setWallet]); |
| 53 | + |
| 54 | + return null; |
| 55 | +} |
0 commit comments