【发布时间】:2021-09-01 13:47:26
【问题描述】:
查看 metamask 或其他 web3 钱包是否使用 ethers.js 解锁的最佳做法是什么?
我目前使用这个:
window.ethereum._metamask.isUnlocked()
但元掩码文档将其报告为实验方法,我想找到更好的方法。
【问题讨论】:
标签: javascript typescript ethereum web3 metamask
查看 metamask 或其他 web3 钱包是否使用 ethers.js 解锁的最佳做法是什么?
我目前使用这个:
window.ethereum._metamask.isUnlocked()
但元掩码文档将其报告为实验方法,我想找到更好的方法。
【问题讨论】:
标签: javascript typescript ethereum web3 metamask
如果有人需要,那是我自己的解决方案:
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));
}
【讨论】:
我的实验发现是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;
}
【讨论】: