Listening to events (frontend)
📖 Scenario: You are building a simple web page that listens to blockchain events from a smart contract. When the contract emits an event, your page will show a message to the user.
🎯 Goal: Create a small frontend script that connects to a blockchain contract and listens for a specific event. When the event happens, display the event data on the page.
📋 What You'll Learn
Create a variable called
contractAddress with the exact value '0x1234567890abcdef1234567890abcdef12345678'.Create a variable called
contractABI with the exact value [{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"message","type":"string"}],"name":"NewMessage","type":"event"}].Create a variable called
provider using new ethers.providers.Web3Provider(window.ethereum).Create a variable called
contract using new ethers.Contract(contractAddress, contractABI, provider).Use
contract.on('NewMessage', (message) => { ... }) to listen to the event and update the page.Display the event message inside the HTML element with id
eventMessage.💡 Why This Matters
🌍 Real World
Listening to blockchain events is essential for building interactive decentralized applications (dApps) that respond to changes on the blockchain in real time.
💼 Career
Frontend developers working with blockchain need to know how to connect to smart contracts and listen to events to create responsive user interfaces.
Progress0 / 4 steps