Integration of MetaMask wallet in React application

Paulina Lewandowska

19 Dec 2022
Integration of MetaMask wallet in React application

Introduction

In decentralized applications, users typically need a crypto wallet to interact with the blockchain. To enable this, developers working on the frontend layer must integrate their application with users' wallet applications. This article is intended for developers using the React library who want to create user interfaces with the popular browser plugin, MetaMask. Here is a step-by-step guide on how to integrate a React application with MetaMask.

A basic application in React

The source code of the application written for this tutarial can be found at this link. I used the following libraries to create the application:

To work with this tutorial, you can use the application provided at the link above, or you can configure the application yourself in React with the help of, for example, create-react-app or vite.

Once our application is configured, you need to make sure that we have all the necessary dependencies installed, to do this, run the command

npm install wagmi ethers

To prepare the application, I also used a component library called Material-ui, if you also want to use it, install the following packages with the command:

npm install @mui/material @emotion/react @emotion/styled

Once the configuration is complete and all the necessary dependencies are installed, we can move on to the next point.

Wagmi Library

To integrate with the MetaMask wallet application, we will use a dedicated library for React called wagmi that contains a sizable number of hooks and functions needed for daily blockchain interactions in frontend applications.

The first step will be to configure the library, to do this we need to wrap our application in a WagmiConfig component passing a client variable with our configuration:

import { WagmiConfig, createClient } from "wagmi";
import { getDefaultProvider } from "ethers";
 
import { Home } from "./pages";
import "./styles.css";
 
const client = createClient({
 autoConnect: true,
 provider: getDefaultProvider()
});
 
export default function App() {
 return (
   <WagmiConfig client={client}>
     <Home />
   </WagmiConfig>
 );
}

All available configuration options can be found at this link in the official wagmi documentation

Connecting the MetaMask wallet

Once we have completed the configuration of the wagmi library, we can move on to creating the component responsible for connecting to our wallet. The hooks available in the blibliothek will be helpful in the implementation.

To access the function that will allow us to make a request to connect the wallet, use the useConnect() hooka. To indicate that the wallet we want to connect to is MetaMask, pass the created instance of the InjectedConnector class in the configuration object to the hooka under the connecter key

import { useConnect } from "wagmi";
import { InjectedConnector } from "wagmi/dist/connectors/injected";
 
 ...
 
 const { connect } = useConnect({
   connector: new InjectedConnector()
 });
 
 ...

Hook returns us a connect function that we can call, for example, when the button is clicked.

 ...
 
<Button onClick={() => connect()}>Connect</Button>
 
 ...

To get information about the connected wallet or its connection status, you can use the useAccount() hookup, which returns us such information as:

  • the address of the connected wallet
  • whether the wallet connection action is in progress
  • whether the user's wallet is currently connected in the application
...
 
 const { address, isConnected, isConnecting } = useAccount();
 
 ...

If the user of our application managed to connect the wallet we should also allow him to disconnect it, for this we need to use the disconnect function, which we can access with the help of the hookup useDisconnect()

 ...
 
 const { disconnect } = useDisconnect();
 
 ...

With the help of these three simple hooks, we are able to handle wallet connection. The full source code of the component that handles the connection from the sample application:

import { useConnect, useDisconnect, useAccount } from "wagmi";
import { InjectedConnector } from "wagmi/dist/connectors/injected";
import { Card, Button, Heading } from "../../components";
import Typography from "@mui/material/Typography";
import { WalletInfo } from "./WalletInfo";
 
export const WalletConnect = () => {
 const { isConnected, isConnecting } = useAccount();
 
 const { connect } = useConnect({
   connector: new InjectedConnector()
 });
 
 const { disconnect } = useDisconnect();
 
 return (
   <Card>
     <Heading sx={{ mb: 2 }}>
       {isConnected ? "Your connected wallet:" : "Connect your MetaMask"}
     </Heading>
 
     {isConnecting && <Typography>Connecting...</Typography>}
 
     {isConnected ? (
       <>
         <WalletInfo />
         <Button sx={{ mt: 2 }} onClick={() => disconnect()}>
           Disconnect
         </Button>
       </>
     ) : (
       <Button
         disabled={isConnecting}
         sx={{ mt: 2 }}
         onClick={() => connect()}
       >
         Connect
       </Button>
     )}
   </Card>
 );
};

In the above example there is a <WalletInfo /> component, which we will use to display information about the connected wallet, we will deal with its creation in the next step.

Displaying information about the connected wallet

The next step will display to the user information about the connected wallet such as:

  • Wallet address
  • The current ETH balance of the wallet

