Working with Tokens
Make sure to implement the prerequisite code, or else the examples in this page will not work!
Retrieve user token balances
You can retrieve how many tokens of a specific type (ERC-20) a user holds in their wallet.
From there, you can create any scenario related to the balance. For instance, you can implement token-gating contents: giving access to certain content of your website only to holders of a certain token.
import { abi as erc20ABI } from './ERC20ABI.json';
const tokenAddress = '0xYourTokenAddress'; // Replace with the actual ERC-20 contract address
const userAddress = '0xUserWalletAddress'; // Replace with the user's wallet address
async function getTokenBalance() {
const balance = await client.readContract({
address: tokenAddress,
abi: erc20ABI,
functionName: 'balanceOf', // This is standard ERC-20 function to get balance
args: [userAddress],
});
return balance.toString();
}
// Example usage
getTokenBalance().then(console.log);
If you want to know if the user holds a specific token, make sure to check their wallet balance and also to check their staked balance. Read how to know what's staked.
Indeed, staked tokens are not taken into account in the wallet balance as they are not held in the wallet anymore: they are held on the staking smart-contract.
Retrieve user CHZ balance
You can retrieve how many tokens of a specific native token a user has held in their wallet; for instance, CHZ on Chiliz Chain.
async function getNativeTokenBalance(address) {
const balance = await client.getBalance({
address,
});
return balance.toString();
}
// Example usage. Replace 0xUserWalletAddress with the actual user wallet address.
getNativeTokenBalance('0xUserWalletAddress').then(console.log);
Send ERC-20 Tokens to a wallet
You can send any token held in your wallet to any other wallet.
This is a code-based alternative to the POST /admin/wallet/transfer/fan-token
endpoint, which was deprecated from the Socios.com API in Q1 2025.
import { createWalletClient, privateKeyToAccount } from 'viem';
const privateKey = '0xSenderPrivateKey'; // Replace with the sender's private key
const account = privateKeyToAccount(privateKey);
const walletClient = createWalletClient({
account,
transport: http('YOUR-CHOSEN-RPC-ENDPOINT.com'),
});
async function sendTokens(to, amount) {
const txHash = await walletClient.writeContract({
address: '0xYourTokenAddress', // Replace with the ERC-20 token contract address
abi: erc20ABI,
functionName: 'transfer', // Standard ERC-20 function to transfer tokens
args: [to, BigInt(amount * 1e18)],
});
return txHash;
}
// Example usage. Replace 0xRecipientAddress with the actual recepient wallet address, and 10 with the exact amount to send.
sendTokens('0xRecipientAddress', 10).then(console.log);
Your private key must only be used in server-side code. DO NOT release code on production with your private key shared on front-end side code.
Last updated