This guide provides instructions on how to interact with the Chiliz Chain to perform common tasks such as retrieving token balances, NFT balances, user transactions, sending ERC-20 tokens, and checking native token balances.
Prerequisites
To play around with Chiliz chain, CHZ, fan tokens and your users' wallet content, you will need to setup your environment as following. If you have any question or a specific configuration, please let us know we will be happy to help.
Before starting a blockchain request, you will need to add this piece of code in order to initiate Viem and connect to the chain via the RPC. You need it only once in your code.
import { createPublicClient, http } from 'viem'; // Initiate Viem
const client = createPublicClient({
transport: http('https://rpc.ankr.com/chiliz'), // Connect to Chiliz chain via Ankr RPC node
});
Tokens
Retrieve user token balances
By using the code below you can easily retrieve how many tokens of a specific token (ERC-20) a user has held in his wallet. Then you will be able to create any scenario related to the balance, for instance, token gating contents.
Code Example for ERC-20/CAP-20 token (Fan tokens, PEPPER, etc.)
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, // Contract address of the token
abi: erc20ABI, // ERC-20 ABI
functionName: 'balanceOf', // Standard ERC-20 function to get balance
args: [userAddress], // User's address whose balance you want to check
});
return balance.toString();
}
// Example usage
getTokenBalance().then(console.log);
Retrieve user native token balance
By using the code below you can easily retrieve how many tokens of a specific native token (CHZ) a user has held in his wallet. Then you will be able to create any scenario related to the balance, for instance, token gating contents.
Code Example for Chiliz (CHZ), Chiliz chain native token
async function getNativeTokenBalance(address) {
const balance = await client.getBalance({
address,
});
return balance.toString();
}
// Example usage
getNativeTokenBalance('0xUserWalletAddress').then(console.log);
If you know the NFT smartcontract address, you can get all metadata:
import { abi as erc721ABI } from './ERC721ABI.json';
const contractAddress = '0xYourNFTAddress'; // Replace with the actual contract address
// Function to fetch metadata for a given tokenId
async function getNFTMetadata(tokenId) {
// Call the `tokenURI` method to get the URL for the metadata
const tokenURI = await client.readContract({
address: contractAddress, // Contract address of the NFT
abi: erc721ABI, // ERC-721 ABI
functionName: 'tokenURI', // Standard ERC-721 function to get metadata uri
args: [tokenId], // User's address whose balance you want to check
});
// Fetch metadata from the token URI (usually a JSON file)
const metadataResponse = await fetch(tokenURI);
const metadata = await metadataResponse.json();
console.log(metadata);
}
// Example usage: Get metadata for a specific token (e.g., token ID 1)
getNFTMetadata(1);
Retrieve user NFT Balance
This code will allow you to check how many NFT from a specific collection a user holds, it will be much light tha "Retrieve user NFT list via Nansen" . Code Example for ERC-721:
import { abi as erc721ABI } from './ERC721ABI.json';
async function getNFTBalance() {
const balance = await client.readContract({
address: '0xYourNFTAddress', // Replace with the actual NFT contract address
abi: erc721ABI, // ERC-721 ABI
functionName: 'balanceOf', // Standard ERC-721 function to get balance
args: ['0xUserWalletAddress'], // User's address whose NFT balance you want to check
});
return balance.toString();
}
// Example usage
getNFTBalance().then(console.log);
Transactions
Retrieve a user transaction details (/user/wallet/{transactionId})
By using the code below you can easily retrieve details about a specific transaction (estimated gas fees transaction details)
async function getTransaction(txHash) {
const transaction = await client.getTransaction({
hash: txHash, // Replace with the actual transaction hash
});
return transaction;
}
// Example usage
getTransaction('0xTransactionHash').then(console.log);
Retrieve a user transaction receipt
By using the code below you can easily retrieve a specific transaction receipt (definitive gas fees and transaction details).
async function getTransactionReceipt(txHash) {
const transactionReceipt = await client.getTransactionReceipt({
hash: txHash, // Replace with the actual transaction hash
});
return transactionReceipt;
}
// Example usage
getTransactionReceipt('0xTransactionHash').then(console.log);
Send ERC-20 Tokens to a wallet (/admin/wallet/transfer/fan-token)
By using the code below you can easily send any token held in your wallet to any other wallet.
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('https://rpc.ankr.com/chiliz'),
});
async function sendTokens(to, amount) {
const txHash = await walletClient.writeContract({
address: '0xYourTokenAddress', // Replace with the ERC-20 token contract address
abi: erc20ABI, // ERC-20 ABI
functionName: 'transfer', // Standard ERC-20 function to transfer tokens
args: [to, BigInt(amount * 1e18)], // Replace 'to' with recipient address and 'amount' with the amount to send
});
return txHash;
}
// Example usage
sendTokens('0xRecipientAddress', 10).then(console.log);
Socios polls
Allow a user to vote on a poll (/poll/{pollId}/vote
By using the code below you can easily allow a logged in user to vote a specific Socios.com poll.
Code Example for Socios.com polls
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('https://rpc.ankr.com/chiliz'),
});
async function vote(id, weight) {
const txHash = await walletClient.writeContract({
address: '0xPollAddress', // Replace with the poll contract address
abi: survey3ABI, // Poll contract ABI
functionName: 'vote', // Function to cast the vote
args: [id, BigInt(weight)], // Replace 'id' with answer id and 'weight' with the amount of tokens that should be used to cast the vote
});
return txHash;
}
// Example usage
vote('dab3d446-959f-47e7-8789-f618d969de1e', 1).then(console.log);
Retrieve user vote on a poll (/poll/{pollId})
By using the code below you can easily retrieve if a user has already voted on a specific poll, and get which answer he has selected.
Code Example for Socios.com polls
import { createPublicClient, http, keccak256 } from 'viem';
import { abi as survey3ABI } from './Survey3ABI.json';
const client = createPublicClient({
transport: http('https://rpc.ankr.com/chiliz'),
});
const pollAddress = '0xPollAddress'; // Replace with the actual poll contract address
const userAddress = '0xUserAddress'; // Replace with the user's wallet address
// Returns hashes of answerIds that the user voted on
async function getUserVoteHashes() {
const votes = await client.readContract({
address: pollAddress, // Poll contract address
abi: survey3ABI, // Poll conttract ABI
functionName: 'getUserAnswers', // Function to retrieve the answers that the user voted on
args: [userAddress], // User's address whose votes you want to fetch
});
return votes;
}
// Returns votes in plain text
async function getUserVotesPlainText() {
// fetch all answers
const answers = await client.readContract({
address: pollAddress, // Poll contract address
abi: survey3ABI, // Poll conttract ABI
functionName: 'getAnswers', // Function to retrieve the answers
args: [], // User's address whose votes you want to fetch
});
// fetch user's votes
const votes = await client.readContract({
address: pollAddress, // Poll contract address
abi: survey3ABI, // Poll conttract ABI
functionName: 'getUserAnswers', // Function to retrieve the answers that the user voted on
args: [userAddress], // User's address whose votes you want to fetch
});
// filter answers, return the ones that the user voted on
const plainTextVotes = answers.filter(a => votes.includes(keccak256(a.id)));
return plainTextVotes;
}
// Example usage
getUserVotesPlainText().then(console.log);
getUserVoteHashes().then(console.log);