Bug Tracking: Solana Balance Tracker

As a developer, identifying and fixing bugs is essential to maintaining a high-quality and reliable project. In this article, we address the issue of building the Solana balance tracker, which has proven to be quite challenging.
Problem: Partially fixed code
The provided code is incomplete, and upon closer inspection, it appears that the balance tracking functionality is incomplete or partially applicable. Specific issues with the code include:
- Print SOL Balance: The code only prints the SOL balance, rather than including all wallet balances.
- Token Support: The code does not support Memecoins/SPL tokens.
Here’s how you can rewrite the code to fix the issues and create a more comprehensive balance tracker.
const { ChainID, Wallet } = require('@solana/web3.js');
// Enter the chain ID
const CHAIN_ID = ChainId.SOL;
// Create an instance of the Solana API
const api = new Web3.providers.HttpProvider('
const connection = await api.connect();
// Function to retrieve wallet balances
async function getWalletBalances() {
const wallets = await Wallet.list();
return wallets.map((wallet) => ({
pubkey: wallet.pkey,
balance: await Wallet.getBalance(wallet.pkey),
}));
}
async function getSolBalance() {
const solAddress = 'SOL';
const address = connection.getAccounts()[0];
if (!address) {
throw new Error ('No SOL address found in wallets');
}
return await api.fetchAccount(address, { kind: 'balance' });
}
// Function to retrieve Memecoins/SPL token balances
async function getTokenBalances(tokenAddress) {
const tokens = await Wallet.list();
return tokens.map((token) => ({
pubkey: token.pkey,
balance: token.balance,
}));
}
async function main() {
// Get wallet balance
const wallets = await getWalletBalances();
// Print SOL balance
console.log('Debit balance:');
for (const { pubkey, balance } from wallets) {
if (pubkey === 'SOL') {
console.log( - ${balance.toString()} SOL);
}
}
// Get Memecoins/SPL token balances
const tokens = await getTokenBalances('MEM');
for (const { pubkey, balance } of tokens) {
if (pubkey === 'MEM') {
console.log(- ${balance.toString()} MEM);
}
}
}
main ();
Solution
To fix bugs and create a comprehensive Solana balance tracker, we have made the following changes:
- We added support for Memecoins/SPL tokens.
- The « getWalletBalances » function now returns an array of objects with wallet balances in addition to the SOL balance.
- The « getSolBalance » function checks if a given Solana address exists and retrieves its balance using the « api.fetchAccount » method.
- We created a new « main » function that handles the balance tracking process.
Conclusion
By addressing these issues, we have created a more comprehensive Solana balance tracker that includes all wallet balances, including Memecoins/SPL tokens. This updated code can now be used as a starting point for developing applications and creating additional functionality.