const express = require('express'); const { ethers } = require('ethers'); const app = express(); app.use(express.json()); const PORT = process.env.PORT || 2015; // Connect to an Ethereum provider const provider = new ethers.JsonRpcProvider(process.env.INFURA_URL || 'https://mainnet.infura.io/v3/25c9f1810f234c278a4f13736a897836'); // ERC-20 token contract address const tokenAddress = '0x22b6c31c2beb8f2d0d5373146eed41ab9ede3caf'; // ERC-20 token ABI (Application Binary Interface) const tokenABI = [ // Only the part of the ABI we need: balanceOf and decimals "function balanceOf(address owner) view returns (uint256)", "function decimals() view returns (uint8)" ]; // Create a contract instance const tokenContract = new ethers.Contract(tokenAddress, tokenABI, provider); app.listen(PORT, () => { console.log("started listening on localhost:" + PORT); }); app.get("/status", (request, response) => { const status = { "Status": "Running" }; response.send(status); }); /* ------------------------------------------------------------------------------- */ app.get("/getBalance", async (request, response) => { try { const { address } = request.query; if (!address) { return response.status(400).json({ error: "Missing wallet address in the query parameters" }); } // Check if the provided address is a valid Ethereum address if (!ethers.isAddress(address)) { return response.status(400).json({ error: "Invalid Ethereum address" }); } // Get the token balance of the wallet address const balanceRaw = await tokenContract.balanceOf(address); // Get the number of decimals used by the token const decimals = await tokenContract.decimals(); // Convert the balance to a human-readable format const balance = ethers.formatUnits(balanceRaw, decimals); response.json({ address, tokenAddress, balance}); } catch (error) { console.error("Error fetching token balance:", error); response.status(500).json({ error: "Failed to fetch token balance", trace: error }); } });