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

Quadratic Voting in Web3

Kajetan Olas

04 Dec 2024
Quadratic Voting in Web3

Decentralized systems are reshaping how we interact, conduct transactions, and govern online communities. As Web3 continues to advance, the necessity for effective and fair voting mechanisms becomes apparent. Traditional voting systems, such as the one-token-one-vote model, often fall short in capturing the intensity of individual preferences, which can result in centralization. Quadratic Voting (QV) addresses this challenge by enabling individuals to express not only their choices but also the strength of their preferences.

In QV, voters are allocated a budget of credits that they can spend to cast votes on various issues. The cost of casting multiple votes on a single issue increases quadratically, meaning that each additional vote costs more than the last. This system allows for a more precise expression of preferences, as individuals can invest more heavily in issues they care deeply about while conserving credits on matters of lesser importance.

Understanding Quadratic Voting

Quadratic Voting (QV) is a voting system designed to capture not only the choices of individuals but also the strength of their preferences. In most DAO voting mechanisms, each person typically has one vote per token, which limits the ability to express how strongly they feel about a particular matter. Furthermore, QV limits the power of whales and founding team who typically have large token allocations. These problems are adressed by making the cost of each additional vote increase quadratically.

In QV, each voter is given a budget of credits or tokens that they can spend to cast votes on various issues. The key principle is that the cost to cast n votes on a single issue is proportional to the square of n. This quadratic cost function ensures that while voters can express stronger preferences, doing so requires a disproportionately higher expenditure of their voting credits. This mechanism discourages voters from concentrating all their influence on a single issue unless they feel very strongly about it. In the context of DAOs, it means that large holders will have a hard-time pushing through with a proposal if they'll try to do it on their own.

Practical Example

Consider a voter who has been allocated 25 voting credits to spend on several proposals. The voter has varying degrees of interest in three proposals: Proposal A, Proposal B, and Proposal C.

  • Proposal A: High interest.
  • Proposal B: Moderate interest.
  • Proposal C: Low interest.

The voter might allocate their credits as follows:

Proposal A:

  • Votes cast: 3
  • Cost: 9 delegated tokens

Proposal B:

  • Votes cast: 2
  • Cost: 4 delegated tokens

Proposal C:

  • Votes cast: 1
  • Cost: 1 delegated token

Total delegated tokens: 14
Remaining tokens: 11

With the remaining tokens, the voter can choose to allocate additional votes to the proposals based on their preferences or save for future proposals. If they feel particularly strong about Proposal A, they might decide to cast one more vote:

Additional vote on Proposal A:

  • New total votes: 4
  • New cost: 16 delegated tokens
  • Additional cost: 16−9 = 7 delegated tokens

Updated total delegated tokens: 14+7 = 21

Updated remaining tokens: 25−21 = 425 - 21 = 4

This additional vote on Proposal A costs 7 credits, significantly more than the previous vote, illustrating how the quadratic cost discourages excessive influence on a single issue without strong conviction.

Benefits of Implementing Quadratic Voting

Key Characteristics of the Quadratic Cost Function

  • Marginal Cost Increases Linearly: The marginal cost of each additional vote increases linearly. The cost difference between casting n and n−1 votes is 2n−1.
  • Total Cost Increases Quadratically: The total cost to cast multiple votes rises steeply, discouraging voters from concentrating too many votes on a single issue without significant reason.
  • Promotes Egalitarian Voting: Small voters are encouraged to participate, because relatively they have a much higher impact.

Advantages Over Traditional Voting Systems

Quadratic Voting offers several benefits compared to traditional one-person-one-vote systems:

  • Captures Preference Intensity: By allowing voters to express how strongly they feel about an issue, QV leads to outcomes that better reflect the collective welfare.
  • Reduces Majority Domination: The quadratic cost makes it costly for majority groups to overpower minority interests on every issue.
  • Encourages Honest Voting: Voters are incentivized to allocate votes in proportion to their true preferences, reducing manipulation.

By understanding the foundation of Quadratic Voting, stakeholders in Web3 communities can appreciate how this system supports more representative governance.

Conclusion

Quadratic voting is a novel voting system that may be used within DAOs to foster decentralization. The key idea is to make the cost of voting on a certain issue increase quadratically. The leading player that makes use of this mechanism is Optimism. If you're pondering about the design of your DAO, we highly recommend taking a look at their research on quadratic funding.

