Bird
Raised Fist0
Blockchain / Solidityprogramming~20 mins

Connecting MetaMask wallet in Blockchain / Solidity - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
MetaMask Connection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output when MetaMask is not installed?
Consider this code snippet that tries to connect to MetaMask. What will it print if MetaMask is not installed in the browser?
Blockchain / Solidity
async function connectWallet() {
  if (typeof window.ethereum === 'undefined') {
    console.log('MetaMask is not installed');
    return;
  }
  try {
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    console.log('Connected account:', accounts[0]);
  } catch (error) {
    console.log('User rejected the connection');
  }
}

connectWallet();
AMetaMask is not installed
BTypeError: window.ethereum.request is not a function
CUser rejected the connection
DConnected account: 0x123...abc
Attempts:
2 left
💡 Hint
Check what happens if window.ethereum is undefined.
Predict Output
intermediate
2:00remaining
What happens if user rejects MetaMask connection request?
Given this code to connect MetaMask wallet, what will be printed if the user rejects the connection request?
Blockchain / Solidity
async function connectWallet() {
  if (!window.ethereum) {
    console.log('MetaMask not found');
    return;
  }
  try {
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    console.log('Connected:', accounts[0]);
  } catch (error) {
    console.log('User rejected the connection');
  }
}

connectWallet();
AMetaMask not found
BConnected: 0xabc123...
CUser rejected the connection
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint
What does the catch block do?
🔧 Debug
advanced
2:00remaining
Why does this MetaMask connection code fail with a TypeError?
Look at this code snippet. It throws a TypeError: window.ethereum.request is not a function. What is the cause?
Blockchain / Solidity
async function connect() {
  if (!window.ethereum) {
    console.log('No MetaMask');
    return;
  }
  try {
    const accounts = await window.ethereum.send('eth_requestAccounts');
    console.log('Account:', accounts[0]);
  } catch (e) {
    console.log('Error:', e.message);
  }
}

connect();
Awindow.ethereum.send is deprecated; use window.ethereum.request instead
Bwindow.ethereum is undefined, so request method is missing
CThe method 'eth_requestAccounts' is invalid
DMissing await keyword before window.ethereum.send
Attempts:
2 left
💡 Hint
Check the MetaMask API for the correct method to request accounts.
🧠 Conceptual
advanced
1:30remaining
What is the purpose of 'eth_requestAccounts' method in MetaMask?
In MetaMask integration, what does calling window.ethereum.request({ method: 'eth_requestAccounts' }) do?
AIt sends a transaction to transfer Ether from the user to the dApp
BIt disconnects the user's wallet from the dApp
CIt fetches the current balance of the user's wallet
DIt requests the user to connect their wallet and returns an array of their account addresses
Attempts:
2 left
💡 Hint
Think about what connecting a wallet means.
Predict Output
expert
3:00remaining
What is the output of this MetaMask connection code with event listener?
This code connects to MetaMask and listens for account changes. What will it print if the user switches to account '0xABC123' after connection?
Blockchain / Solidity
async function connectAndListen() {
  if (!window.ethereum) {
    console.log('MetaMask missing');
    return;
  }
  try {
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    console.log('Connected:', accounts[0]);
    window.ethereum.on('accountsChanged', (newAccounts) => {
      console.log('Account changed to:', newAccounts[0]);
    });
  } catch {
    console.log('Connection failed');
  }
}

connectAndListen();

// Simulate user switching account after 2 seconds
setTimeout(() => {
  window.ethereum.emit('accountsChanged', ['0xABC123']);
}, 2000);
A
Connected: 0xABC123
Account changed to: 0xOriginal
B
Connected: 0xOriginal
Account changed to: 0xABC123
CMetaMask missing
DConnection failed
Attempts:
2 left
💡 Hint
The event listener logs when accounts change after initial connection.

Practice

(1/5)
1. What does window.ethereum represent in a web page when MetaMask is installed?
easy
A. A browser setting to enable cookies
B. An object injected by MetaMask to interact with the Ethereum blockchain
C. A method to create a new Ethereum wallet
D. A function to send transactions automatically

Solution

  1. Step 1: Understand MetaMask injection

    MetaMask injects window.ethereum into the browser to allow web pages to communicate with the Ethereum blockchain.
  2. Step 2: Identify the role of window.ethereum

    This object provides methods to request accounts, send transactions, and listen to blockchain events.
  3. Final Answer:

    An object injected by MetaMask to interact with the Ethereum blockchain -> Option B
  4. Quick 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
A. window.ethereum.getAccounts()
B. window.ethereum.enable()
C. window.ethereum.request({ method: 'eth_requestAccounts' })
D. window.ethereum.connect()

Solution

  1. Step 1: Identify the current recommended method

    The modern and recommended way to request accounts is using window.ethereum.request with the method eth_requestAccounts.
  2. Step 2: Compare options

    window.ethereum.enable() (enable()) is deprecated. Options C and D are not valid MetaMask methods.
  3. Final Answer:

    window.ethereum.request({ method: 'eth_requestAccounts' }) -> Option C
  4. Quick 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
A. Connected: 0x123... (first account address)
B. Error: window.ethereum is undefined
C. No output
D. Error: User rejected the request.

Solution

  1. 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.
  2. Step 2: Identify the error message on rejection

    When user rejects, MetaMask throws an error with message like 'User rejected the request.'
  3. Final Answer:

    Error: User rejected the request. -> Option D
  4. Quick 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
A. Missing await before window.ethereum.request call
B. Incorrect method name, should be 'requestAccounts'
C. window.ethereum.request does not exist
D. accounts is not an array

Solution

  1. Step 1: Check the request call usage

    window.ethereum.request returns a Promise, so it must be awaited or handled with then().
  2. 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.
  3. Final Answer:

    Missing await before window.ethereum.request call -> Option A
  4. Quick 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
A. Correctly checks for MetaMask and handles connection and errors
B. Fails to check if window.ethereum exists before requesting accounts
C. Does not handle user rejection errors
D. Uses deprecated enable() method instead of request()

Solution

  1. Step 1: Check for MetaMask presence

    The code correctly checks if window.ethereum exists before trying to connect.
  2. Step 2: Handle connection and errors properly

    It uses try-catch to handle user rejection or other errors and logs appropriate messages.
  3. Final Answer:

    Correctly checks for MetaMask and handles connection and errors -> Option A
  4. Quick 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