# Developers के लिए MetaMask — अपने dApp को Web3 से Connect करें
MetaMask, millions of users के लिए Web3 का gateway है। सबसे popular Ethereum wallet browser extension के रूप में, यह users को अपने browser से सीधे decentralized applications (dApps) के साथ interact करने की अनुमति देता है। Developers के लिए, MetaMask integration essential है ताकि users wallets को connect कर सकें, transactions को sign कर सकें, और smart contracts के साथ interact कर सकें। यह guide आपको seamless MetaMask integration बनाने के लिए जो कुछ भी जानने की ज़रूरत है, उसे cover करती है।
MetaMask क्या है?
MetaMask एक cryptocurrency wallet और blockchain applications का gateway है। यह function करता है:
- Browser extension (Chrome, Firefox, Edge, Brave)
- Mobile app (iOS और Android)
- Web3 provider जो web pages में
window.ethereumको inject करता है
- Account manager Ethereum addresses और private keys के लिए
- Network switcher Ethereum mainnet, testnets, और अन्य EVM chains के बीच
30 million से ज़्यादा monthly active users के साथ, MetaMask अधिकतर Ethereum dApps के लिए default wallet है।
MetaMask कैसे काम करता है
जब install किया जाता है, तो MetaMask हर webpage में window.ethereum (या EIP-6963 के माध्यम से window.ethereum) नामक एक JavaScript object inject करता है। आपका dApp इस object का उपयोग करता है:
सभी sensitive operations (signing transactions, messages) MetaMask के secure UI में होते हैं — आपके dApp को private keys तक कभी access नहीं मिलता।
MetaMask को Detect करना
Basic Detection
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
} else {
console.log('Please install MetaMask');
// https://metamask.io/download पर redirect करें
}
EIP-6963: Multi-Wallet Detection
Modern dApps को multiple wallets को support करना चाहिए। EIP-6963 सभी installed wallets को detect करने का एक standard तरीका provide करता है:
// Wallet providers के लिए listen करें
const wallets = [];
window.addEventListener('eip6963:announceProvider', (event) => {
wallets.push(event.detail);
});
// Wallet announcements के लिए request करें
window.dispatchEvent(new Event('eip6963:requestProvider'));
// अब wallets में सभी installed providers हैं (MetaMask, Coinbase Wallet, etc.)
Check करें कि MetaMask Active Provider है
const isMetaMask = window.ethereum?.isMetaMask;
if (isMetaMask) {
console.log('MetaMask detected');
}
MetaMask से Connect करना
Account Access के लिए Request करें
async function connectWallet() {
try {
// Account access के लिए request करें
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
const account = accounts[0];
console.log('Connected account:', account);
return account;
} catch (error) {
if (error.code === 4001) {
// User ने request को reject किया
console.log('Please connect to MetaMask');
} else {
console.error('Error connecting:', error);
}
}
}
Connected Accounts प्राप्त करें (कोई Popup नहीं)
अगर user पहले से connected है, तो eth_accounts का उपयोग करें (popup नहीं दिखाता):
async function getConnectedAccounts() {
const accounts = await window.ethereum.request({
method: 'eth_accounts'
});
return accounts; // अगर connected नहीं है तो empty array
}
Complete Connection Flow
async function init() {
// Check करें कि पहले से connected है
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
if (accounts.length > 0) {
// पहले से connected है
setAccount(accounts[0]);
} else {
// "Connect Wallet" button दिखाएं
document.getElementById('connectButton').addEventListener('click', async () => {
const newAccounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
setAccount(newAccounts[0]);
});
}
}
function setAccount(account) {
document.getElementById('account').textContent = account;
document.getElementById('connectButton').style.display = 'none';
document.getElementById('dapp').style.display = 'block';
}
Transactions भेजना
ETH भेजें
async function sendEther(to, amount) {
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
const from = accounts[0];
// amount wei में (1 ETH = 10^18 wei)
const value = '0x' + (amount * 10**18).toString(16);
try {
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [{
from: from,
to: to,
value: value,
// gas: '0x5208', // Optional: simple transfer के लिए 21000 wei
}],
});
console.log('Transaction hash:', txHash);
return txHash;
} catch (error) {
console.error('Transaction failed:', error);
}
}
// Usage
await sendEther('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', 0.1);
Smart Contracts के साथ Interact करें (Raw)
async function callContractFunction() {
const contractAddress = '0x...';
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
// Function signature: transfer(address,uint256)
const functionSignature = '0xa9059cbb'; // keccak256("transfer(address,uint256)") के first 4 bytes
// Parameters को encode करें (address + amount)
const recipient = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'.slice(2).padStart(64, '0');
const amount = (100 * 10**18).toString(16).padStart(64, '0');
const data = functionSignature + recipient + amount;
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [{
from: accounts[0],
to: contractAddress,
data: data,
}],
});
return txHash;
}
Note: Manual encoding error-prone है। ethers.js या web3.js का उपयोग करें (नीचे देखें)।
Networks को Switch करना
Network Switch के लिए Request करें
async function switchToSepolia() {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xaa36a7' }], // Sepolia testnet
});
} catch (error) {
if (error.code === 4902) {
// Network MetaMask में add नहीं है
await addSepoliaNetwork();
} else {
console.error('Failed to switch network:', error);
}
}
}
Custom Network Add करें
async function addPolygonNetwork() {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0x89', // decimal में 137
chainName: 'Polygon Mainnet',
nativeCurrency: {
name: 'MATIC',
symbol: 'MATIC',
decimals: 18
},
rpcUrls: ['https://polygon-rpc.com'],
blockExplorerUrls: ['https://polygonscan.com']
}],
});
} catch (error) {
console.error('Failed to add network:', error);
}
}
Current Network प्राप्त करें
async function getCurrentNetwork() {
const chainId = await window.ethereum.request({ method: 'eth_chainId' });
console.log('Current chain ID:', chainId); // e.g., "0x1" Ethereum mainnet के लिए
const networkMap = {
'0x1': 'Ethereum Mainnet',
'0xaa36a7': 'Sepolia Testnet',
'0x89': 'Polygon Mainnet',
'0xa4b1': 'Arbitrum One',
};
return networkMap[chainId] || 'Unknown Network';
}
Changes के लिए Listen करना
Account Changes
window.ethereum.on('accountsChanged', (accounts) => {
if (accounts.length === 0) {
// User ने सभी accounts को disconnect कर दिया
console.log('Please connect to MetaMask');
} else {
// User ने account switch किया
console.log('Account changed to:', accounts[0]);
setAccount(accounts[0]);
}
});
Network Changes
window.ethereum.on('chainChanged', (chainId) => {
console.log('Network changed to:', chainId);
// Recommended: inconsistent state से बचने के लिए page को reload करें
window.location.reload();
});
Connection/Disconnection
window.ethereum.on('connect', (connectInfo) => {
console.log('Connected to network:', connectInfo.chainId);
});
window.ethereum.on('disconnect', (error) => {
console.log('Disconnected from network:', error);
});
Ethers.js के साथ Integration
Raw MetaMask API verbose है। Ethers.js एक cleaner abstraction provide करता है।
Installation
npm install ethers
Ethers.js के साथ Wallet Connect करें
import { BrowserProvider } from 'ethers';
async function connectWallet() {
if (typeof window.ethereum === 'undefined') {
alert('Please install MetaMask');
return;
}
// Account access के लिए request करें
await window.ethereum.request({ method: 'eth_requestAccounts' });
// Ethers provider बनाएं
const provider = new BrowserProvider(window.ethereum);
// Signer (connected account) प्राप्त करें
const signer = await provider.getSigner();
const address = await signer.getAddress();
console.log('Connected:', address);
return { provider, signer, address };
}
Ethers.js के साथ Transaction भेजें
async function sendEther(to, amount) {
const { signer } = await connectWallet();
const tx = await signer.sendTransaction({
to: to,
value: ethers.parseEther(amount.toString()) // ETH को wei में convert करें
});
console.log('Transaction sent:', tx.hash);
// Confirmation के लिए wait करें
const receipt = await tx.wait();
console.log('Transaction confirmed:', receipt);
return receipt;
}
// Usage
await sendEther('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', 0.1);
Smart Contracts के साथ Interact करें
import { Contract } from 'ethers';
async function interactWithContract() {
const { signer } = await connectWallet();
const contractAddress = '0x...';
const abi = [
"function transfer(address to, uint256 amount) returns (bool)",
"function balanceOf(address owner) view returns (uint256)"
];
const contract = new Contract(contractAddress, abi, signer);
// Read function (कोई gas cost नहीं)
const balance = await contract.balanceOf(await signer.getAddress());
console.log('Balance:', ethers.formatEther(balance));
// Write function (gas cost होता है)
const tx = await contract.transfer('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', ethers.parseEther('10'));
await tx.wait();
console.log('Transfer complete');
}
Blockchain Data को Read करें
async function getBlockchainData() {
const provider = new BrowserProvider(window.ethereum);
// Block number प्राप्त करें
const blockNumber = await provider.getBlockNumber();
console.log('Current block:', blockNumber);
// Gas price प्राप्त करें
const feeData = await provider.getFeeData();
console.log('Gas price:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'gwei');
// Balance प्राप्त करें
const balance = await provider.getBalance('0x...');
console.log('Balance:', ethers.formatEther(balance), 'ETH');
}
Messages को Sign करना
Personal Sign (Human-Readable Messages)
async function signMessage(message) {
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
const signature = await window.ethereum.request({
method: 'personal_sign',
params: [message, accounts[0]],
});
console.log('Signature:', signature);
return signature;
}
// Usage
await signMessage('I agree to the terms of service');
Ethers.js के साथ
async function signMessage(message) {
const { signer } = await connectWallet();
const signature = await signer.signMessage(message);
return signature;
}
EIP-712: Typed Structured Data Signing
Structured data के लिए (permit functions, gasless transactions में उपयोग किया जाता है):
async function signTypedData() {
const { signer } = await connectWallet();
const domain = {
name: 'MyDApp',
version: '1',
chainId: 1,
verifyingContract: '0x...'
};
const types = {
Transfer: [
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint256' }
]
};
const value = {
to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
amount: ethers.parseEther('10')
};
const signature = await signer.signTypedData(domain, types, value);
return signature;
}
Error Handling
Common Error Codes
async function handleMetaMaskError() {
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
} catch (error) {
switch (error.code) {
case 4001:
// User ने request को reject किया
console.log('Please connect to MetaMask');
break;
case -32002:
// Request पहले से pending है
console.log('Please open MetaMask to complete the request');
break;
case -32603:
// Internal error
console.error('Internal error:', error.message);
break;
default:
console.error('Unknown error:', error);
}
}
}
Best Practices
1. हमेशा MetaMask के लिए Check करें
if (typeof window.ethereum === 'undefined') {
showInstallPrompt(); // User को MetaMask install करने के लिए guide करें
}
2. Account Changes को Handle करें
window.ethereum.on('accountsChanged', (accounts) => {
if (accounts.length === 0) {
logout(); // User ने disconnect किया
} else {
updateAccount(accounts[0]);
}
});
3. Network Change पर Reload करें
window.ethereum.on('chainChanged', () => {
window.location.reload(); // Inconsistent state को रोकता है
});
4. Permissions एक बार Request करें
हर page load पर eth_requestAccounts को call न करें। Check करने के लिए eth_accounts का उपयोग करें कि पहले से connected है।
5. Clear Error Messages Provide करें
if (error.code === 4001) {
alert('You need to connect your wallet to use this feature');
}
6. Multiple Networks पर Test करें
अपने dApp को mainnet, testnets (Sepolia), और L2s (Polygon, Arbitrum) पर test करें।
7. Mobile को Support करें
MetaMask Mobile deep linking के लिए WalletConnect का उपयोग करता है। Mobile browsers पर test करें।
Complete React Example
import { useState, useEffect } from 'react';
import { BrowserProvider } from 'ethers';
function App() {
const [account, setAccount] = useState(null);
const [provider, setProvider] = useState(null);
useEffect(() => {
if (window.ethereum) {
// Check करें कि पहले से connected है
window.ethereum.request({ method: 'eth_accounts' })
.then(accounts => {
if (accounts.length > 0) {
setAccount(accounts[0]);
setProvider(new BrowserProvider(window.ethereum));
}
});
// Account changes के लिए listen करें
window.ethereum.on('accountsChanged', (accounts) => {
setAccount(accounts[0] || null);
});
// Network changes के लिए listen करें
window.ethereum.on('chainChanged', () => {
window.location.reload();
});
}
}, []);
const connectWallet = async () => {
if (!window.ethereum) {
alert('Please install MetaMask');
return;
}
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
setAccount(accounts[0]);
setProvider(new BrowserProvider(window.ethereum));
};
return (
<div>
{account ? (
<div>
<p>Connected: {account}</p>
{/* आपका dApp UI */}
</div>
) : (
<button onClick={connectWallet}>Connect Wallet</button>
)}
</div>
);
}
Conclusion
MetaMask integration किसी भी Ethereum dApp के लिए essential है। इस guide को follow करके, आप MetaMask को detect कर सकते हैं, wallets को connect कर सकते हैं, transactions भेज सकते हैं, और smart contracts के साथ seamlessly interact कर सकते हैं। ethers.js के साथ combined, आपके पास एक powerful toolkit है ताकि Web3 applications बना सकें जिन तक millions of users access कर सकते हैं।
आज ही अपना dApp building शुरू करें — MetaMask को integrate करें और अपने smart contracts को life में लाएं। Solingo के hands-on Web3 projects के साथ wallet integration practice करें ताकि full-stack blockchain development में master बन सकें।
अगले steps:
- Wallet connection के साथ एक simple dApp बनाएं
- Transaction history tracking को implement करें
- Multiple wallets (Coinbase Wallet, WalletConnect) के लिए support add करें
- EIP-2612 permits के साथ gasless transactions के बारे में सीखें