To do this, we will prepare two simple components <WalletAddress/> and <WalletBalance/> and , which we will then put into the <WalletInfo/> component:

The address of the currently connected wallet

import { WalletAddress } from "./WalletAddress";
import { WalletBalance } from "./WalletBalance";
 
export const WalletInfo = () => {
 return (
   <div>
     <WalletAddress />
     <WalletBalance />
   </div>
 );
};
import { useAccount } from "wagmi";
import Typography from "@mui/material/Typography";
 
export const WalletAddress = () => {
 const { address } = useAccount();
 return (
   <Typography>
     <strong>Address: </strong>
     {address}
   </Typography>
 );
};

In order to display the connected wallet, we will use the previously mentioned useAccount() hookup, which returns us the address variable. The implementation of a simple component to display the address looks like this:

import { useAccount } from "wagmi";
import Typography from "@mui/material/Typography";
 
export const WalletAddress = () => {
 const { address } = useAccount();
 return (
   <Typography>
     <strong>Address: </strong>
     {address}
   </Typography>
 );
};

Balance of the currently connected wallet

The wagmi library also has a useBalance() hook, which will make the process of retrieving the current wallet balance much easier for us. The process of fetching this value from the blockchain is asynchronous, so this hook returns on, among other things, such information in variables as:

  • isLoading - whether the balance download is in progress
  • isFetched - whether the wallet's balance has been downloaded
  • isError - whether an error occurred while downloading the data
  • data - object containing such fields as:
    • value - user balance in WEI units
    • formatted - user's balance formatted to ETH units
    • symbol - Symbol of the asset for which the balance was downloaded
    • decimals - the number of decimal places that the number describing the quantity of the asset can have

For a better understanding of what a WEI, ETH unit or decimals parameter is, I encourage you to read these articles:

To indicate for which wallet we want to retrieve the balance of funds, we need to pass the address of this wallet as a parameter when calling the hookah as follows, to do this we can use the useAccount() hookah again from the previous step:

 ...
 
 const { address } = useAccount();
 const { isLoading, isFetched, isError, data } = useBalance({ address });
 
 ...

With this information, we are able to implement an entire component with support for the data loading process:

import { useAccount, useBalance } from "wagmi";
import Typography from "@mui/material/Typography";
import Skeleton from "@mui/material/Skeleton";
 
export const WalletBalance = () => {
 const { address } = useAccount();
 const { isLoading, isFetched, isError, data } = useBalance({ address });
 
 return (
   <Typography>
     {isLoading && <Skeleton width={200} />}
     {isFetched && (
       <>
         <strong>Balance: </strong>
         {data?.formatted} {data?.symbol}
       </>
     )}
     {isError && "Fetching balance failed!"}
   </Typography>
 );
};

Summary

The application presented here is just an example, in production applications developers often have to deal with integrating multiple wallet applications, supporting connectivity on multiple blockchain networks, and interactions of connected wallets with smart contracts. All of these functionalities and much more are supported by the wagmi library presented in this turorial. Therefore, I encourage you to study the documentation of this library to see what capabilities it offers.

Tagi

Most viewed


Never miss a story

Stay updated about Nextrope news as it happens.

You are subscribed

Nextrope Partners with Hacken to Enhance Blockchain Security

Miłosz

21 Nov 2024
Nextrope Partners with Hacken to Enhance Blockchain Security

Nextrope announces a strategic partnership with Hacken, a renowned blockchain security auditor. It marks a significant step in delivering reliable decentralized solutions. After several successful collaborations resulting in flawless smart contract audits, the alliance solidifies the synergy between Nextrope's innovative blockchain development and Hacken's top-tier security auditing services. Together, we aim to set new benchmarks, ensuring that security is an integral part of blockchain technology.

Strengthening Blockchain Security

The partnership aims to fortify the security protocols within blockchain ecosystems. By integrating Hacken's comprehensive security audits with Nextrope's cutting-edge blockchain solutions, we are poised to offer unparalleled security features in our projects.

"Blockchain security should never be an afterthought"

"Our partnership with Hacken underscores our dedication to embedding security at the core of our blockchain solutions. Together, we're building a safer future for the industry."

said Mateusz Mach, CEO of Nextrope

About Nextrope

Nextrope is a forward-thinking blockchain development house specializing in creating innovative solutions for businesses worldwide. With a team of experienced developers and blockchain experts, Nextrope delivers high-quality, scalable, and secure blockchain applications tailored to meet the unique needs of each client.

About Hacken

