MetaMask Error – Resolving RPC Error: The Requested Account and/or Method Has Not Been Authorized by the User

ethereumjsmetamaskweb3js

I'm following the tutorial on https://www.toptal.com/ethereum/one-click-login-flows-a-metamask-tutorial#how-the-login-flow-works.

One of the sections show an example of prompting the user's Metamask to sign a piece of data using the following in the console.

web3.personal.sign(web3.fromUtf8("Hello from Toptal!"), web3.eth.coinbase, console.log);

However, in newer versions of MetaMask it doesn't inject the web3 library anymore, only window.ethereum is available. So instead I tried using the following.

try {
  let myEoa = await ethereum.request({method: 'eth_coinbase'});
  const transactionHash = await ethereum.request({
    method: 'personal_sign',
    params: [myEoa, 'Hello World'
    ],
  });
  // Handle the result
  console.log(transactionHash);
} catch (error) {
  console.error(error);
}

This however doesn't trigger the MetaMask sign message pops up and returns an error message in the console directly, does anyone know why is that and how to trigger the popup?

MetaMask - RPC Error: The requested account and/or method has not been authorized by the user. {code: 4100, message: 'The requested account and/or method has not been authorized by the user.'}

Best Answer

Before you make any requests to metamask, you need to first connect to metamask wallet and get the accounts that user authorizes.

You can use this snippet

const accounts = await ethereum.request({
    method: 'eth_requestAccounts',
  });