3

I am trying to write a function to get the ethereum balance of a wallet address via web3js. Problem is I am unable to make it work for some reason. Here is my code running in VSCode:

const testnet = 'https://ropsten.etherscan.io/';
const walletAddress = '0x8690F1feff62008A396B31c2C3f380bD0Ca6d8b8';

const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var balance = web3.eth.getBalance(walletAddress);

The wallet contains 0.98 ether on ropsten but for some reason its not returning when I call it from my code. What am I doing wrong?

9

The issue with your testnet url, https://ropsten.etherscan.io/ is not running eth client.

Find below code to connect ropsten node.

const testnet = 'https://ropsten.infura.io/';
const walletAddress = '0x8690F1feff62008A396B31c2C3f380bD0Ca6d8b8';

const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var balance = web3.eth.getBalance(walletAddress); //Will give value in.
balance = web3.toDecimal(balance);

I am getting value. Now balance will give as wei. Check web3 api method's for the same.

https://github.com/ethereum/wiki/wiki/JavaScript-API#web3towei

  • sorry about that, yes I tried infura but I was getting the same issue. I uninstalled web3 which was 1.0.0-beta and installed 0.14.0 and everything is working fine. seems to be an issue with the latest web3js. – Zaid Amir Feb 15 '18 at 13:03
  • 1
    that code will no longer work. getBalance() now returns a promise (at least in v1.0.0-beta.43) so you need to do getBalance(...).then(bal => { console.log(bal); }) and incidentally, to convert to decimals one now needs to do web3.utils.toDecimal() and if passing it a balance will make it puke "Error: Number can only safely store up to 53 bits" -- hopeless. after, what? 5 years, how long has ethereum been around? and the most basic functionality is still broken – ekkis Feb 9 at 19:29
1

You need to connect to an Ethereum node running on the Ropsten network. https://ropsten.etherscan.io is not such a node.

You can try Infura instead. They provide public Ethereum nodes. You should get an API key, but it works (perhaps with lower rate-limiting?) even without that:

const testnet = 'https://ropsten.infura.io';
0

balance = await web3.eth.getBalance(wallet_address);

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.