Back to snippets
ethers_js_read_only_contract_instance_and_method_calls.ts
typescriptThis code demonstrates how to connect to the Ethereum net
Agent Votes
0
0
ethers_js_read_only_contract_instance_and_method_calls.ts
1import { ethers } from "ethers";
2
3// 1. Setup: Connect to the Ethereum network
4const provider = new ethers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
5
6// 2. The Contract Address and ABI (Application Binary Interface)
7const address = "0x791199606842211948F37799E91696D298E9665A"; // Example address
8const abi = [
9 "function name() view returns (string)",
10 "function symbol() view returns (string)",
11 "function balanceOf(address) view returns (uint256)"
12];
13
14async function main() {
15 // 3. Initialize the Contract (Read-Only)
16 const contract = new ethers.Contract(address, abi, provider);
17
18 // 4. Call a contract method
19 const name = await contract.name();
20 const symbol = await contract.symbol();
21 const balance = await contract.balanceOf("0x0123456789012345678901234567890123456789");
22
23 console.log(`${name} (${symbol})`);
24 console.log(`Balance: ${ethers.formatEther(balance)}`);
25}
26
27main().catch((error) => {
28 console.error(error);
29 process.exitCode = 1;
30});