How to Query and Monitor Ethereum Contract Events with Web3 (2024)

With web3.js, you can query and listen for contract events on the Ethereum blockchain, so that you can specify actions to trigger when certain criteria are met.

In this guide I’ll demonstrate the different methods for querying and listening for contract events with web3. I’ve designed this post so that you can use it as a reference and skip forward to the part you need. If you already know how to set up web3 you can skip to making an event query.

Here’s what I’ll be covering in this post.

  • Setting up the Contract
  • Making a Event Query
  • Query Past Events with getPastEvents()
  • Create an Event Listener for a Contract’s Events
  • Create an Event Listener for a Specific Event Type
  • Appendix A: The content of an event
    • Sample output
    • Properties

Setting up the Contract

You need to instantiate a contract before you can query events for it.

const Web3 = require('web3'); const client = require('node-rest-client-promise').Client();const INFURA_KEY = "SECRET_INFURA_KEY"; // Insert your own key here :)const ETHERSCAN_API_KEY = "SECRET_ETHERSCAN_KEY";const web3 = new Web3('wss://mainnet.infura.io/ws/v3/' + INFURA_KEY);const CONTRACT_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";const etherescan_url = `http://api.etherscan.io/api?module=contract&action=getabi&address=${CONTRACT_ADDRESS}&apikey=${ETHERSCAN_API_KEY}`async function getContractAbi() { const etherescan_response = await client.getPromise(etherescan_url) const CONTRACT_ABI = JSON.parse(etherescan_response.data.result); return CONTRACT_ABI;}async function eventQuery(){const CONTRACT_ABI = getContractAbi();const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);/* Code to query events here */ }eventQuery();

The contract examples I use in this post all use the wrapped ether token. Because it’s one of the most popular tokens in Ethereum, the contract has a high volume of transactions, making it a great address to use for testing event listening.

Making a Event Query

There are two primary use cases for interacting with Ethereum contract events. You can:

  • query a contract’s past events for analysis or storage on a local database

  • create an event listener for a contract’s events to specify actions you want to trigger in specific circ*mstances

Query Past Events with getPastEvents()

You can use web3 to query all past events that a contract has ever emitted. The getPastEvents() will return an array of event objects. However it is currently limited to one thousand results at a time - getPastEvents() will return an error if more results would be returned.

The first argument allows you to specify the event type to query, or allEvents to return all event types.The second argument is a filter object that allows you to filter by start1 and end block as shown below:

