0
0
Blockchain / Solidityprogramming~5 mins

Connecting MetaMask wallet in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Connecting MetaMask lets your website talk to your Ethereum wallet. This helps you use blockchain features like sending money or checking your balance.

When you want users to log in with their Ethereum wallet on your website.
When you need to read the user's Ethereum address to personalize their experience.
When you want to let users send transactions or interact with smart contracts.
When building decentralized apps (dApps) that require blockchain access.
When you want to check if the user has MetaMask installed and ready.
Syntax
Blockchain / Solidity
async function connectMetaMask() {
  if (window.ethereum) {
    try {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      return accounts[0];
    } catch (error) {
      console.error('User rejected connection');
    }
  } else {
    console.error('MetaMask not installed');
  }
}

window.ethereum is the object MetaMask injects into your browser.

The method eth_requestAccounts asks the user to connect their wallet.

Examples
This example connects and logs the first account address.
Blockchain / Solidity
async function connect() {
  if (window.ethereum) {
    try {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Connected account:', accounts[0]);
    } catch (error) {
      console.log('User rejected connection');
    }
  } else {
    alert('Please install MetaMask!');
  }
}
This uses promises instead of async/await to connect MetaMask.
Blockchain / Solidity
window.ethereum.request({ method: 'eth_requestAccounts' })
  .then(accounts => console.log('Account:', accounts[0]))
  .catch(() => console.log('Connection rejected'));
Sample Program

This program tries to connect to MetaMask and prints the connected account or an error message.

Blockchain / Solidity
async function connectMetaMask() {
  if (window.ethereum) {
    try {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Connected account:', accounts[0]);
    } catch (error) {
      console.log('User rejected connection');
    }
  } else {
    console.log('MetaMask not installed');
  }
}

connectMetaMask();
OutputSuccess
Important Notes

Users must approve connection in MetaMask popup.

If MetaMask is not installed, your site should guide users to install it.

Always handle errors like user rejection gracefully.

Summary

MetaMask injects window.ethereum to interact with Ethereum.

Use eth_requestAccounts to ask users to connect their wallet.

Handle cases when MetaMask is missing or user rejects connection.