If you're looking to create a robust governance model and go through institutional-grade testing please reach out to contact@nextrope.com. Our team is ready to help you with the token engineering process and ensure that your DAO will stand out as a beacon of innovation and resilience in the long term.

Aethir Tokenomics – Case Study

Kajetan Olas

22 Nov 2024
Aethir Tokenomics – Case Study

Authors of the contents are not affiliated to the reviewed project in any way and none of the information presented should be taken as financial advice.

In this article we analyze tokenomics of Aethir - a project providing on-demand cloud compute resources for the AI, Gaming, and virtualized compute sectors.
Aethir aims to aggregate enterprise-grade GPUs from multiple providers into a DePIN (Decentralized Physical Infrastructure Network). Its competitive edge comes from utlizing the GPUs for very specific use-cases, such as low-latency rendering for online games.
Due to decentralized nature of its infrastructure Aethir can meet the demands of online-gaming in any region. This is especially important for some gamer-abundant regions in Asia with underdeveloped cloud infrastructure that causes high latency ("lags").
We will analyze Aethir's tokenomics, give our opinion on what was done well, and provide specific recommendations on how to improve it.

Evaluation Summary

Aethir Tokenomics Structure

The total supply of ATH tokens is capped at 42 billion ATH. This fixed cap provides a predictable supply environment, and the complete emissions schedule is listed here. As of November 2024 there are approximately 5.2 Billion ATH in circulation. In a year from now (November 2025), the circulating supply will almost triple, and will amount to approximately 15 Billion ATH. By November 2028, today's circulating supply will be diluted by around 86%.

From an investor standpoint the rational decision would be to stake their tokens and hope for rewards that will balance the inflation. Currently the estimated APR for 3-year staking is 195% and for 4-year staking APR is 261%. The rewards are paid out weekly. Furthermore, stakers can expect to get additional rewards from partnered AI projects.

Staking Incentives

Rewards are calculated based on the staking duration and staked amount. These factors are equally important and they linearly influence weekly rewards. This means that someone who stakes 100 ATH for 2 weeks will have the same weekly rewards as someone who stakes 200 ATH for 1 week. This mechanism greatly emphasizes long-term holding. That's because holding a token makes sense only if you go for long-term staking. E.g. a whale staking $200k with 1 week lockup. will have the same weekly rewards as person staking $1k with 4 year lockup. Furthermore the ATH staking rewards are fixed and divided among stakers. Therefore Increase of user base is likely to come with decrease in rewards.
We believe the main weak-point of Aethirs staking is the lack of equivalency between rewards paid out to the users and value generated for the protocol as a result of staking.

Token Distribution

The token distribution of $ATH is well designed and comes with long vesting time-frames. 18-month cliff and 36-moths subsequent linear vesting is applied to team's allocation. This is higher than industry standard and is a sign of long-term commitment.

  • Checkers and Compute Providers: 50%
  • Ecosystem: 15%
  • Team: 12.5%
  • Investors: 11.5%
  • Airdrop: 6%
  • Advisors: 5%

Aethir's airdrop is divided into 3 phases to ensure that only loyal users get rewarded. This mechanism is very-well thought and we rate it highly. It fosters high community engagement within the first months of the project and sets the ground for potentially giving more-control to the DAO.

Governance and Community-Led Development

Aethir’s governance model promotes community-led decision-making in a very practical way. Instead of rushing with creation of a DAO for PR and marketing purposes Aethir is trying to make it the right way. They support projects building on their infrastructure and regularly share updates with their community in the most professional manner.

We believe Aethir would benefit from implementing reputation boosted voting. An example of such system is described here. The core assumption is to abandon the simplistic: 1 token = 1 vote and go towards: Votes = tokens * reputation_based_multiplication_factor.

In the attached example, reputation_based_multiplication_factor rises exponentially with the number of standard deviations above norm, with regard to user's rating. For compute compute providers at Aethir, user's rating could be replaced by provider's uptime.

Perspectives for the future

While it's important to analyze aspects such as supply-side tokenomics, or governance, we must keep in mind that 95% of project's success depends on demand-side. In this regard the outlook for Aethir may be very bright. The project declares $36M annual reccuring revenue. Revenue like this is very rare in the web3 space. Many projects are not able to generate any revenue after succesfull ICO event, due to lack fo product-market-fit.

If you're looking to create a robust tokenomics model and go through institutional-grade testing please reach out to contact@nextrope.com. Our team is ready to help you with the token engineering process and ensure your project’s resilience in the long term.