Exploring blockchain technology has been an exciting journey for me as a frontend developer. This new world of decentralized applications presents fascinating opportunities. Below, I'll share my learnings about querying Ethereum main coin and token balances using Node.js.
How to Query Ethereum (ETH) Main Coin Balance
Ethereum's native currency (ETH) can be queried directly using a public address through the getBalance() API method:
const baseValue = web3.eth.getBalance(address); // address = public keyThe returned baseValue is denominated in wei (the smallest Ethereum unit). To convert it to ether:
baseValue = web3.utils.fromWei(baseValue, "ether");Now baseValue shows the balance in ether units.
How to Query Token Balances
Token balance queries require:
- The token's contract address
- The contract ABI (Application Binary Interface)
First, create a contract instance:
const myContract = new web3.eth.Contract(contractAbi, contractAddress);Then query token information:
const tokenName = await myContract.methods.name().call();
const tokenSymbol = await myContract.methods.symbol().call();
const tokenBalance = await myContract.methods.balanceOf(address).call();
const tokenDecimals = await myContract.methods.decimals().call();Like ETH balances, token balances also return in wei format. Convert them using:
const formattedBalance = tokenBalance / (10 ** tokenDecimals);Key Considerations
- Always verify contract addresses
- Handle failed queries gracefully
- Consider gas fees for write operations
๐ Learn more about Web3.js integration
FAQ Section
Q: Why is my ETH balance showing in wei?
A: Ethereum uses wei for precision in calculations. Convert to ether for human-readable values.
Q: How do I find a token's contract ABI?
A: Check Etherscan or the token's official documentation.
Q: What's the difference between ETH and tokens?
A: ETH is Ethereum's native currency, while tokens are smart contracts built on top of Ethereum.
Q: Can I query balances without running a node?
A: Yes, using services like Infura or Alchemy as Web3 providers.
Remember to verify all contract addresses and ABIs before implementation. Happy coding in the Web3 space!