Web3
Web

Use thirdweb to capture and listen to Contract Events on the Blockchain and set up real-time event listeners to listen to transaction events on a specific contract.

In this tutorial, we will show you how to use thirdweb to capture and listen to Contract Events on the Blockchain and set up real-time event listeners to listen to transaction events on a specific contract. Thirdweb is a powerful tool that allows users to easily listen and track events on the blockchain in real-time, and its user-friendly interface makes it accessible to even those new to blockchain technology.

We will be covering the following topics:

  1. Finding your contract’s address on ThirdWeb
  2. Set up your enviornment
  3. Set up a real-time event listener for contract events using ContratEvents.getAllEvents()

Finding Your Contract’s Address On ThirdWeb

To listen to Contract Events on the Blockchain and set up a real-time event listener for transaction events on a specific contract, you will first need to find the contract’s address on the blockchain that you want to track. If you havent already, check out our article on creating contracts in thirdweb for a primer on this. If you’ve created a contract previously, you’ll already have access tothe contract address in your thirdweb Dashboard. It’ll be the little copy-able hex value underneath your contracts name and description:

Setting Up Our Environment

Ok, now that we have our contract Address, lets set-up our ThirdWeb environment. First, lets open up a console and create a directory called ThirdWebTest and cd into the it. We’re going to assume you already have NPM and Node set up on your computer but if not. Please do that before continuing.

Create the Directory:

Mkdir ThirdWebTest
cd ThirdWebTest

Now, run the following to install the latest thirdWeb Packages

npm install @thirdweb-dev/sdk ethers@5

Next, create a file inside the directory called index.js

touch index.js

The index.js is going to be our launch pad for this application. To continue, open up your index.js file in your favorite editor to get started. In this tutorial, we’re going to keep things extremely simple. So this definitely wont be a complete application, but it’ll lay the groundwork to get us started and listening to basic events.

At the top of you’re index.js file, lets add the lines to require the thirdweb SDK that we imported earlier.

const { ThirdwebSDK } = require('@thirdweb-dev/sdk');

Since this is just a basic example. We’ll be using the testnet to listen to our contract. This means two things”

1.) That we’ve already created a thirdWeb Contract that we can listen to events on. Note: If you don’t know how to do this, check out our prior article.

2.) The contract was created on the mumbai testnet.

There are multiple networks that a contract can exist on. In our case, we’re going to be working with Polygon, so we’ll want to use the Polygon testnet, which is the Mumbai network.

To tell our application to listen to the mumbai network, initialize it and pass in the “mumbai” param. ThirdWeb supports all major chains and testnets, but today we’ll just focus on Mumbai.

Add the below lines to your index.js file:

const sdk = new ThirdwebSDK("mumbai");

Next, lets set-up a basic method to call our code. To do this, we’ll add the below async function:

const runEvents = async function(){

// future code goes here

}
runEvents();

Now, to access a contract, we’ll add the sdk.getcontract() method to our function and pass it a ThirdWeb generated contract address as shown below. For this example, its important that the contract is a ThirdWeb contract. In the future we can use other contracts, and pass in their ABI, but we’re going to skip that at this point and can address that in a later tutorial. Add the following to your runEvents function:

console.log("Getting Contract...");
const contract = await sdk.getContract("0x…"); // this should be the contract address you found in the first section

Note: As mentioned above, you can also use non third web generated contracts, but to do this you’ll need to use the getContractFromAbi() method and pass in a valid ABI. We’re not going to do that in this tutorial but we might touch on that in a later article.

OK, now that we have our contract set-up. We can start listening to its events. To do this, we’ll use the contract.events.listenToAllEvents() method to Listen to all the events emitted from this contract. Add the following lines to your file:

console.log("Listening to contract...");
contract.events.listenToAllEvents((event) => {
  console.log(event.eventName) // the name of the emitted event
  console.log(event.data) // event payload
});

At this point, make sure your work is saved. The complete code is shown below:

const { ThirdwebSDK } = require('@thirdweb-dev/sdk');
const sdk = new ThirdwebSDK("mumbai");

const runEvents = async function(){
    console.log("Getting Contract...");
    const contract = await sdk.getContract("0x..."); // this should be the contract address you found in the first section
    console.log("Listening to contract...");
    contract.events.listenToAllEvents((event) => {
        console.log(event.eventName) // the name of the emitted event
        console.log(event.data) // event payload
        });
}
runEvents();

To test our code, open up your console and run the index.js file by typing the below

node index.js

If everything is set-up correctly, you should now be actively listening to events on your contract and logging out some basic info from these events.

Keep in mind, unless there’s a lot going on with your contract, you aren’t going to see a lot happening at this point. But, if you perform any actions on your contract, such as minting an NFT, transferring an item, or anything else that will emit an event, you should see that event being logged in real time. similar to the below:

Console:
Transfer
{
  from: '0x0000000000000000000000000000000000000000',
  to: '0x...',
  tokenId: BigNumber { _hex: '0x00', _isBigNumber: true }
}
TokensClaimed
{
  claimConditionIndex: BigNumber { _hex: '0x00', _isBigNumber: true },
  claimer: '0x...',
  receiver: '0x...',
  startTokenId: BigNumber { _hex: '0x00', _isBigNumber: true },
  quantityClaimed: BigNumber { _hex: '0x01', _isBigNumber: true }
}

Wrapping Things Up

And that’s it, congrats! You’ve just created your first event listener on ThirdWeb and you’re ready to start processing contract events! As you can see, the core principals of capturing contract events are fairly simple to set up. In a future article, we’ll get a little further into the weeds of decoding this event data and making it a bit more useful.

Until then, go ahead and give the above a try!

Looking for a reliable partner for your next project?

At SLIDEFACTORY, we’re dedicated to turning ideas into impactful realities. With our team’s expertise, we can guide you through every step of the process, ensuring your project exceeds expectations. Reach out to us today and let’s explore how we can bring your vision to life!

Contact Us
Posts

More Articles

Vision Pro Headset
Contact Us

Need Help? Let’s Get Started.

Looking for a development partner to help you make something incredible?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.