Guides
DocumentationLog In

Integrating with Wagmi

This tutorial is a step-by-step guide on how to integrate multiple wallets such as Coinbase Wallet, Metamask, and Wallet Connect into your dapp using the wagmi library.

To explore a running version of the finished product, fork our CodeSandbox.

Image 1: Example of a custom modal built with wagmi

This guide assumes you have a React application already setup and running. If you are more comfortable jumping straight into code, below is the final working example of a multi-wallet modal integration. We encourage you to fork the sandbox and reconfigure it to suit the needs of your dapp setup.

Embed: wagmi demo

Prerequisites

Setup Wagmi and Wallet Connectors

Step 1: Install ethers and wagmi

Install ethers.js as a required dependency for wagmi.

yarn add ethers
yarn add wagmi

Step 2: Import and Instantiate Wallet Connectors

In your index.js file, instantiate the connectors to integrate into your dapp. Here we setup connectors for Coinbase Wallet, WalletConnect, and Metamask.

Each connector has its own set of required parameters to pass in, such as a fallback JSON RPC URL or the chains to support.

import { configureChains, defaultChains } from "wagmi";

import { infuraProvider } from "wagmi/providers/infura";
import { publicProvider } from "wagmi/providers/public";

import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { WalletConnectConnector } from "wagmi/connectors/walletConnect";

// API key for Ethereum node
// Two popular services are Infura (infura.io) and Alchemy (alchemy.com)
const infuraId = process.env.INFURA_ID;

// Configure chains for connectors to support
const { chains } = configureChains(defaultChains, [
  infuraProvider({ infuraId }),
  publicProvider(),
]);

// Set up connectors
export const connectors = [
  new CoinbaseWalletConnector({
    chains,
    options: {
      appName: "wagmi demo",
    },
  }),
  new WalletConnectConnector({
    chains,
    options: {
      infuraId,
      qrcode: true,
    },
  }),
  new MetaMaskConnector({
    chains,
  }),
];

πŸ“˜

Seeing errors? Check out the Troubleshooting section below for help.

Step 3: Create Client

In your index.js file, create a wagmi client using createClient from wagmi. Configure the client with the wallet connectors we defined above.

import { createClient } from "wagmi";

...

const client = createClient({
  autoConnect: true,
  connectors,
});

Step 4: Import and Setup WagmiConfig

In your index.js file, import the WagmiConfig component from wagmi and wrap it around your app root component, passing it the client we defined above.

import { WagmiConfig, createClient } from "wagmi";

...

ReactDOM.render(
  <React.StrictMode>
    <WagmiConfig client={client}>
      <App />
    </WagmiConfig>
  </React.StrictMode>,
  document.getElementById('root')
);

Connect and Disconnect from Wallet

Wagmi offers a convenient set of React hooks to interact with Ethereum. To connect your dapp to a user's wallet in your App.js file, import the useConnect React hook, which provides a method to establish a connection to the wallet connector of your choice and a boolean indicating the connection status.

import { useConnect } from "wagmi";

function App() {
    const { connect, connectors } = useConnect();
  
  return (
    <div className="App">
      <button onClick={() => { connect({ connector: connectors[0] }) }}>Coinbase Wallet</button>
      <button onClick={() => { connect({ connector: connectors[1] }) }}>Wallet Connect</button>
      <button onClick={() => { connect({ connector: connectors[2] }) }}>Metamask</button>
    </div>
  );
}

To disconnect from the current wallet, import the useDisconnect hook and call the disconnect method.

Bind the methods onto your UI components and that’s it! You should now be able to seamlessly connect and disconnect to Coinbase Wallet and other wallets from your dapp.

import { useConnect, useDisconnect } from "wagmi";

function App() {
    const { connect, connectors } = useConnect();
  const { disconnect } = useDisconnect();
  
  return (
    <div className="App">
      <button onClick={() => { connect({ connector: connectors[0] }) }}>Coinbase Wallet</button>
      <button onClick={() => { connect({ connector: connectors[1] }) }}>Wallet Connect</button>
      <button onClick={() => { connect({ connector: connectors[2] }) }}>Metamask</button>

      <button onClick={disconnect}>Disconnect</button>
    </div>
  );
}

Access connection status, account, network information

To access information regarding the current connection, connected user wallet address, and network information, you can import the relevant hooks from the wagmi library.

import { useConnect, useDisconnect, useAccount, useNetwork } from "wagmi";

function App() {
  const { data: accountData } = useAccount();
  const { connect, connectors, isConnected } = useConnect();
  const { disconnect } = useDisconnect();
  const { activeChain } = useNetwork();
  
  return (
    <div className="App">
      <button onClick={() => { connect({ connector: connectors[0] }) }}>Coinbase Wallet</button>
      <button onClick={() => { connect({ connector: connectors[1] }) }}>Wallet Connect</button>
      <button onClick={() => { connect({ connector: connectors[2] }) }}>Metamask</button>

      <button onClick={disconnect}>Disconnect</button>

      <div>Connection Status: ${isConnected}</div>
      <div>Account: ${accountData.address}</div>
      <div>Network ID: ${activeChain.id}</div
    </div>
  );
}

Switch Networks

Unlike other libraries, Wagmi offers built-in support for a variety of Ethereum interactions. For instance, in order to switch networks, you can directly call the switchNetwork method from the useNetwork hook with the target network chain id.

To learn more about how to implement this, check out our demo CodeSandbox. Search for switchNetwork as a place to start.

import { useNetwork } from "wagmi";

const { switchNetwork } = useNetwork();

const switchToPolygon = () => switchNetwork(137);

The full set of hooks for relevant Ethereum interactions can be found in the wagmi documentation.

Troubleshooting

πŸ“˜

I run into the following error: Module not found: Error: Can't resolve <'buffer'/'util'/...>

Due to the removal of default polyfills in webpack5, you must install the following utilities:

yarn add util

Then, add the following code snippet to your webpack.config.js:

resolve: {
  fallback: {
    'fs': false,
    'util': require.resolve('util/'),
  },
}

If you are using an application built on create-react-app locally, you must run npm run eject to be able to customize your webpack configuration.

Additional Resources