How do I get the balance of an account in Ethereum?
Asked Answered
E

5

64

How can I programmatically discover how much ETH is in a given account on the Ethereum blockchain?

Elizbeth answered 31/8, 2015 at 13:50 Comment(0)
E
79

On the Web:

(Not programmatic, but for completeness...) If you just want to get the balance of an account or contract, you can visit http://etherchain.org or http://etherscan.io.

From the geth, eth, pyeth consoles:

Using the Javascript API, (which is what the geth, eth and pyeth consoles use), you can get the balance of an account with the following:

web3.fromWei(eth.getBalance(eth.coinbase)); 

"web3" is the Ethereum-compatible Javascript library web3.js.

"eth" is actually a shorthand for "web3.eth" (automatically available in geth). So, really, the above should be written:

web3.fromWei(web3.eth.getBalance(web3.eth.coinbase));

"web3.eth.coinbase" is the default account for your console session. You can plug in other values for it, if you like. All account balances are open in Ethereum. Ex, if you have multiple accounts:

web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]));
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]));
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[2]));

or

web3.fromWei(web3.eth.getBalance('0x2910543af39aba0cd09dbb2d50200b3e800a63d2'));

EDIT: Here's a handy script for listing the balances of all of your accounts:

function checkAllBalances() { var i =0; eth.accounts.forEach( function(e){ console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " + web3.fromWei(eth.getBalance(e), "ether") + " ether"); i++; })}; checkAllBalances();

Inside Contracts:

Inside contracts, Solidity provides a simple way to get balances. Every address has a .balance property, which returns the value in wei. Sample contract:

contract ownerbalancereturner {

    address owner;

    function ownerbalancereturner() public {
        owner = msg.sender; 
    }

    function getOwnerBalance() constant returns (uint) {
        return owner.balance;
    }
}
Elizbeth answered 31/8, 2015 at 14:10 Comment(3)
Can I recommend that your script for listing balances can be much simpler: eth.accounts.forEach( function(e, i){ console.log(" eth.accounts["+i+"]: " + e + " \tbalance: " + web3.fromWei(eth.getBalance(e), "ether") + " ether") })Folder
eth.getBalance() receives 2 parameters, not 1, what happens when you only supply one? what's the default for the second one?Railway
web3.fromWei is not a functionHellenistic
U
4

From the docs, (check out the link for variations)

web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> "1000000000000"
Underbody answered 14/2, 2021 at 20:42 Comment(0)
S
2

For the new release of the web3 API:

The latest version of web3 API (vers. beta 1.xx) uses promises (asynchronous, like callback). Dokumentation: web3 beta 1.xx

Hence it is a Promise and returns String for the given address in wei.

I am on Linux (openSUSE), geth 1.7.3, Rinkeby Ethereum testnet, using Meteor 1.6.1, and got it to work the following way connecting via IPC Provider to my geth node:

// serverside js file

import Web3 from 'web3';

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  var net = require('net');
  var web3 = new Web3('/home/xxYourHomeFolderxx/.ethereum/geth.ipc', net);
};

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

  web3.eth.coinbase = '0x123..............';

  web3.eth.getAccounts(function(err, acc) {
    _.each(acc, function(e) {
      web3.eth.getBalance(e, function (error, result) {
        if (!error) {
          console.log(e + ': ' + result);
        };
      });
    });
  });
Saintly answered 13/1, 2018 at 0:32 Comment(2)
those using nodejs (I'm on v11.5.0) won't make this work because import isn't supported. so you'll need to do const Web3 = require('web3'); insteadAcaroid
also, the balance will be returned in wei to it needs to be converted with .fromWei()Acaroid
A
1

Ethers.js

Using the Ethers.js JavaScript library, you can get an account's balance with provider.getBalance().

Here's a simple example (using Infura node or similar):

const provider =
    new ethers.providers.WebSocketProvider('wss://mainnet.infura.io/ws/v3/<your_id>');

async function checkBalance() {
    balance = await provider.getBalance('0x2910543af39aba0cd09dbb2d50200b3e800a63d2');
    console.log(ethers.utils.formatEther(balance));
}

checkBalance();
Area answered 22/4, 2022 at 3:37 Comment(0)
O
0

The 'for-each' loop works, but also a very short and simple way to get the balance is simply adding the await for the function:

var bal = await web3.eth.getBalance(accounts[0]);

or if you want to display it directly:

console.log('balance = : ', await web3.eth.getBalance(accounts[0]));
Omsk answered 29/9, 2020 at 13:2 Comment(2)
when i run this i get Uncaught SyntaxError: missing ) after argument listIndestructible
SyntaxError: await is only valid in async functionHellenistic

© 2022 - 2024 — McMap. All rights reserved.