iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📌

Implementing Event Emitting and Listening with Solidity and ethers.js

に公開

By emitting an event on the contract side, you can receive the event notification on the frontend.

As a use case, for example, when a tweet is made, the contract side emits an event at the timing when that tweet is included in a block. The frontend receives that event and updates the timeline. This way, you can eliminate wasteful polling, such as using setTimeout to check for timeline updates at regular intervals.

The contract implementation looks something like this. You define an event and use emit within a specific process to issue the event.

pragma solidity ^0.8.0;
contract Twitter {
    event Tweet(address indexed _from, string _msg);
    function tweet(string memory _tweet) public {
       emit Tweet(msg.sender, _tweet);
    }
}

To receive this notification on the frontend, you can do something like the following. This example uses ethers.js and useDapp. By using provider.once, we subscribe to the event so that we receive notifications from the next block onwards. With contract.on, you can receive the event issued by the emit Tweet defined earlier in the contract. Since the Tweeted event is specified in filters, all events that are emit Tweet-ed will flow in.

import { utils, Contract, ethers } from "ethers"
...
const { library } = useEthers()
const subscribeTweet = async () => {
  const inteface = new utils.Interface(ABI.abi)
  const contract = new Contract(
    `${CONTRACT_ID}`,
    inteface,
    library?.getSigner()
  )
  const provider = new ethers.providers.Web3Provider(library.provider)
  const filters = contract.filters["Tweeted"]
  if (filters !== undefined) {
    provider.once("block", () => {
      contract.on(filters(), (author: string, content: string) => {
      })
    })
  }
}

In the contract defined previously, there is a part where indexed is specified for an event argument. This can be used to filter which events to receive when subscribing to them on the frontend. For instance, if you change the filters() part in the frontend code above to filters(<MY ADDRESS>), only events for your own posts will be received.

For more details, such as where events are stored, please refer to the official Solidity documentation: Contracts — Solidity 0.5.4 Documentation.

Discussion