页面刷新后如何检查Metamask是否已连接

Дан*_*еев 17 javascript ethereum web3js metamask

我的 dApp 必须连接到 MetaMask。文档中有两种粗鲁的解决方案:让用户每次手动单击连接 btn 或在页面加载后弹出连接确认。我想实现唯一方便的解决方案:第一次用户通过单击连接 btn 并与 MetaMask 弹出窗口交互来手动连接,然后我的 dApp 检测到连接仍然建立并使用此连接。我找不到解决方案,但我在其他 dApp 中看到了这个(例如捕获以太)我使用:

import detectEthereumProvider from '@metamask/detect-provider';

const provider = await detectEthereumProvider(); 

if (provider) {
  connect(provider)
} else {
  // kind of "Install the MetaMask please!"
}

function connect(provider) {
  // How to check if the connection is here
  if (//connection established) {
    // Show the user connected account address
  } else {
    // Connect
    provider.request({ method: "eth_requestAccounts" })
      .then // some logic
  }
}
Run Code Online (Sandbox Code Playgroud)

Дан*_*еев 20

我终于找到了一个可能的解决方案,结果证明它应该是简单的。以太坊 JSON-RPC 中有一个eth_accounts方法,它允许我们请求可用帐户,而无需实际请求它们。这样我们就可以检查metamask是否仍然连接(如果有任何帐户)并避免自动请求或每次都需要手动单击“连接”。简单的示例实现可以是:

// detect provider using @metamask/detect-provider
detectEthereumProvider().then((provider) => {
  if (provider && provider.isMetaMask) {
    provider.on('accountsChanged', handleAccountsChanged);
    // connect btn is initially disabled
    $('#connect-btn').addEventListener('click', connect);
    checkConnection();
  } else {
    console.log('Please install MetaMask!');
  }
});

function connect() {
  ethereum
    .request({ method: 'eth_requestAccounts' })
    .then(handleAccountsChanged)
    .catch((err) => {
      if (err.code === 4001) {
        console.log('Please connect to MetaMask.');
      } else {
        console.error(err);
      }
    });
}

function checkConnection() {
  ethereum.request({ method: 'eth_accounts' }).then(handleAccountsChanged).catch(console.error);
}

function handleAccountsChanged(accounts) {
  console.log(accounts);

  if (accounts.length === 0) {
    $('#connection-status').innerText = "You're not connected to MetaMask";
    $('#connect-btn').disabled = false;
  } else if (accounts[0] !== currentAccount) {
    currentAccount = accounts[0];
    $('#connection-status').innerText = `Address: ${currentAccount}`;
    $('#connect-btn').disabled = true;
  }
}
Run Code Online (Sandbox Code Playgroud)