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 hooks library.

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

Image 1: Example of a custom modal built with wagmi hooks

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 install Coinbase Wallet, Wallet Connect, and an Injected connector (used to connect with Metamask).

Each connector has its own set of required parameters to pass in, such as a fallback JSON RPC URL or default chain ID.

import { chain, defaultChains } from "wagmi";
import { InjectedConnector } from "wagmi/connectors/injected";
import { WalletConnectConnector } from "wagmi/connectors/walletConnect";
import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";

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

// Chains for connectors to support
const chains = defaultChains;

export const connectors = ({ chainId }) => {
  const rpcUrl =
    defaultChains.find((x) => x.id === chainId)?.rpcUrls?.[0] ??
    chain.mainnet.rpcUrls[0];
  return [
    new CoinbaseWalletConnector({
      options: {
        appName: "My wagmi app",
        jsonRpcUrl: `${rpcUrl}/${infuraId}`
      }
    }),
    new WalletConnectConnector({
      options: {
        infuraId,
        qrcode: true
      }
    }),
    new InjectedConnector({
      chains,
      options: { shimDisconnect: true }
    })
  ];
};

📘

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

Step 3: Import and Setup Provider

In your index.js file, import the Provider from wagmi. Wrap the Provider around your app root component with the connectors we defined above to make them globally accessible throughout your dapp.

import { Provider } from "wagmi";

...

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

Connect and Disconnect from Wallet

Wagmi hooks offer a convenient set of hooks to interact with Ethereum. To connect your dapp to a user's wallet in your App.js file, import the useConnect 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 [{ data, error }, connect] = useConnect();
  
  return (
    <div className="App">
      <button onClick={() => { connect(data.connectors[0]) }}>Coinbase Wallet</button>
      <button onClick={() => { connect(data.connectors[1]) }}>Wallet Connect</button>
      <button onClick={() => { connect(data.connectors[2]) }}>Metamask</button>
    </div>
  );
}

To disconnect from the current wallet, import the useAccount 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 { useAccount, useConnect } from "wagmi";

function App() {
    const [{ data, error }, connect] = useConnect();
  const [{ data: accountData }, disconnect] = useAccount();
  
  return (
    <div className="App">
      <button onClick={() => { connect(data.connectors[0]) }}>Coinbase Wallet</button>
      <button onClick={() => { connect(data.connectors[1]) }}>Wallet Connect</button>
      <button onClick={() => { connect(data.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, useAccount, useNetwork } from "wagmi";

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

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

      <div>Connection Status: ${connectData.connected}</div>
      <div>Account: ${accountData.address}</div>
      <div>Network ID: ${networkData.chain.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 { useConnect, useAccount, useNetwork } from "wagmi";

const [{ data: networkData }, 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.

📘

The wallet connection does not persist upon refreshing the browser

Web3Modal provides a built-in option for you to automatically cache the connected provider.

// set cacheProvider parameter as true when instantiating web3modal
const web3Modal = new Web3Modal({
 cacheProvider: true, // optional
 providerOptions // required
});

// hook to automatically connect to the cached provider
useEffect(() => {
 if (web3Modal.cachedProvider) {
   connectWallet();
 }

}, []);>

Additional Resources