8

I do not see anything in creating accounts and retrieving ether balance in web3j's documentation, I wonder if it is possible.

TerenceT
  • 105
  • 1
  • 1
  • 7

3 Answers3

12

The "ethGetBalance" method will return the balance of any given account. Pls see example below:

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

// send asynchronous requests to get balance
EthGetBalance ethGetBalance = web3
  .ethGetBalance("0xAccountAddress", DefaultBlockParameterName.LATEST)
  .sendAsync()
  .get();

BigInteger wei = ethGetBalance.getBalance();
3

You can use CURL command or use request module inside your code to call create account API -

CURL command for your reference:

curl -X POST --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' http://localhost:8545

Also, you must run the geth node with the "personal" api enabled to make this method available:

geth --rpc --rpcapi "personal,eth,web3"

To check account balance using web3js, use following command -

web3.eth.getBalance('account address hash in quotes')

Hope this helps.

Sanchit
  • 3,482
  • 1
  • 12
  • 29
0

This is how you do it kotlin web3j. I'm using Goerli infura


val web3j = Web3j.build(HttpService("https://goerli.infura.io/v3/YOUR_GOERLI_INFURA_KEY"))

var mBalance: EthGetBalance = web3j.ethGetBalance(walletAddress, DefaultBlockParameterName.LATEST).sendAsync() .get()

val unScaledBalance = mBalance.balance

val scaledBalance = BigDecimal(unScaledBalance).divide( BigDecimal(1000000000000000000L), 18, RoundingMode.HALF_UP )

    Log.d(TAG, "checkAddressBalance: ScaledBalance: $scaledBalance")

Jeremy Then
  • 4,599
  • 3
  • 5
  • 28
Shoaib Kakal
  • 71
  • 12