0

I'm trying to perform a simple balance check, but the code inside web3.eth.getAccounts doesn't run.

I'm trying to get web3 from the instance injected by Metamask.

myWeb3.eth.getAccounts(function(err, accounts) {
  console.log("why doesn't this run? 🤔");
  myWeb3.eth.getBalance(accounts[0], function(err, balance) {
    render("Your balance is " + window.web3.fromWei(balance, "ether"));
  });
});

https://codesandbox.io/s/q3m178xnl9 src/index.js:26

I'm not really a developer, so it's possible this is something silly on my end.

Thanks a lot ❤️

0

You should try starting with more simple, easy to read code. Especially when trying to get others to help you debug, you should be providing to us a minimal, complete, and verifiable example.

Here is a better starting point: https://jsfiddle.net/87jhmodc/8/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.min.js"></script>
    <script type="text/javascript">
      window.addEventListener('load', function() {
        if (typeof web3 !== 'undefined') {
          console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
          window.web3 = new Web3(web3.currentProvider);
        } else {
          console.log('No Web3 Detected... get Metamask');
        }
      })

      function getBalance() {
        var wei, balance
        try {
          web3.eth.getAccounts(function(err, accounts) {
            web3.eth.getBalance(accounts[0], function(error, wei) {
              if (!error) {
                var balance = web3.fromWei(wei, 'ether');
                document.getElementById("output").innerHTML = balance + " ETH";
              }
            })
          });
        } catch (err) {
          document.getElementById("output").innerHTML = err;
        }
      }

    </script>
  </head>

  <body>
    <button type="button" onClick="getBalance();">Get Balance</button>
    <br />
    <br />
    <div id="output"></div>
  </body>

</html>

Take a look here too: Ethereum and Web3.js “Hello World”: Get the ETH Balance of an Ethereum Address

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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