11

I am currently trying to connect my React front-end to Metamask on Chrome.

When using the following method, I get that ethereum.enable() is deprecated:

if (window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    window.ethereum.enable();
}

To be more accurate, the complete warning is:

MetaMask: 'ethereum.enable()' is deprecated and may be removed in the future. Please use the 'eth_requestAccounts' RPC method instead.
For more information, see: https://eips.ethereum.org/EIPS/eip-1102

So I when to the documentation and updated that code to:

if (window.ethereum) {
    try {
        // Request account access if needed
        const accounts = await window.ethereum.send(
            "eth_requestAccounts"
        );
        setError(null);
    } catch (error) {
        setError("Unable to connect to Metamask");
    }
}

This way, I get the following warning:

MetaMask: 'ethereum.send(...)' is deprecated and may be removed in the future. Please use 'ethereum.sendAsync(...)' or 'ethereum.request(...)' instead.
For more information, see: https://eips.ethereum.org/EIPS/eip-1193

Subsidiary question: I still don't really understand why I need to set this async function call in a variable (accounts), so... If someone has an explanation, I'm taking it!


Anyway: after this warning, I went to the doc again and I saw that sendAsync is supposed to be deprecated as well... And I didn't find anything about ethereum.request.

TLDR: what is the current best practice to connect Metamask to a front-end, right now? Thanks!

Thanh-Quy Nguyen
  • 326
  • 1
  • 2
  • 11

1 Answers1

19

Now that window.web and ethereum.enable() are deprecated, the recommended way to connect to MetaMask is with ethereum.request(). The function takes an object with a JSON-RPC method (like eth_requestAccounts) and returns a Promise.

For example:

if (window.ethereum) {
  try {
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    setAccounts(accounts);
  } catch (error) {
    if (error.code === 4001) {
      // User rejected request
    }
setError(error);

} }

You can find full documentation here: https://docs.metamask.io/guide/ethereum-provider.html#basic-usage

Morten
  • 6,017
  • 2
  • 12
  • 26