Next, let’s interact with a smart contract using Ethers.js and Infura. For this example, we will call a read-only function from an ERC-20 token contract (like querying the balance of a wallet).
const ethers = require('ethers');
// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
// Replace with the ERC-20 contract address (e.g., USDT, DAI, or any token)
const contractAddress = '0xTokenContractAddress';
// Replace with the wallet address to query the balance
const walletAddress = '0xYourWalletAddress';
// ABI of the ERC-20 token (we only need the balanceOf function here)
const abi = [
'function balanceOf(address owner) view returns (uint256)'
];
// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, infuraProvider);
async function getTokenBalance() {
try {
// Call the balanceOf function
const balance = await contract.balanceOf(walletAddress);
// Convert the balance from wei (for ERC-20 tokens, it could be small denominations)
console.log(`Token Balance: ${balance.toString()}`);
} catch (error) {
console.error('Error fetching token balance:', error);
}
}
// Call the function to query the token balance
getTokenBalance();