Wallet Connection in Mini Apps (wagmi)
We assume you are familiar with what a Farcaster Mini App is. Additionally this guide assumes you are familiar with wagmi.sh. In case you are not learn how to build onchain Mini Apps and do transactions.
Enable Wallet Connections to your web application from Farcaster Mini Apps
-
Install the
@farcaster/frame-wagmi-connector
package.bun add @farcaster/frame-wagmi-connector
npm install @farcaster/frame-wagmi-connector
pnpm install @farcaster/frame-wagmi-connector
yarn add @farcaster/frame-wagmi-connector
-
Add the connector to your website
If you already have an app built with wagmi, then you can add the connector directly:
import { farcasterFrame } from "@farcaster/frame-wagmi-connector";// other importsexport const wagmiConfig = createConfig({// your wagmi configconnectors: [farcasterFrame(),// your other connectors...],// rest of your wagmi config});If not you will want to walk through the wagmi setup guide and then add the farcasterFrame Wagmi connector for your Mini App to have connected wallets.
-
Use your wagmi config
With the Farcaster Mini App connector available you can now use the wagmi config in your Mini APp.
This is no different then any other wagmi application. For references to how one can build such Mini Apps or wagmi apps please check the wagmi docs and more Farcaster Mini App docs available here.
To learn about testing your Farcaster Mini App with connected wallet refer to the Farcaster Mini App Testing Guide.
More detailed steps can be found in the Mini App + Webapp Wallet connect tutorial.
Bonus: Make sure you are on the right chain in your Mini App transactions
You may face issues where the chain you expect it to be is not the one the users wallet is. Using the chainId we can detect the current chain and switch to the one we need.
Wagmi with the useChainId
and useSwitchChain
hooks provides a way to switch chains and monitor everything we need.
In a react based project the following effect does the trick:
import { useChainId, useSwitchChain } from "wagmi";import { base } from "wagmi/chains";
// your function / componentexport default function YourComponent() {const chainId = useChainId();const { switchChainAsync } = useSwitchChain();
useEffect(() => { const switchToBase = async () => { if (chainId !== base.id) { try { await switchChainAsync({ chainId: base.id }); } catch (error) { console.error("Failed to switch to Base:", error); } } }; switchToBase();}, [chainId, switchChainAsync]); return ( // some JSX )}