Yul*_*ian 4 javascript ethereum web3js metamask ethers.js
我使用Ethers.js允许用户将他们的 Metamask 钱包连接到我的应用程序。这是我的代码:
import { ethers } from "ethers"
async function connect() {
const provider = new ethers.providers.Web3Provider(window.ethereum, "any")
await provider.send("eth_requestAccounts", [])
const signer = provider.getSigner()
const address = await signer.getAddress()
// Always prints the address that I first connected with
console.log(address)
}
Run Code Online (Sandbox Code Playgroud)
问题是,一旦我连接了我的一个 Metamask 帐户,即使我切换到另一个 Metamask 帐户并尝试连接它,我也总是会得到它的钱包地址。
这是为什么?我应该如何解决这个问题?
要获取当前帐户,请获取0以下地址eth_requestAccounts:
let accounts = await provider.send("eth_requestAccounts", []);
let account = accounts[0];
Run Code Online (Sandbox Code Playgroud)
要自动更新,请监听该accountsChanged事件:
provider.on('accountsChanged', function (accounts) {
account = accounts[0];
});
Run Code Online (Sandbox Code Playgroud)
代码:
import { ethers } from "ethers"
async function connect() {
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
let accounts = await provider.send("eth_requestAccounts", []);
let account = accounts[0];
provider.on('accountsChanged', function (accounts) {
account = accounts[0];
console.log(address); // Print new address
});
const signer = provider.getSigner();
const address = await signer.getAddress();
console.log(address);
}
Run Code Online (Sandbox Code Playgroud)
我认为问题在于切换帐户时您需要重新实例化签名者和提供者。
此外,如果我正确阅读文档,最好在eth_requestAccounts成功调用后实例化签名者。
| 归档时间: |
|
| 查看次数: |
7705 次 |
| 最近记录: |