---
description: Web3 frontend integration—Wagmi, Viem, wallet connection (ConnectKit/RainbowKit). Config, providers, read/write contracts, tx states, error handling.
alwaysApply: false
---

# Web3 Frontend Integration

Guidelines for secure, usable Web3 frontends.

## Stack

- **Viem**: Type-safe RPC and contract calls; use for low-level and chain config.
- **Wagmi**: React hooks (useReadContract, useWriteContract, useAccount, useChainId); integrates with React Query for caching.
- **Wallet connection**: ConnectKit or RainbowKit for connection UI and network switching.
- **Types**: Generate from ABIs (e.g. wagmi cli) so contract calls are typed.

## Config

- **Chains**: Mainnet, L2s, testnets as needed; separate RPC URLs per chain (env vars).
- **Connectors**: Injected (MetaMask etc.), WalletConnect, Coinbase; set projectId for WalletConnect.
- **Transports**: `http()` per chain; optional fallback or custom RPC.

## Providers

- Wrap app with WagmiProvider (config), QueryClientProvider, and ConnectKit/RainbowKit provider so hooks and connection UI work.

## Read vs Write

- **Read**: useReadContract (or useContractRead) for view functions; cached and reactive.
- **Write**: useWriteContract + useWaitForTransactionReceipt; handle pending, confirming, success, and failure. Show clear UI state (e.g. “Confirm in wallet”, “Confirming…”, “Done” / “Failed”).

## Error Handling

- **Parse revert**: Use ContractFunctionRevertedError (viem) to get custom error name; map to user-facing message (e.g. InsufficientBalance, SlippageExceeded).
- **Network/wallet**: Handle disconnect, wrong network, rejection; prompt switch network or retry.

## Definition of Done (Web3 Frontend)

- [ ] Wallet connect and network switch work; multiple wallets supported.
- [ ] All tx states (idle, pending, confirming, success, failed) reflected in UI.
- [ ] Contract errors parsed and shown clearly; no raw revert data only.

## Common Pitfalls

- **No slippage/deadline** - Use minAmountOut and deadline in swaps; inform user.
- **Ignoring tx state** - Show loading and success/failure; don’t assume instant confirm.
- **Single chain only** - Support chain switch and correct RPC per chain.
