I am trying to understand web3 better and tried out the following snipped:
<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>
I am running ganache-cli
in the background and was expecting to get back a list of accounts and the balance of the account[0]
.
However, I get back:
As you can see above my accounts
object is empty and therefore I get an error.
Basically I just want to load one account address from the ganache-cli and display its balance.
Any suggestions what is wrong with my code?
I appreciate your replies!
const accounts = web3.eth.getAccounts();
?