Connecting MetaMask wallet in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When connecting a MetaMask wallet, the program interacts with the user's browser extension to request access. We want to understand how the time needed to connect changes as the number of requests or users grows.
How does the connection process scale when repeated multiple times or for many users?
Analyze the time complexity of the following code snippet.
async function connectWallet() {
if (window.ethereum) {
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
return accounts[0];
} catch (error) {
throw new Error('User rejected connection');
}
} else {
throw new Error('MetaMask not installed');
}
}
This code asks MetaMask to connect and returns the first account if successful.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single asynchronous request to MetaMask extension.
- How many times: One request per connection attempt.
The connection process involves one request regardless of the number of accounts returned or users. If you connect once, it takes one request; if you connect 10 times, it takes 10 requests.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 connection attempts | 10 requests |
| 100 connection attempts | 100 requests |
| 1000 connection attempts | 1000 requests |
Pattern observation: The number of operations grows directly with the number of connection attempts.
Time Complexity: O(n)
This means the time to connect scales linearly with how many times you try to connect.
[X] Wrong: "Connecting once takes longer if the wallet has many accounts."
[OK] Correct: The connection request asks for all accounts at once, so the time depends mostly on the request itself, not the number of accounts.
Understanding how asynchronous requests scale helps you explain performance in real blockchain apps. This skill shows you can reason about user interactions and external calls clearly.
"What if the code requested account balances for each account after connecting? How would the time complexity change?"
Practice
window.ethereum represent in a web page when MetaMask is installed?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]
- Thinking window.ethereum is a function
- Confusing it with wallet creation
- Assuming it's a browser setting
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]
- Using deprecated enable() method
- Calling non-existent getAccounts() or connect()
- Not passing method as an object
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();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]
- Assuming accounts array is returned on rejection
- Not handling promise rejection
- Expecting no output on rejection
async function connectWallet() {
const accounts = window.ethereum.request('eth_requestAccounts');
console.log(accounts[0]);
}
connectWallet();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]
- Forgetting await on async calls
- Passing method as string instead of object
- Assuming request returns array directly
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();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]
- Not checking if MetaMask is installed
- Ignoring errors from user rejection
- Using deprecated methods
