Blockchain and Web3 course Β· Module 7: Contract Interaction
Interacting with Smart Contracts
In this lesson7
Welcome to the Communication Center! Atlas here. Today you'll learn how to communicate with automated mechanisms (smart contracts) using ethers.js.
ABI - The Mechanism's User Manual
ABI (Application Binary Interface) is the "user manual" for a contract - it describes what functions are available:
const abi = [
// View function (read-only)
"function balanceOf(address owner) view returns (uint256)",
// State-modifying function
"function transfer(address to, uint256 amount) returns (bool)",
// Event
"event Transfer(address indexed from, address indexed to, uint256 amount)"
];Creating a Contract Instance
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider("https://...");
const contractAddress = "0x...";
const abi = [...];
// Read-only (with provider)
const contract = new ethers.Contract(contractAddress, abi, provider);
// Read-write (with signer)
const wallet = new ethers.Wallet(privateKey, provider);
const contractWithSigner = new ethers.Contract(contractAddress, abi, wallet);
// or
const contractConnected = contract.connect(wallet);Reading Data (view functions)
// Calling a view function - costs no gas
const balance = await contract.balanceOf("0x...");
console.log("Balance:", ethers.formatUnits(balance, 18));
// View functions are free!
const name = await contract.name();
const symbol = await contract.symbol();
const totalSupply = await contract.totalSupply();Writing Data (transactions)
// Calling a state-modifying function - costs gas
const tx = await contractWithSigner.transfer(
"0x...", // to
ethers.parseUnits("100", 18) // amount
);
console.log("TX Hash:", tx.hash);
// Wait for confirmation
const receipt = await tx.wait();
console.log("Confirmed in block:", receipt?.blockNumber);Listening to Events
// Listen for new events
contract.on("Transfer", (from, to, amount, event) => {
console.log(`Transfer: ${from} β ${to}: ${ethers.formatUnits(amount, 18)}`);
});
// Fetch historical events
const filter = contract.filters.Transfer(null, "0x..."); // to = 0x...
const events = await contract.queryFilter(filter, -1000); // last 1000 blocks
events.forEach(event => {
console.log("Historical transfer:", event.args);
});Error handling
try {
const tx = await contract.transfer("0x...", amount);
await tx.wait();
} catch (error) {
if (error.code === "CALL_EXCEPTION") {
console.log("Contract returned an error:", error.reason);
} else if (error.code === "INSUFFICIENT_FUNDS") {
console.log("Not enough funds for gas");
} else {
console.log("Other error:", error);
}
}Summary
- ABI - contract interface
- Contract instance with ethers.js
- View functions - free reads
- Write functions - transactions (cost gas)
- Events - listening and history
- Error handling
Code for this lesson: index.js
// ABI - Application Binary Interface
const ERC20_ABI = [
// Read functions (view/pure)
{
"type": "function",
"name": "name",
"inputs": [],
"outputs": [{ "type": "string" }],
"stateMutability": "view"
},
{
"type": "function",
"name": "symbol",
"inputs": [],
"outputs": [{ "type": "string" }],
"stateMutability": "view"
},
{
"type": "function",
"name": "decimals",
"inputs": [],
"outputs": [{ "type": "uint8" }],
"stateMutability": "view"
},
{
"type": "function",
"name": "totalSupply",
"inputs": [],
"outputs": [{ "type": "uint256" }],
"stateMutability": "view"
},
{
"type": "function",
"name": "balanceOf",
"inputs": [{ "name": "account", "type": "address" }],
"outputs": [{ "type": "uint256" }],
"stateMutability": "view"
},
// Write functions
{
"type": "function",
"name": "transfer",
"inputs": [
{ "name": "to", "type": "address" },
{ "name": "amount", "type": "uint256" }
],
"outputs": [{ "type": "bool" }],
"stateMutability": "nonpayable"
},
{
"type": "function",
"name": "approve",
"inputs": [
{ "name": "spender", "type": "address" },
{ "name": "amount", "type": "uint256" }
],
"outputs": [{ "type": "bool" }],
"stateMutability": "nonpayable"
},
// Events
{
"type": "event",
"name": "Transfer",
"inputs": [
{ "name": "from", "type": "address", "indexed": true },
{ "name": "to", "type": "address", "indexed": true },
{ "name": "value", "type": "uint256", "indexed": false }
]
}
];
console.log("=== ABI - APPLICATION BINARY INTERFACE ===\n");
console.log("ABI is a JSON describing how to communicate with a contract:");
console.log(" - What functions are available");
console.log(" - What parameters they accept");
console.log(" - What they return");
console.log(" - What events they emit\n");
console.log("=== FUNCTION STRUCTURE IN ABI ===\n");
const transferFn = ERC20_ABI.find(item => item.name === "transfer");
console.log("Transfer function:");
console.log(JSON.stringify(transferFn, null, 2));
console.log("\n=== FUNCTION SELECTOR ===\n");
// Simulation of selector calculation
function getFunctionSelector(signature) {
// In reality: keccak256(signature).slice(0,4)
const hash = signature.split('').reduce((h, c) =>
((h << 5) - h) + c.charCodeAt(0), 0);
return "0x" + Math.abs(hash).toString(16).slice(0, 8);
}
console.log("Function signature -> 4-byte selector:");
console.log(` transfer(address,uint256) -> ${getFunctionSelector("transfer(address,uint256)")}`);
console.log(` approve(address,uint256) -> ${getFunctionSelector("approve(address,uint256)")}`);
console.log(` balanceOf(address) -> ${getFunctionSelector("balanceOf(address)")}`);
console.log("\nABI is generated automatically when compiling Solidity");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. ABI (Application Binary Interface) is:
2. To create a contract instance in ethers.js you need:
These are 2 of 14 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for parsing an event from a transaction receipt:
- Vertical ordering
Arrange the steps for handling a custom error from a contract:
- Vertical ordering
Arrange the steps for optimizing gas before sending a transaction:
- Vertical ordering
Arrange the steps for fetching historical events:
- Code editor
Complete the code for reading a token balance
- Code editor
Complete the code for a token transfer
- Code editor
Complete the listener for the Transfer event
- Code editor
Complete the code for parsing events from a receipt
- Horizontal ordering
Arrange the correct signature of the transfer function:
- Horizontal ordering
Arrange the correct signature of the Transfer event:
- Horizontal ordering
Arrange the function call with a custom gas limit:
- Horizontal ordering
Arrange the call for encoding function data:
- Code editor
Complete the queryFilter code for historical events
- Code editor
Complete the gas estimation code
- Code editor
Complete the custom error handling code
- Code editor
Complete the ABI encoding code
- Click in order
Click the elements in the order needed to create an Interface:
- Click in order
Click the elements in the order needed to create a contract instance:
- Click in order
Click the elements in the order needed to create an event filter:
- Click in order
Click the elements in the order needed to parse a log:
- Vertical ordering
Arrange the steps for preparing a multicall:
- Horizontal ordering
Arrange the ABI fragment for the balanceOf function:
- Code editor
Complete the multicall code
- Code editor
Complete the code for decoding results
- Click in order
Click the elements in the order needed to decode a custom error:
Tasks after this lesson
- QuestionQuiz: ABI
- QuestionQuiz: Contract instance
- QuestionQuiz: View functions
- QuestionQuiz: Write functions
- QuestionQuiz: contract.connect()
- QuestionQuiz: Events
- QuestionQuiz: contract.on()
- QuestionQuiz: queryFilter
- QuestionQuiz: Function selector
- QuestionQuiz: Event topics
- QuestionQuiz: Interface
- QuestionQuiz: contract.interface.parseLog()
- QuestionQuiz: estimateGas
- QuestionQuiz: Custom errors
- Put in orderSorting: Parsing an event from a receipt
- Put in orderSorting: Handling an error from a contract
- Put in orderSorting: Gas estimation before a transaction
- Put in orderSorting: Filtering events from history
- Coding taskGap: Reading from a contract
- Coding taskGap: Sending a transaction to a contract
- Coding taskGap: Listening for events
- Coding taskGap: Parsing logs from a receipt
- Put in orderHorizontal sorting: Function signature
- Put in orderHorizontal sorting: Event signature
- Put in orderHorizontal sorting: Call with overrides
- Put in orderHorizontal sorting: Interface encoding
- Coding taskGap: QueryFilter - fetching history
- Coding taskGap: Gas estimation
- Coding taskGap: Custom error handling
- Coding taskGap: ABI encoding parameters
- Click in orderSorting: Building an interface
- Click in orderSorting: Building a contract instance
- Click in orderSorting: Building an event filter
- Click in orderSorting: Parsing a log
- Put in orderSorting: Multicall preparation
- Put in orderHorizontal sorting: Function ABI fragment
- Coding taskGap: Multicall pattern
- Coding taskGap: Decoding return values
- Click in orderSorting: Decoding an error
- Project to submitSend your project to the mentor
- ConversationEnd of Module 7