Connect Wallet | Wagmi (2024)

The ability for a user to connect their wallet is a core function for any Dapp. It allows users to perform tasks such as: writing to contracts, signing messages, or sending transactions.

Wagmi contains everything you need to get started with building a Connect Wallet module. To get started, you can either use a third-party library or build your own.

Third-party Libraries

You can use a pre-built Connect Wallet module from a third-party library such as:

The above libraries are all built on top of Wagmi, handle all the edge cases around wallet connection, and provide a seamless Connect Wallet UX that you can use in your Dapp.

Build Your Own

Wagmi provides you with the Hooks to get started building your own Connect Wallet module.

It takes less than five minutes to get up and running with Browser Wallets, WalletConnect, and Coinbase Wallet.

1. Configure Wagmi

Before we get started with building the functionality of the Connect Wallet module, we will need to set up the Wagmi configuration.

Let's create a config.ts file and export a config object.

tsx

import { http, createConfig } from 'wagmi'import { base, mainnet, optimism } from 'wagmi/chains'import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors'const projectId = '<WALLETCONNECT_PROJECT_ID>'export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), },})

In the above configuration, we want to set up connectors for Injected (browser), WalletConnect (browser + mobile), MetaMask, and Safe wallets. This configuration uses the Mainnet and Base chains, but you can use whatever you want.

WARNING

Make sure to replace the projectId with your own WalletConnect Project ID, if you wish to use WalletConnect!

Get your Project ID

2. Wrap App in Context Provider

Next, we will need to wrap our React App with Context so that our application is aware of Wagmi & React Query's reactive state and in-memory caching.

tsx

 // 1. Import modulesimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { WagmiProvider } from 'wagmi'import { config } from './config'// 2. Set up a React Query client.const queryClient = new QueryClient()function App() { // 3. Wrap app with Wagmi and React Query context. return ( <WagmiProvider config={config}> <QueryClientProvider client={queryClient}>  {/** ... */}  </QueryClientProvider>  </WagmiProvider> )}

tsx

import { http, createConfig } from 'wagmi'import { base, mainnet, optimism } from 'wagmi/chains'import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors'const projectId = '<WALLETCONNECT_PROJECT_ID>'export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), },})

3. Display Wallet Options

After that, we will create a WalletOptions component that will display our connectors. This will allow users to select a wallet and connect.

Below, we are rendering a list of connectors retrieved from useConnect. When the user clicks on a connector, the connect function will connect the users' wallet.

tsx

import * as React from 'react'import { Connector, useConnect } from 'wagmi'export function WalletOptions() { const { connectors, connect } = useConnect() return connectors.map((connector) => ( <button key={connector.uid} onClick={() => connect({ connector })}> {connector.name} </button> ))}

tsx

 // 1. Import modulesimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { WagmiProvider } from 'wagmi'import { config } from './config'// 2. Set up a React Query client.const queryClient = new QueryClient()function App() { // 3. Wrap app with Wagmi and React Query context. return ( <WagmiProvider config={config}> <QueryClientProvider client={queryClient}>  {/* ... */} </QueryClientProvider>  </WagmiProvider> )}

tsx

import { http, createConfig } from 'wagmi'import { base, mainnet, optimism } from 'wagmi/chains'import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors'const projectId = '<WALLETCONNECT_PROJECT_ID>'export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), },})

4. Display Connected Account

Lastly, if an account is connected, we want to show some basic information, like the connected address and ENS name and avatar.

Below, we are using hooks like useAccount, useEnsAvatar and useEnsName to extract this information.

We are also utilizing useDisconnect to show a "Disconnect" button so a user can disconnect their wallet.

tsx

import { useAccount, useDisconnect, useEnsAvatar, useEnsName } from 'wagmi'export function Account() { const { address } = useAccount() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName! }) return ( <div> {ensAvatar && <img alt="ENS Avatar" src={ensAvatar} />} {address && <div>{ensName ? `${ensName} (${address})` : address}</div>} <button onClick={() => disconnect()}>Disconnect</button> </div> )}

tsx

import * as React from 'react'import { Connector, useConnect } from 'wagmi'export function WalletOptions() { const { connectors, connect } = useConnect() return connectors.map((connector) => ( <WalletOption key={connector.uid} connector={connector} onClick={() => connect({ connector })} /> ))}function WalletOption({ connector, onClick,}: { connector: Connector onClick: () => void}) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( <button disabled={!ready} onClick={onClick}> {connector.name} </button> )}

