Detect if wallet is connected

What would be a good way to detect if a wallet (MetaMask mainly) is connected to a website, using web3?
What I would like to do is something I’ve seen in many sites, having a button that says “Connect” when the wallet is disconnected, and “Connected to 0x xxxx” when is connected.

I haven’t found a reliable way to do that, but obviously is possible because all sites has it.

Welcome to the forum @AlexS! Have you seen this package?

1 Like

No, I haven’t, I’ll give it a try, thank you!

1 Like

Ah no, this is not was I was looking for, maybe I didn’t explain myself correctly.
I can detect the wallet and obtain the provider. However, what I would like to do in a reliable way, is something like this:
Initially, the wallet is not connected and the button on the webpage says Connect
When I click on the Connect button, the wallet asks for permission and then the button changes to Connected and the account id:
image

What I would like to do, if I refresh the page or come back later, to detect that I’m connected and therefore show the button as connected already.
I’ve seen this behaviour in some websites, but even here in OpenZeppelin Defender doesn’t work exactly like that.

1 Like

Hm, I’m not sure how MetaMask works once the user comes back to the page. I would’ve assumed in that case the provider is already unlocked.

1 Like

I know Exactly what you are talking about and I am also looking for an answer. Some sites once you click the connect wallet button it is greyed out or replaced by an address then when you reload the page it already shows that you are connected. It is possible I am just not sure how to do it. Please post if you figure it out.

Hi! Using Ethers JS you can try to instantiate a Web3Provider object passing it window.ethereum and issue an eth_requestAccounts. This according to my tests triggers the MetaMask login popup if the user is not connected, and if not, it “works silently”. Then you can try to get the signer from the instantiated provider. If it returns an account, you render the “Connected to: …” thingy. If not, the Connect button.

const provider = new Web3Provider(wallet);
await provider.send('eth_requestAccounts', []);
const signer = await provider.getSigner(0);

if (signer === undefined) userIsNotConnected();
else userIsConnected();

The one thing that this doesn’t solve is that issuing the eth_requestAccounts to poke on the state of the connection will trigger the MM login popup, which might be too aggressive depending on how you’d like your app to behave.

3 Likes

Thanks Martín, yes, I found that what you describe is a solution to this problem, and I was going to post it later today.
Cheers!

1 Like