简体   繁体   English

检查 web3 钱包是否已解锁

[英]Check if web3 wallet is unlocked

What is the best practice to see if metamask or other web3 wallets are unlocked with ethers.js ?查看 metamask 或其他 web3 钱包是否使用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.但它被 metamask 文档报告为实验方法,我想找到更好的方法。

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.我的实验发现listAccounts 返回一个字符串数组,如果钱包没有解锁,它返回一个空数组。

For MetaMask specifically, I know you can't have an account without having an address.特别是对于 MetaMask,我知道没有地址就无法拥有帐户。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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