我试图更好地理解web3,并尝试了以下几点:
<script type="text/javascript">
if (typeof web3 !== 'undefined') {
web3Provider = web3.currentProvider;
} else {
// If no injected web3 instance is detected, fall back to Ganache
web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
}
web3 = new Web3(web3Provider);
web3.eth.defaulAccount = web3.eth.accounts[0]
console.log("getBalance:")
const accounts = web3.eth.accounts
console.log("accounts", accounts)
const balance = web3.eth.getBalance(web3.eth.accounts[1])
console.log("balance", web3.fromWei(balance, "ether"))
</script>我正在后台运行ganache-cli,并期望得到一个帐户列表和account[0]的余额。
然而,我回来了:

正如您在上面看到的,我的accounts对象是空的,因此我得到了一个错误。基本上,我只想从ganache-cli加载一个帐户地址,并显示它的余额。
有什么建议吗?我的代码有什么问题?
谢谢你的回复!
发布于 2018-02-05 21:12:19
您应该使用web3.eth.getAccounts。大多数web3操作也是异步的,所以请确保await调用。
(async () => {
const accounts = await web3.eth.getAccounts();
console.log(accounts);
const balance = await web3.eth.getBalance(accounts[0]);
console.log("balance", web3.utils.fromWei(balance, "ether"));
})();发布于 2019-01-16 11:14:33
dApps现在必须通过调用提供者上的一个新方法来请求对用户帐户的访问: ethereum.enable()
这里有更多的细节,https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8
发布于 2018-10-08 06:43:47
也有同样的问题。使用web3.eth.getAccounts()
https://ethereum.stackexchange.com/questions/38651
复制相似问题