[Ethereum] Cant get address balance using web3js

balancesweb3js

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?

Best Answer

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

Related Topic