How to check if a web3 wallet is unlocked?

Viewed 1499

What is the best practice to see if metamask or other web3 wallets are unlocked with ethers.js?

I currently use this:

window.ethereum._metamask.isUnlocked()

But it is reported as experimental methods by the metamask documentation and I would like to find something better.

2 Answers

That's my own resolution if anyone need it :

isUnlocked$ = new BehaviorSubject<boolean>(false);

async isWalletUnlocked() {
      const web3Provider = new ethers.providers.Web3Provider(window.ethereum, 'any');
      const signer = await this.web3Provider.getSigner();
    
      signer
      .getAddress()
      .then((address: string) => {
        this.isUnlocked$.next(true);
      })
      .catch((err) => this.isUnlocked$.next(false));
}

What my experimentation found was that listAccounts returns an array of strings and if the wallet is not unlocked, it returns an empty array.

For MetaMask specifically, I know you can't have an account without having an address.

Therefore the function I came up with was:

async function isUnlocked() {
    const provider = new ethers.providers.Web3Provider(window.ethereum);

    let unlocked;

    try {
        const accounts = await provider.listAccounts();

        unlocked = accounts.length > 0;
    } catch (e) {
        unlocked = false;
    }

    return unlocked;
}
Related