【问题标题】:How to check if a web3 wallet is unlocked?如何检查 web3 钱包是否已解锁?
【发布时间】:2021-09-01 13:47:26
【问题描述】:

查看 metamask 或其他 web3 钱包是否使用 ethers.js 解锁的最佳做法是什么?

我目前使用这个:

window.ethereum._metamask.isUnlocked()

但元掩码文档将其报告为实验方法,我想找到更好的方法。

【问题讨论】:

    标签: javascript typescript ethereum web3 metamask


    【解决方案1】:

    如果有人需要,那是我自己的解决方案:

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

    【讨论】:

      【解决方案2】:

      我的实验发现是listAccounts returns an array of strings,如果钱包没有解锁,它会返回一个空数组。

      特别是对于 MetaMask,我知道没有地址就无法拥有帐户。

      因此我想出的功能是:

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

      【讨论】:

        猜你喜欢
        • 2021-09-29
        • 2014-02-28
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 2022-11-11
        • 1970-01-01
        • 2022-06-27
        • 2011-06-13
        相关资源
        最近更新 更多