Blockchain and Web3 course Β· Module 7: Contract Interaction

Interacting with Smart Contracts

2 min read Β·
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. 1. ABI (Application Binary Interface) is:

  2. 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:

  1. QuestionQuiz: ABI
  2. QuestionQuiz: Contract instance
  3. QuestionQuiz: View functions
  4. QuestionQuiz: Write functions
  5. QuestionQuiz: contract.connect()
  6. QuestionQuiz: Events
  7. QuestionQuiz: contract.on()
  8. QuestionQuiz: queryFilter
  9. QuestionQuiz: Function selector
  10. QuestionQuiz: Event topics
  11. QuestionQuiz: Interface
  12. QuestionQuiz: contract.interface.parseLog()
  13. QuestionQuiz: estimateGas
  14. QuestionQuiz: Custom errors
  15. Put in orderSorting: Parsing an event from a receipt
  16. Put in orderSorting: Handling an error from a contract
  17. Put in orderSorting: Gas estimation before a transaction
  18. Put in orderSorting: Filtering events from history
  19. Coding taskGap: Reading from a contract
  20. Coding taskGap: Sending a transaction to a contract
  21. Coding taskGap: Listening for events
  22. Coding taskGap: Parsing logs from a receipt
  23. Put in orderHorizontal sorting: Function signature
  24. Put in orderHorizontal sorting: Event signature
  25. Put in orderHorizontal sorting: Call with overrides
  26. Put in orderHorizontal sorting: Interface encoding
  27. Coding taskGap: QueryFilter - fetching history
  28. Coding taskGap: Gas estimation
  29. Coding taskGap: Custom error handling
  30. Coding taskGap: ABI encoding parameters
  31. Click in orderSorting: Building an interface
  32. Click in orderSorting: Building a contract instance
  33. Click in orderSorting: Building an event filter
  34. Click in orderSorting: Parsing a log
  35. Put in orderSorting: Multicall preparation
  36. Put in orderHorizontal sorting: Function ABI fragment
  37. Coding taskGap: Multicall pattern
  38. Coding taskGap: Decoding return values
  39. Click in orderSorting: Decoding an error
  40. Project to submitSend your project to the mentor
  41. ConversationEnd of Module 7