craig

1 min read - Posted 18 Dec 19

Retrieving an Ethereum Account Balance in Web3j

Balance at Current Block

To obtain the balance of an account in java with web3j at the current block, the following code snippet can be used:

//Connect to node.
//Defaults to http://localhost:8545
Web3j web3 = Web3j.build(new HttpService());

//Get balance result synchronously
EthGetBalance balanceResult = web3.ethGetBalance("0xF0f15Cedc719B5A55470877B0710d5c7816916b1", 
    DefaultBlockParameterName.LATEST).send();

//Obtain the BigInteger balance representation, in the wei unit.
BigInteger balanceInWei = balanceResult.getBalance();

Balance at a Specific Block

The below code snippet will obtain the account balance at block 300000:

Web3j web3 = Web3j.build(new HttpService());

EthGetBalance balanceResult = web3.ethGetBalance("0xF0f15Cedc719B5A55470877B0710d5c7816916b1", 
new DefaultBlockParameterNumber(300000)).send();

BigInteger balanceInWei = balanceResult.getBalance();

Balances are returned in the smallest denomination, called wei. To convert to other denominations, such as ether, see this cheetsheet article.

Created with Sketch.Content is"CC-BY-SA 4.0" licensed
Article On-chain
Article Author

Craig Williams

Software Developer @ Kauri / ConsenSys

19

3

2

0 Comments
Related Articles
Signing an Ethereum Transaction in Web3j

Web3j provides a bunch of helper classes to enable you to create and sign a transaction within your ethereum java code. The transaction creation process involve

Sending an Ether Transfer Transaction from One Account to Another in Web3j

To transfer ether from one account to another, a transaction must be sent to the ethereum network. The easiest way to achieve this within your java application