Connecting MetaMask lets your website talk to your Ethereum wallet. This helps you use blockchain features like sending money or checking your balance.
Connecting MetaMask wallet in Blockchain / Solidity
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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!'); } }
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();
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.
Practice
1. What does
window.ethereum represent in a web page when MetaMask is installed?easy
Solution
Step 1: Understand MetaMask injection
MetaMask injectswindow.ethereuminto the browser to allow web pages to communicate with the Ethereum blockchain.Step 2: Identify the role of
This object provides methods to request accounts, send transactions, and listen to blockchain events.window.ethereumFinal Answer:
An object injected by MetaMask to interact with the Ethereum blockchain -> Option BQuick Check:
window.ethereum = MetaMask's injected object [OK]
Hint: Remember: window.ethereum is MetaMask's bridge to Ethereum [OK]
Common Mistakes:
- Thinking window.ethereum is a function
- Confusing it with wallet creation
- Assuming it's a browser setting
2. Which of the following is the correct way to request account access from MetaMask in JavaScript?
easy
Solution
Step 1: Identify the current recommended method
The modern and recommended way to request accounts is usingwindow.ethereum.requestwith the methodeth_requestAccounts.Step 2: Compare options
window.ethereum.enable() (enable()) is deprecated. Options C and D are not valid MetaMask methods.Final Answer:
window.ethereum.request({ method: 'eth_requestAccounts' }) -> Option CQuick Check:
Use request with eth_requestAccounts to connect [OK]
Hint: Use window.ethereum.request with 'eth_requestAccounts' [OK]
Common Mistakes:
- Using deprecated enable() method
- Calling non-existent getAccounts() or connect()
- Not passing method as an object
3. What will the following code output if the user rejects the MetaMask connection request?
async function connect() {
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log('Connected:', accounts[0]);
} catch (error) {
console.log('Error:', error.message);
}
}
connect();medium
Solution
Step 1: Understand the try-catch block
The code tries to request accounts. If the user rejects, the promise rejects and control goes to catch block.Step 2: Identify the error message on rejection
When user rejects, MetaMask throws an error with message like 'User rejected the request.'Final Answer:
Error: User rejected the request. -> Option DQuick Check:
User rejection triggers catch with error message [OK]
Hint: User rejection triggers catch block with error message [OK]
Common Mistakes:
- Assuming accounts array is returned on rejection
- Not handling promise rejection
- Expecting no output on rejection
4. Identify the error in this code snippet that tries to connect MetaMask wallet:
async function connectWallet() {
const accounts = window.ethereum.request('eth_requestAccounts');
console.log(accounts[0]);
}
connectWallet();medium
Solution
Step 1: Check the request call usage
window.ethereum.request returns a Promise, so it must be awaited or handled with then().Step 2: Identify missing await
The code calls request without await, so accounts is a Promise, not an array, causing accounts[0] to be undefined.Final Answer:
Missing await before window.ethereum.request call -> Option AQuick Check:
Async calls need await to get resolved value [OK]
Hint: Always await async calls like window.ethereum.request [OK]
Common Mistakes:
- Forgetting await on async calls
- Passing method as string instead of object
- Assuming request returns array directly
5. You want to connect a MetaMask wallet and display the connected account or an error message if MetaMask is not installed. Which code snippet correctly handles both cases?
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('Connection error:', error.message);
}
} else {
console.log('MetaMask is not installed');
}
}
connect();hard
Solution
Step 1: Check for MetaMask presence
The code correctly checks ifwindow.ethereumexists before trying to connect.Step 2: Handle connection and errors properly
It uses try-catch to handle user rejection or other errors and logs appropriate messages.Final Answer:
Correctly checks for MetaMask and handles connection and errors -> Option AQuick Check:
Check existence + try-catch = robust connection [OK]
Hint: Always check window.ethereum before connecting [OK]
Common Mistakes:
- Not checking if MetaMask is installed
- Ignoring errors from user rejection
- Using deprecated methods
