Connecting Your DApp to MetaMask Wallet
MetaMask is a popular browser extension and mobile app that allows users to interact with Ethereum-based decentralized applications (dApps) directly from their web browser or mobile device. In this guide, we'll walk through the steps to connect your web app to MetaMask Wallet.
Prerequisites
Before we begin, ensure you have the following prerequisites:
MetaMask Installed: Make sure your users have MetaMask installed in their web browser or mobile device. If not, they can download it from the official MetaMask website.
Basic Ethereum Knowledge: Familiarize yourself with basic Ethereum concepts such as wallets, accounts, and transactions.
Step 1: Setting Up Your Web App
The first step is to set up your web app to detect and interact with MetaMask. Let's go through the process:
Installation
Install the @metamask/detect-provider
package in your react-app, which provides a simple way to detect MetaMask in the user's browser.
npm install @metamask/detect-provider
Step 1: Detecting MetaMask
Use the detectEthereumProvider()
function to check if MetaMask is installed in the user's browser.
import { detectEthereumProvider } from "@metamask/detect-provider";
const checkMetaMask = async () => {
const provider = await detectEthereumProvider();
if (provider) {
console.log("MetaMask detected");
} else {
console.log("MetaMask not detected");
}
};
checkMetaMask();
Step 2: Authenticating Users
Once MetaMask is detected, prompt users to connect their wallet to your web app using the eth_requestAccounts
method.
const connectWallet = async () => {
try {
const provider = await detectEthereumProvider();
if (provider) {
const accounts = await provider.request({ method: "eth_requestAccounts" });
console.log("Connected account:", accounts[0]);
} else {
console.error("MetaMask not detected");
}
} catch (error) {
console.error("Error connecting to MetaMask:", error);
}
};
// Call connectWallet() when user clicks "Connect Wallet" button
Step 3: Handling Account Changes
Handle changes to the connected MetaMask account by listening for the accountsChanged
event.
const handleAccountChange = async () => {
const provider = await detectEthereumProvider();
if (provider) {
provider.on("accountsChanged", (accounts: string[]) => {
console.log("Accounts changed:", accounts);
});
} else {
console.error("MetaMask not detected");
}
};
Step 4: Interacting with MetaMask
Finally, interact with the connected MetaMask wallet to perform transactions and other operations.
const sendTransaction = async (to: string, value: string) => {
const provider = await detectEthereumProvider();
if (provider) {
await provider.request({
method: "eth_sendTransaction",
params: [{ to, value }],
});
console.log("Transaction sent");
} else {
console.error("MetaMask not detected");
}
};
However, it's important to note that users may encounter issues when using MetaMask on mobile devices. To ensure a seamless experience on mobile, you need to provide the correct deep link when opening the MetaMask app.
One way to detect if the user is on a mobile device is by using the following code:
const [isMobile, setIsmobiel] = useState<boolean>(false);
const userAgent = window.navigator.userAgent;
setIsMobile(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent));
Then, if the user is on a mobile device, you can provide the correct deep link to open the MetaMask app and If the user doesn't have the wallet installed it will redirect to the Play Store app: you can add this below code snippet to the connectWallet function inside try.
if (isMobile) {
const metamaskAppDeepLink = `https://metamask.app.link/dapp/${window.location.origin.slice(8)}`;
window.location.href = metamaskAppDeepLink;
}
// passing the origin without http:// or https://
Experiment with these code snippets, explore the MetaMask documentation, and start building amazing decentralized applications today!
読んでくれてありがとう
(Yonde kurete arigatou) - Thanks for reading
Subscribe to my newsletter
Read articles from Shivam Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shivam Yadav
Shivam Yadav
I am a developer from India, pursuing Btech majoring in Information Technology. I want to tackle tough problems that others find tricky. I'm okay with working late if needed. I love when my work gets noticed and that pushes me to do more. I'm also open to learning new things, even if I am not familiar with something initially. I'm all about giving my best to meet the work's needs.