Complete the code to check if MetaMask is installed.
if (typeof window.ethereum [1] 'undefined') { console.log('MetaMask is installed!'); } else { console.log('Please install MetaMask.'); }
We use !== 'undefined' to check if MetaMask (window.ethereum) exists.
Complete the code to request account access from MetaMask.
const accounts = await window.ethereum.request({ method: '[1]' });The method 'eth_requestAccounts' asks MetaMask to connect and provide accounts.
Fix the error in the code to handle MetaMask connection errors.
try { const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); console.log('Connected account:', [1]); } catch (error) { console.error('User rejected the request'); }
The accounts variable is an array; the first account is accounts[0].
Fill both blanks to listen for account changes and log the new account.
window.ethereum.on('[1]', (accounts) => { console.log('Account changed to:', [2]); });
The event 'accountsChanged' fires when user switches accounts. The new account is accounts[0].
Fill all three blanks to create a function that connects MetaMask and returns the first account.
async function connectMetaMask() {
if (typeof window.ethereum [1] 'undefined') {
try {
const accounts = await window.ethereum.request({ method: '[2]' });
return [3];
} catch (error) {
console.error('Connection failed');
return null;
}
} else {
console.log('MetaMask not installed');
return null;
}
}Check if window.ethereum is not undefined, request accounts with 'eth_requestAccounts', and return the first account.