2

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!

4

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

0

You can do this with any node, no external API or multiple calls needed, with the help of a smart contract. I just recently wrote a smart contract and library for this, and put it into an NPM package. You can check it out here: https://www.npmjs.com/package/eth-balance-checker

The call looks like this:

import Web3 from 'web3';
import { getAddressBalances } from 'eth-balance-checker/lib/web3';

const web3 = new Web3(...);
const address = '0x123...';
const tokens = ['0x0', '0x456...'];
getAddressBalances(web3, address, tokens).then(balances => {
  console.log(balances); // { "0x0": "100", "0x456...": "200" }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.