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!
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityHello 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!
Here is my suggestions:
Just to clarify, all ERC20 tokens have the same set of methods (ERC20 protocol). Now, there are two ways to accomplish your task:
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)
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)
You want to use web3 balanceOf()
method.
Example: web3.eth.getBalance(address);
Links:
Web3 has been updated since @Vanja Dev's answer
var tokenInst = new web3.eth.Contract(tokenABI,tokenAddress);
tokenInst.methods.balanceOf('0x260c25f991171850f48889eb9d8aF11998D20c30').call().then(function (bal) {
console.log(bal);
})
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" }
});