Setup a Token Balance Checker on Solana
This guide will help you set up and use a script to fetch the token balance of a user wallet. The script fetches token balances (e.g., BONK) in both Lamports and UI units. The UI balance is useful for checking against human-readable thresholds, such as 1,000,000 tokens.
Pre-requisites
Ensure Node.js and npm (Node Package Manager) are installed on your system. You can verify the installation by running the following commands:
node -v
npm -v
Installation
Step 1: Install ts-node
Globally
ts-node
is a TypeScript execution environment for node. Install it globally using npm:
npm install -g ts-node
Step 2: Install Required Dependencies
Run the following command to install the necessary libraries:
npm install @metaplex-foundation/mpl-token-metadata @metaplex-foundation/mpl-toolbox @metaplex-foundation/umi @metaplex-foundation/umi-bundle-defaults
Step 3: Install Development Dependency
Install TypeScript as a development dependency:
npm install --save-dev typescript
Script Setup
Create a file named getTokenBalance.ts
and paste the following code snippet into it:
import { mplTokenMetadata } from "@metaplex-foundation/mpl-token-metadata";
import {
findAssociatedTokenPda,
safeFetchMint,
safeFetchToken,
} from "@metaplex-foundation/mpl-toolbox";
import { publicKey } from "@metaplex-foundation/umi";
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
const getTokenbalance = async (
userPublicKeyString: string, // USER WALLET ADDRESS
mintPublicKeyString: string, // TOKEN MINT
) => {
try {
// Get RPC from Helius or any other RPC provider of your choice
const endpoint = "ADD YOUR RPC HERE";
const umi = createUmi(endpoint).use(mplTokenMetadata());
const userPublicKey = publicKey(userPublicKeyString);
const mint = publicKey(mintPublicKeyString);
const associatedTokenAccount = findAssociatedTokenPda(umi, {
mint,
owner: userPublicKey,
});
const mintData = await safeFetchMint(umi, mint);
const userPublicKeyData = await safeFetchToken(
umi,
associatedTokenAccount[0]
);
const balanceInLamports = userPublicKeyData?.amount;
let uiBalance = BigInt(0);
if (balanceInLamports && mintData) {
uiBalance = balanceInLamports / BigInt(10 ** mintData?.decimals);
} else {
// Handle cases where balance or mint data is not available
console.error("Balance or mint data not available.");
}
// LAMPORTS AMOUNT
console.log(balanceInLamports);
// UI AMOUNT
console.log(uiBalance);
return {
balanceInLamports,
uiBalance
};
} catch (error) {
console.error(error);
}
};
Usage
The getTokenbalance
function fetches the token balance of a given user wallet address and token mint. It returns the balance in both Lamports and UI units.
Parameters
userPublicKeyString
: The public key of the user wallet.mintPublicKeyString
: The public key of the token mint.
Example
(async () => {
const result = await getTokenbalance(
"USER_WALLET_PUBLIC_KEY", // Replace with actual user wallet public key
"TOKEN_MINT_PUBLIC_KEY" // Replace with actual token mint public key
);
if (result) {
const { balanceInLamports, uiBalance } = result;
// Check if the user has 1,000,000 BONK
const threshold = BigInt(1_000_000);
if (uiBalance > threshold) {
console.log("User has more than 1,000,000 BONK tokens.");
} else {
console.log("User has less than 1,000,000 BONK tokens.");
}
}
})();
Notes
-
Ensure you replace "ADD YOUR RPC HERE" with the endpoint of your chosen RPC provider.
-
Adjust the user wallet public key and token mint public key according to your requirements.
This script provides a basic example of fetching token balances using the Metaplex Foundation's libraries. You can extend or modify it to suit your specific use case.
Next Steps: Setting Up Onchain API Task App to verify user task completions
Now that you have set up the token balance checker and have your endpoint, you can use this to set up an Onchain API Task App (opens in a new tab) to verify user task completions on the Solana blockchain.
This will allow you to automate the verification process and ensure that users are rewarded accurately based on their token balances.