简体   繁体   中英

Check if web3 wallet is unlocked

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM