Web3.js – How to Connect DAPP to MetaMask If Coinbase Wallet Injects Another Ethereum Provider

ethereum-wallet-dappweb3js

I am facing the following issue when trying to connect my DApp to Metamask:

Normally, Metamask injects ethereum provider authomatically and we just call Web3(window.ethereum) to instantiate the library.

Now, my problem is that having also installed Coinbase Wallet as a browser extension, it seems it is injecting also an ethereum provider, and now I have 2 providers and the selected one by default seem to be the Coinbase one. When I console.log window.ethereum, I am getting the folowing:

window ethereum 
 u {_events: {…}, _eventsCount: 0, _maxListeners: undefined, providers: Array(2), 
  selectedProvider: w, …}
  enable: ƒ ()
  overrideIsMetaMask: true
  providers: (2) [w, Proxy]
  request: ƒ ()
  selectedProvider: w {_events: {…}, _eventsCount: 4, _maxListeners: undefined, 
  _filterPolyfill: e.FilterPolyfill, _subscriptionManager: e.SubscriptionManager, …}
  send: ƒ ()
  sendAsync: ƒ ()
  _events: {}
  _eventsCount: 0
  _maxListeners: undefined
  chainId: (...)
  isMetaMask: (...)
  networkVersion: (...)
  [[Prototype]]: o

As you can see, as selectedProvider I am getting w, while actually Metamask is the other one.
In the end, what I am trying to achieve is creating one button to connect to Metamask and another to connect to Coinbase Wallet, but even using web3-react, both buttons are connecting to Coinbase Wallet.

Best Answer

In your case you need to get specific provider in window.ethereum:

const metamaskProvider = window.ethereum.providers.find((provider) => provider.isMetaMask);
Related Topic