[英]Check if web3 wallet is unlocked
查看 metamask 或其他 web3 錢包是否使用ethers.js解鎖的最佳實踐是什么?
我目前使用這個:
window.ethereum._metamask.isUnlocked()
但它被 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 返回一個字符串數組,如果錢包沒有解鎖,它返回一個空數組。
特別是對於 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.