tsx

 // 1. Import modulesimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { WagmiProvider } from 'wagmi'import { config } from './config'// 2. Set up a React Query client.const queryClient = new QueryClient()function App() { // 3. Wrap app with Wagmi and React Query context. return ( <WagmiProvider config={config}> <QueryClientProvider client={queryClient}>  {/* ... */} </QueryClientProvider>  </WagmiProvider> )}

tsx

import { http, createConfig } from 'wagmi'import { base, mainnet, optimism } from 'wagmi/chains'import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors'const projectId = '<WALLETCONNECT_PROJECT_ID>'export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), },})

5. Wire it up!

Finally, we can wire up our Wallet Options and Account components to our application's entrypoint.

tsx

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { WagmiProvider, useAccount } from 'wagmi'import { config } from './config'import { Account } from './account'import { WalletOptions } from './wallet-options'const queryClient = new QueryClient()function ConnectWallet() { const { isConnected } = useAccount() if (isConnected) return <Account /> return <WalletOptions />}function App() { return ( <WagmiProvider config={config}> <QueryClientProvider client={queryClient}>  <ConnectWallet /> </QueryClientProvider>  </WagmiProvider> )}

tsx

import { useAccount, useDisconnect, useEnsAvatar, useEnsName } from 'wagmi'export function Account() { const { address } = useAccount() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName! }) return ( <div> {ensAvatar && <img alt="ENS Avatar" src={ensAvatar} />} {address && <div>{ensName ? `${ensName} (${address})` : address}</div>} <button onClick={() => disconnect()}>Disconnect</button> </div> )}

tsx

import * as React from 'react'import { Connector, useConnect } from 'wagmi'export function WalletOptions() { const { connectors, connect } = useConnect() return connectors.map((connector) => ( <WalletOption key={connector.uid} connector={connector} onClick={() => connect({ connector })} /> ))}function WalletOption({ connector, onClick,}: { connector: Connector onClick: () => void}) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( <button disabled={!ready} onClick={onClick}> {connector.name} </button> )}

tsx

import { http, createConfig } from 'wagmi'import { base, mainnet, optimism } from 'wagmi/chains'import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors'const projectId = '<WALLETCONNECT_PROJECT_ID>'export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), },})

Playground

Want to see the above steps all wired up together in an end-to-end example? Check out the below StackBlitz playground.


Connect Wallet | Wagmi (2024)

FAQs

Why won't my wallet connect connect? ›

Tap on Browser, then choose Clear Browser Cache. - Clear all previous WalletConnect connections. For this, go to Settings, then select WalletConnect, choose the relevant DApp, and press Disconnect. After these steps, close the app and reopen it.

How do I connect my wallet to wallet connect? ›

How to use WalletConnect
  1. 1: Open a web app. Open your browser and go to the website of the application that you want to use. ...
  2. 2: Choose WalletConnect. ...
  3. 3: QR code. ...
  4. 4: Open WalletConnect in your mobile wallet. ...
  5. 5: Approve the request. ...
  6. 6: You're connected! ...
  7. 1: Open a web app. ...
  8. 2: Choose WalletConnect.
Sep 29, 2020

What does it mean to connect a wallet? ›

Connect Wallet ​ The ability for a user to connect their wallet is a core function for any Dapp. It allows users to perform tasks such as: writing to contracts, signing messages, or sending transactions. Wagmi contains everything you need to get started with building a Connect Wallet module.

Is wallet Connect trustworthy? ›

It's safe in the sense that it establishes a secure (encrypted) connection, with your approval, between your Bitcoin.com Wallet and the DApps of your choosing.

How do I reset WalletConnect? ›

Resetting WalletConnect Sessions

Whenever you experience a WalletConnect problem, we recommend disconnecting all active WalletConnect sessions. You can easily do this by navigating to Settings > WalletConnect Sessions > Disconnect All Sessions.

Why won t my Apple Wallet connect? ›

Update to the latest version of iOS, watchOS, macOS, or visionOS. Confirm that you have Face ID, Touch ID, Optic ID, or a passcode set on your device. Make sure that you are in a supported country or region. Check that your device is compatible with Apple Pay.

How do I activate my wallet on my phone? ›

4. Set up your Wallet
  1. From the Play Store, download the Google Wallet app.
  2. Open the Google Wallet app .
  3. Follow the setup instructions. If you're new to Google Wallet, you're asked to add a card the first time you open the app. You can use your camera to scan a debit or credit card or enter the details manually.

How do I pair my wallet with my iPhone? ›

Connect your account to Wallet

Go to the Wallet app on your iPhone. Tap the card you want to connect. Tap Get Started, then follow the onscreen instructions to connect your account.

Which wallets are compatible with Wallet Connect? ›

A quick check at the WalletConnect compatible wallets
  • MetaMask.
  • Trust wallet.
  • Binance DEX.
  • Uniswap.
  • Rainbow.
  • Etherscan.
  • OpenSea.

Is wallet connect free? ›

WalletConnect's free to use builder kits — AppKit and WalletKit — are designed to give projects everything they need to create great web3 products while working harmoniously with the WalletConnect protocol to give users unbeatable experiences from start to finish.

How do I sync my wallet to my iPhone? ›

To set up eWallet's iCloud sync on your primary iPhone or iPad
  1. Go to your device's Settings App → iCloud and make sure: ...
  2. Open eWallet on your iPhone or iPad, but do not enter the password yet (you may need to tap the Wallets button.
  3. Tap the cloud icon.
  4. Select your wallet under CLOUD STORAGE SERVICE and then select iCloud.
May 8, 2023

Is connecting wallet to website safe? ›

Also in general connecting your wallet to any website isn't a big security risk, but it's simply better to not connect unless you have a need for it. Metamask strongly recommends that you only connect with websites that you trust.

Does wallet connect charge fees? ›

Transaction Fee: WalletConnect charges a 0.85% transaction fee on all swaps. Supported Tokens: The tokens available for swapping are limited to those supported by 1Inch. Note that the availability of tokens may vary depending on the network.

Who owns wallet connect? ›

Who is the founder of WalletConnect? Pedro Gomes is the founder of WalletConnect.

How do I contact wallet connect? ›

Have a question but can't find an answer in our FAQ? Please send an email to [email protected] with your question.

Why isn t my wallet app working on iPhone? ›

Sign out of Apple ID, force restart, sign back in. Force restart app. Remove cards and re add (now cannot re add cards, but can open app) Reselect region in settings.

Could not get a wallet connection.? ›

Check for interference from security software or extensions

Sometimes, security software, adblockers, or other extensions can interfere with the connection between your wallet and browser. Try disabling or temporarily removing these programs/extensions and check if the connection issue is resolved.

Top Articles
Why Mutual Funds are a great investment option for beginners
Experts weigh in to help you figure out how much car you can afford
Devin Mansen Obituary
Unit 30 Quiz: Idioms And Pronunciation
Pnct Terminal Camera
Mountain Dew Bennington Pontoon
Access-A-Ride – ACCESS NYC
Toyota Campers For Sale Craigslist
Nfr Daysheet
Southside Grill Schuylkill Haven Pa
Black Gelato Strain Allbud
A Complete Guide To Major Scales
How to Type German letters ä, ö, ü and the ß on your Keyboard
Irving Hac
Little Rock Arkansas Craigslist
Amelia Bissoon Wedding
Classroom 6x: A Game Changer In The Educational Landscape
Flower Mound Clavicle Trauma
Huge Boobs Images
Five Day National Weather Forecast
Lesson 8 Skills Practice Solve Two-Step Inequalities Answer Key
Hanger Clinic/Billpay
Bank Of America Financial Center Irvington Photos
Lowe's Garden Fence Roll
라이키 유출
Amortization Calculator
Buying Cars from Craigslist: Tips for a Safe and Smart Purchase
Bocca Richboro
Myql Loan Login
Violent Night Showtimes Near Amc Dine-In Menlo Park 12
Cable Cove Whale Watching
Osrs Important Letter
Advance Auto Parts Stock Price | AAP Stock Quote, News, and History | Markets Insider
Life Insurance Policies | New York Life
The Venus Flytrap: A Complete Care Guide
Jay Gould co*ck
About Us | SEIL
Troy Gamefarm Prices
Toth Boer Goats
Winco Money Order Hours
Sunrise Garden Beach Resort - Select Hurghada günstig buchen | billareisen.at
Busted Newspaper Campbell County KY Arrests
More News, Rumors and Opinions Tuesday PM 7-9-2024 — Dinar Recaps
Amc.santa Anita
How Much Is 10000 Nickels
Www Craigslist Com Atlanta Ga
Is Ameriprise A Pyramid Scheme
Bekkenpijn: oorzaken en symptomen van pijn in het bekken
Fluffy Jacket Walmart
Big Brother 23: Wiki, Vote, Cast, Release Date, Contestants, Winner, Elimination
Besoldungstabellen | Niedersächsisches Landesamt für Bezüge und Versorgung (NLBV)
Koniec veľkorysých plánov. Prestížna LEAF Academy mení adresu, masívny kampus nepostaví
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 6624

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.