const START_BLOCK = 7700000;const END_BLOCK = 7701000;contract.getPastEvents("allEvents", { fromBlock: START_BLOCK, toBlock: END_BLOCK // You can also specify 'latest'  }) .then(events => console.log(events)).catch((err) => console.error(err));

You can also specify the type of event your want to query. Let’s use Transfer , since it is a required event for ERC-20 and ERC-721 tokens:

contract.getPastEvents("Transfer",//...

See the sample output for an event in Appendix A: The content of an event

Create an Event Listener for a Contract’s Events

You can also create an event listening to upcoming events, and specify a callback that will occur when the event is emitted.

You can use contract.events.allEvents() to specify a callback for all events.

contract.events.allEvents().on('data', (event) => {console.log(event);}).on('error', console.error);

See the sample output for an event in Appendix A: The content of an event

Create an Event Listener for a Specific Event Type

You can use contract.events.EventName() to specify actions for specific event types. For example, Transfer:

contract.events.Transfer().on('data', (event) => {console.log(event);}).on('error', console.error);

See the sample output for an event below.

Appendix A: The content of an event

Sample output

{ removed: false, logIndex: 53, transactionIndex: 65, transactionHash: '0x778b776cb1a4998fb681081a79c4e2e8afea877644747cfc64e6dd36f6fda7f2', blockHash: '0x1eab83d59f65ab513681ad1314c4b334cca301def37e29ce098dfb293fd24181', blockNumber: 7907793, address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', id: 'log_0x03168f825cef626f45228ae375b310303c66b79ed364a46119e7e004794af27c', returnValues: { '0': '0xad9EB619Ce1033Cc710D9f9806A2330F85875f22', '1': '0x39755357759cE0d7f32dC8dC45414CCa409AE24e', '2': BigNumber { _hex: '0x01158e460913d00000' }, src: '0xad9EB619Ce1033Cc710D9f9806A2330F85875f22', dst: '0x39755357759cE0d7f32dC8dC45414CCa409AE24e', wad: BigNumber { _hex: '0x01158e460913d00000' } }, event: 'Transfer', signature: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', raw: { data: '0x000000000000000000000000000000000000000000000001158e460913d00000', topics: [ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '0x000000000000000000000000ad9eb619ce1033cc710d9f9806a2330f85875f22', '0x00000000000000000000000039755357759ce0d7f32dc8dc45414cca409ae24e' ] } }

Properties

name type description
id String
event String The event name
signature String|Null The event signature, null if it’s an anonymous event.
address String Address this event originated from.
returnValues Object The return values coming from the event, e.g. {from: '0x123...', to: '0x234...', amount: 100}.
logIndex Number Integer of the event index position in the block.
transactionIndex Number Integer of the transaction’s index position the event was created in.
transactionHash 32 Bytes|String Hash of the transaction this event was created in.
blockHash 32 Bytes|String Hash of the block this event was created in. null when it’s still pending.
blockNumber Number The block number this log was created in. null when still pending.
raw.data String The data containing non-indexed log parameter.
raw.topics Array An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters of the event.
  1. The fromBlock property argument is specified as optional in the documentation, but in the current web3 version (1.0.0-beta.55) the method will fail without a filter object argument with this property.

How to Query and Monitor Ethereum Contract Events with Web3 (2024)

FAQs

How do I query an Ethereum smart contract? ›

The best way to view a token's smart contract is through Etherscan, a block explorer and analytics platform built on Ethereum. Block explorers like Etherscan allow users to search and index real-time and historical information about a blockchain.

How do I interact with a contract on Web3? ›

Part 2: Interact with your Smart Contract
  1. Step 1: Create a interact. js file. ...
  2. Step 2: Update your .env file. ...
  3. Step 3: Grab your contract ABI. ...
  4. Step 4: Create an instance of your contract. ...
  5. Step 5: Read the init message. ...
  6. Step 6: Update the message. ...
  7. Step 7: Read the new message.

How do I query Ethereum blockchain data? ›

The most basic way to access Ethereum blockchain data is by hosting a node yourself on your local computer, and then querying that node directly.

How do I get ABI from contract address in Web3? ›

After successfully deploying your contract, you get to copy its ABI. To do this, you need to go back to the “Solidity Compiler” tab and scroll down. There, you'll see the copy icon and “ABI”: So, just click the above-marked area and you will have your smart contract's ABI in your clipboard.

Can a smart contract read events? ›

Events are basically a separated data storage that can be read easily by nodes . We can subscribe to the events from smart contracts and update the transaction and the UI's state accordingly.

How do you analyze a smart contract? ›

A smart contract can be read by visiting a project's Etherscan (if based on Ethereum) and GitHub page.
...
The sections for decimals, governance, and totalSupply reveal the following information:
  1. YFI is a token with 18 decimals.
  2. YFI has a separate governance contract.
  3. YFI has a maximum total supply of 36,666 tokens.
Sep 1, 2022

How do I call a smart contract from Web3? ›

How to Use a Web3 JS Call Contract Function
  1. Initialize a NodeJS project.
  2. Install the Moralis SDK.
  3. Get your Moralis Web3 API key (this is your gateway to the best Ethereum API in 2023)
  4. Obtain a smart contract's ABI.
  5. Implement the “runContractFunction” Web3 JS call contract function.
Dec 19, 2022

What is the difference between Web3 and smart contracts? ›

Smart contracts are agreements between two or more parties over the internet. Moreover, Web3 contracts are the backbone of the Web3 industry, and today's blockchain-driven internet operates on Web3 contracts. Web3 contracts are self-executing agreements.

How do I manually interact with smart contract? ›

Interact with deployed smart contracts
  1. Perform a read operation. To perform a read operation, you need the address that the contract was deployed to and the contract's ABI. ...
  2. Perform a write operation. To perform a write operation, send a transaction to update the stored value. ...
  3. Verify an updated value.
Aug 8, 2022

Where can I track Ethereum transactions? ›

It's easy to check your balance and transaction history on an Ethereum blockchain explorer like EthVM, Etherscan, or Ethplorer. These websites offer a full history of your activity.

How do I follow Ethereum transactions? ›

From the app's home screen, tap on the Ethereum wallet the transaction was made from. You should then see a list of transactions. Tapping on a transaction will display more details, such as whether the transaction has been confirmed or is still pending.

Can I track an Ethereum transaction? ›

Some of the most popular blockchain explorers to track transactions are the following: Etherscan: This is the most popular of all when it comes to the Ethereum blockchain network. It allows users to have access to a wide range of data, from wallet balances to smart contracts, and more.

How do you find the ABI of an Ethereum contract? ›

Paste the contract address that you previously copied in the “Contract Address” field. You also need to paste the “ABI / JSON Interface” of the contract on the above screen. To get the ABI, go to the Remix window and click on the ABI button as shown in the screenshot below.

What is Web3 contract address and ABI? ›

The ABI (Application Binary Interface) is the JSON format of the smart contract that contains its functions and methods. This gives a reference of what you can call using the Web3 library. The Contract Address refers to the smart contract's address that was deployed on the blockchain.

What is ABI in Web3? ›

The web3. eth. abi functions let you encode and decode parameters to ABI (Application Binary Interface) for function calls to the EVM (Ethereum Virtual Machine).

Can you audit a smart contract? ›

A smart contract audit involves a detailed analysis of a protocol's smart contract code to identify security vulnerabilities, poor coding practices, and inefficient code before identifying solutions that resolve these issues.

Is it illegal to exploit smart contracts? ›

The consequences for this kind of hacking are jail and serious fines. The idea that 'code is law' as an ethos means that anyone can exploit unintended flaws in smart contracts to drain them of funds is wrong.

Do you need to audit a smart contract? ›

The audit process is an important part of ensuring the security and reliability of blockchain applications. A smart contract audit involves a detailed analysis of the contract's code to identify security issues and incorrect and inefficient coding, and to determine ways to resolve the problems.

What are the 4 major parts of a smart contract? ›

Anatomy of smart contracts
  • Prerequisites.
  • Data. Storage. Memory. Environment variables.
  • Functions. View functions. Constructor functions. Built-in functions.
  • Writing functions.
  • Events and logs.
  • Annotated examples. Hello world. Token. Unique digital asset.
  • Further reading.
  • Related topics.

What are the best practices of smart contract auditing? ›

Here are the main stages of how we conduct a security audit for smart contracts:
  • Code consistency check. ...
  • Undocumented features check.
  • Test against the standard list of vulnerabilities.
  • Detailed business logic review, search for deadlocks and backdoors or potential exploits.
Sep 22, 2022

What is the algorithm for smart contracts? ›

Byzantine fault-tolerant algorithms are the algorithms that allow digital security through decentralization to form smart contracts blockchain. Certain programming languages with various degrees of Turing completeness as a built-in feature of some blockchains make the creation of custom sophisticated logic possible.

Is smart contract a web3? ›

Smart contracts, or digital self-executing contracts built on blockchain, are a key component of web3. These contracts power a range of functions, from executing financial transactions to identifying users to running a decentralized autonomous organization or DAO.

What is the function of ETH contract in web3? ›

The web3. eth. Contract object makes it easy to interact with smart contracts on the ethereum blockchain. When you create a new contract object you give it the json interface of the respective smart contract and web3 will auto convert all calls into low level ABI calls over RPC for you.

What is the difference between call and send in web3? ›

The difference between the call() and send() methods has to do with the type of function they are calling and their effect. Solidity functions can be divided into two categories: Functions that alter the state of the contract. Functions that do not alter the state of the contract.

What language is Web3 smart contract? ›

Solidity is the most widely used smart contract programming language in web3, having been created by an Ethereum team. The language is object-oriented, high-level, and Turing-complete. These characteristics are a result of the language's heavy dependence on C++, Python, and JavaScript.

What is the most popular smart contract platform? ›

This article will introduce and analyze the five most prominent smart contract platforms: Ethereum, Hyperledger Fabric, Corda, Stellar and Rootstock as well as consider their popularity and technical maturity in the growing community.

Is Web 3.0 the same as metaverse? ›

Web3 is about decentralized ownership and control and putting the web in the hands of its users and the community. The metaverse, on the other hand, is a shared digital reality that enables users to connect with each other, build economies and interact in real time -- and it doesn't care who owns it.

How do you debug a smart contract? ›

A simple way to handle the debugging process is to use Tenderly Debugger. This tool streamlines debugging Smart Contracts as it allows you to easily identify the exact line of code where an error occurred and analyze values of local and state variables.

What tool do you use to interact with smart contracts? ›

Smart Contract Programming Language

The top choices in programming languages for smart contract development include Solidity, Rust, and Vyper. Solidity is the most commonly used programming language for smart contract development.

Who executes smart contracts? ›

SMART CONTRACTS PLATFORMS

Ethereum: smart contracts are written in a programming language called Solidity and executed by the Ethereum virtual machine.

How do you mint directly from a contract? ›

You'll need to select “Contract” then “Write Contract.” Once there, you should see the functions you can interact with. You'll be looking for the mint function; it might be named safeMint. After you connect your wallet and provide your address, you should be able to mint the NFT to your wallet.

What is the largest transaction on Ethereum? ›

The Most Expensive Transaction on Ethereum Cost USD 23.5 Million.

How do I track my ERC-20 transaction? ›

To monitor an ERC-20 token, you need to track its transactions and events on the network. You can use Etherscan or other tools to do this. You can use Etherscan to view your token balance, transfers, holders, and approvals.

How do I track crypto transactions? ›

How to Trace Bitcoin Transactions
  1. The first step is to visit blockchair.com and enter the Bitcoin address that you want to trace into the search bar.
  2. Once you have done this, hit enter, and you will be taken to a page that contains all of the information related to that address.

Who verifies transactions in Ethereum? ›

Ethereum miners verify legitimate transactions and create new ether as a reward for their work. A transaction is considered verified once the miner solves a cryptographic (mathematical) puzzle.

Does Ethereum keep track of smart contracts? ›

This machine state, of which all Ethereum nodes agree to keep a copy, stores smart contract code and the rules by which these contracts must abide. Since every node has the rules baked in via code, all Ethereum smart contracts have the same limitations.

What is transaction trace on Ethereum? ›

Tracing allows users to examine precisely what was executed by the EVM during some specific transaction or set of transactions. There are two different types of transactions in Ethereum: value transfers and contract executions. A value transfer just moves ETH from one account to another.

How do I track crypto transactions on Etherscan? ›

How Do I Find Transactions On Etherscan? The easiest way to look up a transaction through Etherscan is by using the transaction ID. However, if you do not have it or don't know where to find it, entering one of the two wallet addresses involved in the transaction will work too.

How do I get data from my smart contract? ›

ABI of a smart contract can be taken from Etherscan.io by following the steps given below:
  1. Go to Etherscan.io and click “ERC20 Top Tokens” in the drop-down of “Tokens” located in the top navigation bar.
  2. Click any token from the list of ERC20 tokens.
  3. Now, the details of that token will be shown.

How do I call a smart contract? ›

How to Call Smart Contract Function from JavaScript
  1. Set Up a NodeJS Project.
  2. Add the Code to the ”index. js” File.
  3. Run the Program.
Dec 16, 2022

Can anyone call a smart contract? ›

Can anyone call a smart contract? Generally speaking, anyone can call a smart contract. Smart contracts can even call other smart contracts. This functionality is useful when minting new tokens.

What is the Ethereum query language? ›

Therefore, we propose the Ethereum Query Language (EQL), a query language that allows users to retrieve information from the blockchain by writing SQL-like queries. The queries provide a rich syntax to specify data elements to search information scattered through several records.

How to do smart contract audit? ›

Let's break down the process of a smart contract security audit.
  1. Documentation. The first step of an audit is to gather all relevant documentation. ...
  2. Run tests with tools. ...
  3. Manual review of code. ...
  4. Resolve issues. ...
  5. Audit report.

Where is smart contract data stored? ›

Smart contracts are executed on blockchain, which means that the terms are stored in a distributed database and cannot be changed. Transactions are also processed on the blockchain, which automates payments and counterparties.

Where are events stored in Ethereum? ›

Events are also known as "logs" in Ethereum. The output of the events are stored in transaction receipts under a logs section.

How do you call a contract method in Web3? ›

How to Use a Web3 JS Call Contract Function
  1. Initialize a NodeJS project.
  2. Install the Moralis SDK.
  3. Get your Moralis Web3 API key (this is your gateway to the best Ethereum API in 2023)
  4. Obtain a smart contract's ABI.
  5. Implement the “runContractFunction” Web3 JS call contract function.
Dec 19, 2022

What is the function of ETH contract in Web3? ›

The web3. eth. Contract object makes it easy to interact with smart contracts on the ethereum blockchain. When you create a new contract object you give it the json interface of the respective smart contract and web3 will auto convert all calls into low level ABI calls over RPC for you.

Who manages the smart contracts? ›

The one who "runs" the smart contract is the caller of a function of a contract. The one who sends the message, interacts with the contract and sends ETH. It is in a contract referred as "msg. sender" It could be an address account or a contract acount (contracts can call others' contracts function).

Can someone hack a smart contract? ›

Smart Contracts Are Vulnerable

Although some hack attacks are due to lax security measures and phishing attempts on users' personal keys, the truth is that the majority of funds stolen in the DeFi industry are due to one thing – vulnerabilities in the smart contracts that power the industry.

What language are smart contracts written in? ›

A great aspect about Ethereum is that smart contracts can be programmed using relatively developer-friendly languages. If you're experienced with Python or any curly-bracket language(opens in a new tab)↗, you can find a language with familiar syntax. The two most active and maintained languages are: Solidity.

How do you directly interact with a smart contract? ›

Interact with deployed smart contracts
  1. Perform a read operation. To perform a read operation, you need the address that the contract was deployed to and the contract's ABI. ...
  2. Perform a write operation. To perform a write operation, send a transaction to update the stored value. ...
  3. Verify an updated value.
Aug 8, 2022

What is the most popular language for Ethereum? ›

JavaScript serves as the backbone of Ethereum as it functions as a runtime environment with script execution. Java — A general-purpose programming language that is concurrent, object-oriented, and class-based is designed in such a way that Java has few implementation dependencies.

What language does Vitalik Buterin code in? ›

He created his own programming language in Solidity for Ethereum. It is a curly-bracket language influenced by C++, Python, and JavaScript. Solidity is an object-oriented, high-level language for implementing smart contracts.

What is the most popular coding language Ethereum? ›

Solidity is the most popular blockchain programming language of the Ethereum Virtual Machine (EVM), also widely used across a range of EVM-compatible blockchains.

Top Articles
How much money are freight brokers really making from truckers?
Average Cost of College [2024]: Yearly Tuition + Expenses
Algebra Calculator Mathway
Mychart Mercy Lutherville
Martha's Vineyard Ferry Schedules 2024
7.2: Introduction to the Endocrine System
Lichtsignale | Spur H0 | Sortiment | Viessmann Modelltechnik GmbH
Publix 147 Coral Way
Bowlero (BOWL) Earnings Date and Reports 2024
24 Hour Walmart Detroit Mi
D10 Wrestling Facebook
Cvs Appointment For Booster Shot
Moviesda3.Com
Tamilrockers Movies 2023 Download
CANNABIS ONLINE DISPENSARY Promo Code — $100 Off 2024
Edicts Of The Prime Designate
Sni 35 Wiring Diagram
Why Is 365 Market Troy Mi On My Bank Statement
Drago Funeral Home & Cremation Services Obituaries
Craigslist Pet Phoenix
Crawlers List Chicago
Craigslist Clinton Ar
Ups Drop Off Newton Ks
Shreveport City Warrants Lookup
eugene bicycles - craigslist
Strange World Showtimes Near Savoy 16
Manuela Qm Only
Albert Einstein Sdn 2023
Margaret Shelton Jeopardy Age
Accuradio Unblocked
11526 Lake Ave Cleveland Oh 44102
Royalfh Obituaries Home
Craigslist Brandon Vt
Grave Digger Wynncraft
Darknet Opsec Bible 2022
Datingscout Wantmatures
Smayperu
Mobile Maher Terminal
Shiftwizard Login Johnston
Busch Gardens Wait Times
O'reilly's Palmyra Missouri
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Conan Exiles Armor Flexibility Kit
Emily Browning Fansite
All Weapon Perks and Status Effects - Conan Exiles | Game...
How To Get To Ultra Space Pixelmon
Craigslist Sarasota Free Stuff
The Plug Las Vegas Dispensary
Ciara Rose Scalia-Hirschman
Amourdelavie
Public Broadcasting Service Clg Wiki
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6257

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.