This content originally appeared on Level Up Coding - Medium and was authored by Sicong Zhao
Blockchain Development Tutorial 03
Getting the state of on-chain operations can be important for various applications. When users play with your dApp (staking tokens, minting NFTs, etc), to provide an interactive user experience, you need to monitor on-chain events.
In this tutorial, I will introduce how to listen to the on-chain event. You might be surprised by how simple it is. Overall, there are only two steps to set up the monitor:
- Define and emit events in the smart contract.
- Define and register event listeners in your frontend.
Step1. Define and emit events in the smart contract.
Let’s imagine we are building an NFT project. You want to know when an NFT is being minted, and get the user’s address and the corresponding NFT token id. Below is how to define such an event.
Then you can emit the event in your smart contract by the following code. You might change the variables based on the context of your smart contract. Here I use msg.sender and nftTokenId just for the illustration purpose.
Step2. Define and register event listeners in your frontend.
My go-to framework for web development is Vue.JS (Vue 3), so I will use it for this tutorial. But the concept is universal, and the JavaScript code should be very similar.
Below is the code that sets up the event listener in your frontend.
- In line 3, it calls getContract function (defined elsewhere in the code, see Appendix below) which returns an ethers.contract object, its documentation is here.
- In line 5, we use the on method of ethers.contract object to subscribe to event calling listener when the event occurs. Here we provide two inputs to this method: (1) the event name NFTMinted, the same as defined in the smart contract. (2) a callback function, in which you can specify your frontend logic which will be triggered when the event occurs.
Now that we have the event listener function, the last thing to do is to actually call this function when users connect to their wallet.
Appendix
Parting Words
There you have it! I hope this tutorial helped you understand how websites listen to on-chain events. Please feel free to leave a comment if you have any questions or suggestions. If you want me to write other topics about blockchain development, please also let me know!
Want to Connect?Please feel free to reach out (my LinkedIn).
How to Monitor On-chain Events was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Sicong Zhao
Sicong Zhao | Sciencx (2022-03-09T02:33:13+00:00) How to Monitor On-chain Events. Retrieved from https://www.scien.cx/2022/03/09/how-to-monitor-on-chain-events/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.