โ†
Previous Module
Role-based DAO Permissions

๐Ÿ”— Connection Flow: QR Code โ†’ Session

Understand how WalletConnect establishes encrypted sessions

Integrate Web3 wallets into your dApp

๐Ÿ”„ Connection Flow & State Management

Managing connection state is critical for good UX. Your dApp must handle: wallet detection, permission requests, user rejection, account switching, network changes, and disconnection. Users expect seamless transitionsโ€”"Connect" button becomes "Connected: 0x742d..." with dropdown for disconnect/switch account. Let's build a realistic wallet selector.

๐ŸŽฎ Interactive: Multi-Wallet Connection Simulator

Try connecting different wallets, switch networks, and see state changes in real-time. Experience what users see when using your dApp.

Select a Wallet

๐ŸŽฏ Connection State Management

State 1: Disconnected

Show "Connect Wallet" button. Detect available wallets (window.ethereum, WalletConnect). List options for user to choose.

Code: const [account, setAccount] = useState<string | null>(null)

State 2: Connecting

Show loading spinner. Call ethereum.request({ method: 'eth_requestAccounts' }). Handle rejection (user clicks "Cancel").

Code: setConnecting(true); await provider.send('eth_requestAccounts', [])

State 3: Connected

Display truncated address (0x742d...0bEb). Show network badge. Add dropdown: switch account, disconnect. Listen for accountsChanged event.

Code: ethereum.on('accountsChanged', handleAccountsChanged)

State 4: Network Switching

User clicks "Switch to Polygon". Call wallet_switchEthereumChain. If chain not added, call wallet_addEthereumChain. Update UI.

Code: ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x89' }] })

โš ๏ธ Error Handling

User Rejects Connection

Catch error code 4001. Show friendly message: "Connection cancelled. Click 'Connect Wallet' to try again." Don't spam connection requests.

Wallet Not Installed

Check if (!window.ethereum). Show install prompt: "Install MetaMask" button linking to chrome.google.com/webstore. Or offer WalletConnect as alternative.

Wrong Network

Detect chainId. If not your expected network (e.g., user on Polygon, you need Mainnet), show banner: "Please switch to Ethereum Mainnet" with button to trigger wallet_switchEthereumChain.

๐Ÿ’ก Key Insight

Good wallet connection UX is 90% state management, 10% blockchain calls. Users don't care about ethereum.request() internalsโ€”they care about clear feedback: "Connecting...", "Connected: 0x742d...", "Switch to Polygon". Handle every edge case: rejection, wallet not found, wrong network, disconnection, account switching. Popular dApps (Uniswap, Aave) use libraries like RainbowKit, ConnectKit, or web3modal that handle all this complexity. Don't build from scratchโ€”use proven components. Your users will thank you.

โ† Introduction