Hacken is a leading blockchain security auditor known for its rigorous smart contract audits and security assessments. With a mission to make the industry safer, Hacken provides complex security services that help companies identify and mitigate vulnerabilities in their applications.

Looking Ahead

As a joint mission, both Nextrope and Hacken are committed to continuous innovation. We look forward to the exciting opportunities this partnership will bring and are eager to implement a more secure blockchain environment for all.

For more information, please contact:

Nextrope

Hacken

Join us on our journey to deliver top-notch blockchain tech and a safer future for the industry!

Nextrope as Sponsor at ETH Warsaw 2024: Highlights

Miłosz

04 Oct 2024
Nextrope as Sponsor at ETH Warsaw 2024: Highlights

ETH Warsaw has established itself as a significant event in the Web3 space, gathering developers, entrepreneurs, and investors in the heart of Poland’s capital each year. The 2024 edition was filled with builders and leaders united in advancing decentralized technologies.

Leading Event of Warsaw Blockchain Week

As a blend of conference and hackathon, ETH Warsaw aims to push the boundaries of innovation. For companies and individuals eager to shape the future of tech, the premier summit during Warsaw Blockchain Week offers a unique platform to connect and collaborate.

Major Milestones in Previous Editions

  • Over 1,000 participants attended the forum
  • 222 hackers competed, showcasing groundbreaking technical skills
  • $119,920 in bounties was awarded to boost promising solution development

Key Themes at ETH Warsaw 2024

This year’s discussions were centered around shaping the adoption of blockchain. To emphasize that future implementation requires a wide range of voices, perspectives, and understanding, ETH Warsaw 2024 encouraged participation from individuals of all backgrounds. As the industry stands on the cusp of a potential bull market, building resilient products brings substantial impact. Participants mutually raised an inhibitor posed by poor architecture or suspicious practices.

Infrastructure and Scalability

  • Layer 2 (L2) solutions
  • Zero-Knowledge Proofs (ZKPs)
  • Future of Account Abstraction in Decentralized Applications (DApps)
  • Advancements in Blockchain Interoperability
  • Integration of Artificial Intelligence (AI) and Machine Learning Models (MLMs) with on-chain data

Responsibility

With the premise of robust blockchain systems, we delved into topics such as privacy, advanced security protocols, and white-hacking as essential tools for maintaining trust. Discussions also included consensus mechanisms and their role in the entire infrastructure, beginning with transparent Decentralized Autonomous Organizations (DAOs).

Legal Policies

The track on financial freedom led to the transformative potential of decentralized finance (DeFi). We tackled the challenges and opportunities of blockchain products within a rapidly evolving regulatory landscape.

Mass Adoption

Conversations surrounding accessible platforms underscored the need to simplify onboarding for new users, ultimately crafting solutions that appeal to mainstream audiences. Contributors explored ways to improve user experience (UX), enhance community management, and support Web3 startups.

ETH Legal, co-organized with PKO BP and several leading law firms, studied the implementation of the MiCA guidelines starting next year and affecting the market. It aimed to dissect the complex policies that govern digital assets.

Currently, founders navigate a patchwork of regulations that vary by jurisdiction. There is a clear need for structured protocols that ensure consumer protection and market integrity while attracting more users. Legal experts broke down the implications of existing and anticipated changes on decentralized finance (DeFi), non-fungible tokens (NFTs), business logic, and other emerging technologies.

The importance of ETH Legal extended beyond theoretical discussions. It served as a vital forum for stakeholders to connect and share insights. Thanks to input from renowned experts in the field, attendees left with a deeper understanding of the challenges ahead.

Warsaw Blockchain Week: Nextrope’s Engagement

The Warsaw Blockchain Week 2024 ensured a wide range of activities, with a packed schedule of conferences, hackathons, and networking opportunities. Nextrope actively engaged in several side events throughout the week and recognized the immense potential to foster connections.

Side Events Attended by Nextrope

  • Elympics on TON
  • Aleph Zero Opening Party
  • Cookie3 x NOKS x TON Syndicate
  • Solana House

Nextrope’s Contribution to ETH Warsaw 2024

At ETH Warsaw 2024, Nextrope proudly positioned itself as a Pond Sponsor of the conference and hackathon, reflecting the event's mission. Following a strong track record of partnerships with large financial institutions and startups, we seized the opportunity to share our reflections with the community.

Together, we continue to innovate toward a more decentralized and inclusive future. By actively participating in open conversations about regulatory and technological advancements, Nextrope solidifies its role as an exemplar of dedication, forward-thinking, and technological resources.