Smart Contract Events vs Server-Side Events | by Mayowa Obisesan | Nov, 2023

Hey guys,

Generated by Bing Image Creator — Powered by Dall-e 3

If you are a web2 developer, you must have tried your hands on real-time applications before. For that to happen you will most likely settle for either SSE or WebSocket. The latter is more commonly used for real-time software. as it allows for two-way communication. But there is a catch. Working with WebSocket is no easy feat. Deploying a WebSocket application is even more tricky. If you’ve ever experienced any of this, you will appreciate how convenient events in web3 are.

Events in web3 are similar to Server-Side Events (SSE) more than WebSocket. In fact, they are basically web3 server-side events.

You might ask, if Web3 Events are SSE in web2, then what makes it special? The answer is the Setup.

In a Solidity smart contract, to define an event, just do this:

contract EventTest {
string name;

// Declare the Event called NameSet
event NameSet(string name);

function setName(string memory _name) public view {
name = _name;
emit NameSet(_name); // Emit the event called NameSet
}
}

This contract is a simple one. It defines a setter function that sets a name and emits an event. That’s it. You have successfully defined an equivalent of an SSE in web2. For perspective let me show how to define SSE in Python programming language using FastAPI( — that supports it out of the box).

import asyncio
from fastapi import FastAPI
from fastapi.requests import Request
from sse_starlette import EventSourceResponse

app = FastAPI()

@app.get("/stream")
async def ping_summary(request: Request):
async def event_generator():
await asyncio.sleep(STREAM_DELAY)
return EventSourceResponse(event_generator())

Even with the reputation of Python achieving similar results with less code. You cannot deny the simplicity of Smart contract Events.

Apart from the simplicity of defining events, deploying the Smart contract events are native to deploying smart contracts. No external libraries are needed to implement Event emission. In fact, no imports are needed to implement events, just define the events, deploy to testnet, mainnet or local nodes and it works the same way. And that’s it, you have implemented events. Cool right?

Let’s compare this to web2 events.

To set up SSE in web2, you need two setups.

  1. The EventSource API. In JavaScript, you need to fetch SSE using the EventSource API that JS provides.
  2. The StreamingResponse. The server must provide a streaming response not the conventional JSON response nor the HTTP response. A streaming response and this mean both the server and client must be configured to provide and fetch a streaming response.

Of course, the setup is not the problem in fact. The problem is in the deployment on a remote server and not locally. That’s where you begin to feel the work. For you to understand why web3 event is beautiful, let’s see how you will need to deploy a web2 event-based application.

You need to get a dedicated server that will allow you to run your own instance of your streaming program. Not all free platforms will allow you to host a streaming program. Believe me, I’ve tried. That means you will probably need a paid cloud server to test your streaming program. Once you’ve gotten the server you’ll need and probably paid for it, then you need to fetch the streamed data using EventSource API or any other JS API to fetch this data before it can be used on the web.

I’m sure you can see why I appreciate web3 Events so much. It’s impressive.

Let’s move on to the next phase of working with Events in both web2 and web3.

This also seems simple if you think about it. But let’s compare this to web3 Events. You start with writing your Smart contract and testing locally, all that’s needed is to emit events, as many as possible from your contract. For deployment, deploy to testNet or mainNet as you would a contract without event. Then connect with your contract using React or a provisioned SDK, and to get the events data, use a provided event listener. That’s all.

All you need is a smart contract which emit events of any data type and a listener to retrieve the event once it is emitted. That’s it.

Let’s talk about consuming the events. After I have written the code and deployed the code. I want to consume the event(s) from the client-side. Which is easier? Web2 or web3?

To be honest, they are fairly the same. Assume I decide to use React to build my frontend, let compare the web2 and web3 implementations for consuming the respective deployed events. Let’s start with web2 consumption. To consume web2 deployed events, I have to use the EventSource API natively provided by JavaScript to fetch the events. Here’s an example of how to use EventSource.

const useSummary = () => {
const [ summary setSummary ] = useState([]);
const [ listening, setListening ] = useState(false);

useEffect( () => {
if (!listening) {
const eventSource = new EventSource(`${process.env.REACT_APP_BASE_URL}/summary`);
eventSource.onopen = () => {
console.log("Opened Event stream");
}
eventSource.onmessage = (event) => {
let eventData = JSON.parse(event.data);
setSummary((summary) => summary.concat(parsedData));
}
eventSource.onclose = () => {
console.log("Event stream closed");
}

setListening(true);
}
}, [listening, summary]);
}

In web3 however, the implementation is quite different. There’s an event listener provided by the web3 frontend libraries or SDK to listen for events from the web3 nodes. Here is a sample event listener script.

const usePosts = () => {
const [posts, setPosts] = useState([]);
const { provider } = useConnection();

useEffect(() => {
// Listen for event
const handleCreatePostEvent = (id, poster, content, timePosted, tips) => {
setPosts([
{
id: id,
poster: poster,
content: content,
timePosted: Number(timePosted),
tips: tips
},
...posts,
]);
};
const contract = getInkContractWithProvider(provider);
contract.on("NewPost", handleCreatePostEvent);

return () => {
contract.off("NewPost", handleCreatePostEvent);
};
}, [posts, provider]);
}

Yea, as I said, quite similar.

The only significant code here is these lines:

const contract = getInkContractWithProvider(provider);
// This line listens for an event called NewPost defined in the smart contract
contract.on("NewPost", handleCreatePostEvent);

return () => {
// The event is being cleaned here
contract.off("NewPost", handleCreatePostEvent);
};

You can see that implementing events in web3 is basically a breeze.

Let’s leave all the technical details aside. Let’s imagine a real-life scenario — the metaverse. The metaverse is a perfect place to appreciate events in real-life. The metaverse is a virtual world. It allows to live your life virtually and as the real-world, everything should happen spontaneously following the laws of cause and effect and following the laws of “For every action, there is an equal and opposite reaction”. This is exactly what events can help achieve. For every action you perform in the metaverse, there is a reaction to that action. That reaction are the Events emitted. It is easy to see how events can help the metaverse function even at scale.

Imagine you in the metaverse. You have a land, you have friends, you have connections, you have assets. The moment you interact with all of these, your state in the metaverse should be updated to reflect the changes that have been made to any and all of these assets you own. This is the beauty of web3 Events. They make it easy to get events on any entity at scale. Because both L2 and L1 chains have these event feature builtin.

The metaverse and events are probably inseparable. The metaverse is really what I want to spend the next few years contributing to and I believe that web3 smart contracts on both L1s and L2s and L3s and L0s can help make this happen. I truly appreciate this feature of web3 smart contracts.

I hope you have learnt something about Events in this article.

You can check out my other articles about everything Technology, programming, Web3 and Software in general.

Thank you for reading.

https://medium.com/@mayowaobisesan/smart-contract-events-vs-server-side-events-385c0b3b3020

Related Posts