[Ethereum] How to view custom token balance in ether wallet using web3

ethergo-ethereummyetherwalletweb3j

Hello I am newbie to cryptocurrency. I have created my erc20 custom token. Now, I want to create an API to view the balance(in my token as well as in ethers) using web3 and node js.Can someone please suggest how I can do that?

Thanks in advance!

Best Answer

Here is my suggestions:

ERC20 token balance

Just to clarify, all ERC20 tokens have the same set of methods (ERC20 protocol). Now, there are two ways to accomplish your task:

  1. use ERC20 balanceOf(address _owner) method

// Get the account balance of another account with address _owner

function balanceOf(address _owner) public constant returns (uint256 balance);

Example: first, create token instance

var tokenInst = web3.eth.contract(tokenABI).at(tokenAddress);

Then you can call methods of the token. For balance you should write the following:

tokenInst.balanceOf.call(address_to_check)
  1. use balances map if it is public.

// Balances for each account

mapping (address => uint256) balances;

Example is similar to previous: first, create token instance

var tokenInst = web3.eth.contract(tokenABI).at(tokenAddress);

Then you can call methods of the token. For balance you can also write the following:

tokenInst. balances.call(address_to_check)

ETH balance

You want to use web3 balanceOf() method.

Example: web3.eth.getBalance(address);

Links:

web3ethgetbalance