如何从新的 MetaMask ethereum API 中获取帐户列表?

How to get a list of accounts from the new MetaMask ethereum API?

MetaMask 最近更改了他们注入 API 的方式,不再暴露 window.web3 对象。

MetaMask no longer injects web3. For details, see: https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3

Uncaught TypeError: web3.eth is undefined

如何从新的 MetaMask 中获取帐户列表 ethereum API?

您可以使用MetaMask或其他钱包注入的window.ethereum对象。

if (typeof window.ethereum !== 'undefined') {
  // connects to MetaMask
  const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
} else {
  // tell the user to install an `ethereum` provider extension
}

这使用新的 API 在提供程序上调用异步以太坊请求。它接受大部分以太坊 APIs 并且在实现中非常通用。