[Ethereum] How to access metamask accounts when using Infura Websockets

dapp-developmentdappsinfura

I am making a dApp where in for login purpose I access metamask account to which user is logged in. I also have a back end server that listens to events emitted by the smart contract that updates data in an off-chain database.

Now, I plan to deploy my dApp to Rinkeby network for next level of testing. To listen to events on Rinkeby network I am using Infura websockets:

var web3 = new Web3("wss://rinkeby.infura.io/_ws");

But this has caused me problem. With the above web3 setting the dApp is unable to detect metamask (is locked or not) and the user account which is logged in.

I am stuck here as in I want to access the user account which is logged in Metamask and also want to use Infura Websockets to listen to events. But it looks like I can set only either of them as web3 provider.

Please suggest how can I circumvent this problem.

Best Answer

One approach I've used in the past is to just instantiate two Web3s. E.g.:

const web3 = new Web3(web3.currentProvider); // MetaMask
const web3EventReader = new Web3("wss://rinkeby.infura.io/ws");

Then use web3 for your typical MetaMask stuff and web3EventReader to listen to events.

(Side note: I changed /_ws to /ws, because I thought that's the proper URL.)

Related Topic