3

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: enter image description here 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!

1
  • What happens if you replace it with const accounts = web3.eth.getAccounts();? Commented Feb 5, 2018 at 20:39

5 Answers 5

5

You should be using web3.eth.getAccounts. Most web3 operations are also asynchronous so make sure you await the calls.

(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"));
})();
2

dApps must now request access to user accounts by calling a new method on the provider: ethereum.enable()

more details here https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8

1

Had the same issue. Use web3.eth.getAccounts()

0

You can also do this way:

   var defaultAccount = web3.eth.defaultAccount;
console.log(defaultAccount);

// set the default account
web3.eth.defaultAccount = '0x8888f1f195afa192cfee860698584c030f4c9db1';

According to https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethdefaultaccount

0

use await and let web3 load all the addresses before it produces the result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.