📄The Solidity Events Guide I Wish I Had
Welcome to the grand odyssey of Web3, a journey from the familiar shores of Web2 towards the vast ocean of the Ethereum blockchain. Web2, the mainland we've known and navigated for years, is brimming with data cities and information highways. But an exciting adventure beckons us beyond, towards the open sea of decentralization.
Our vessels in this voyage are nodes, sturdy ships that bear the responsibility of carrying supplies across the deep, uncharted waters. These supplies, cryptographic blocks of data and instructions, are destined for the islands, the scattered archipelago of smart contracts, each an autonomous paradise operating under its own rules and logic.
On these islands, tireless robotic workers, algorithms encapsulated within the smart contracts, receive the supplies. With meticulous precision, they use these supplies to construct, verify, and enforce a diverse array of creations, from self-executing agreements to entire decentralized applications.
Yet, how does the mainland stay informed of the activities taking place on these far-off islands? Enter Solidity events. Like messages encapsulated in a bottle, these events carry vital progress reports and significant updates. Once created by the contract robots, they are picked up by the passing node-ships and carried back across the Ethereum ocean, back to the eagerly awaiting inhabitants of the mainland.
So, join us as we set sail into the open sea of the Ethereum blockchain, guided by the stars of Solidity events, exploring the intriguing islands of smart contracts and charting a course towards the thrilling future of decentralization.
~ ChatGPT
Ethereum is a world computer where each node in the network is running an implementation of it's code, and the Ethereum blockchain is the collective agreement of these nodes on what the latest state of the machine is. One key component of the Ethereum computer that is necessary for this consensus of the latest state to be possible is, deterministic state updates. Because Ethereum aims to be decentralized, each node in the network must be able to process the transactions in a new block and have the same resulting latest state as all the other nodes in the network. One of the reasons this can be achieved, is because the Ethereum computer (i.e. the Ethereum Virtual Machine) is sandboxed. This sandboxing means the EVM is limited in capability, so that given a set of inputs, there can only be one output. This is how each node executing the latest transactions can all arrive at the same latest state of the blockchain.
While the deterministic state updates are ideal for achieving consensus, there are some tradeoffs that create unique challenges when combing the worlds of Web2 and Ethereum. One of those limitations is how an Ethereum smart contract can communicate with the world that exists outside of the sandboxed virtual machine all Ethereum smart contract exist in. Part of the reason for this limitation is the indeterministic nature of making a call from the EVM to the outside world. Imagine you had a smart contract that made an API requests to a web API to get the latest price for a pair of assets. When Node A processes a transaction that triggers this API call, it receives a response of 42
and updates it's latest state accordingly. Then when Node B processes the same transaction, the price has changed so it receives a response of 40
, and updates it's latest state accordingly. Then Node C makes the request and receives a 404
HTTP response because the API went offline for a second, how does Node C even update it's state then? Regardless, you can see the bigger issue that a call from the EVM to the world outside of it's sandbox may not always produce the same response. If this was allowed, how is the Ethereum world computer supposed to reach consensus on what the latest state should be when every node in the network could possibly have a different view of the latest state?
To help solve this issue of communication between Web2 and Ethereum, the EVM has allowed for the generation of logs. In Solidity we make use of these logs by emitting events.
Table of Contents
Logging in Ethereum
Under the hood, emitting events in Solidity instructs the EVM to execute one of the following opcodes: LOG0
, LOG1
, LOG2
, LOG3
, or LOG4
(You can view their details here). When an event is emitted, the LOG
opcode generates a log entry that includes the address of the contract that emitted the event, an array of topics, and some amount of data. Topics come from indexed
parameters of the event, and each LOG
opcode has a corresponding number that denotes the number of topics it can handle (from 0 - 4). The data
property of the log comes from non-indexed event parameters, and the restrictions of how much data can be logged are the gas cost of storing the data (currently 8 gas for each byte of data + some other values shown in the images below), and the block's gas limit (even if you were willing to pay for a lot of gas to be used to store your data, it is very possible that your transaction can exceed the total amount of gas allowed to be used in the current block - especially when you consider your transaction may not be the only transaction using the block's gas allowance).
When a LOG
instruction is executed, the generated log entry is stored in the transaction context within the EVM, this is a temporary space used by the EVM to process a transaction before it's finalized. This transaction context holds information about the transaction currently being processed, including any changes made to the state, and any log entries generated. Once the transaction has been processed by the EVM and is ready to be included in the blockchain, a transaction receipt is created. This receipt is a summary of the transaction's execution, including the status, gas used, and logs generated.
Below is an example of a transaction receipt, some data has been omitted for brevity, but you can view the whole receipt here:
From this receipt, we can discern that this transaction emitted a single event (since logs.length == 1
), with 3 topics (since logs[0].topics.length == 3
), and therefore made use of the opcode LOG3
.
Ethereum Log Topics
As mentioned in the previous section, topics come from the indexed
parameters of an event and each LOG
opcode has a corresponding number that denotes the number of topics it can contain (from 0 - 4). These topics provide an efficient way to filter transactions that an event listener may be interested in from all the transactions in a block. But how are they generated?
Each topic has a maximum length of 32 bytes of data, and each topic is encoded to this maximum length, even if the data doesn't occupy 32 bytes. As you can see in the above transaction receipt, we have a topic of
where the actual data, b0b734cfc8c50f2742449b3946b2f0ed03e96d77
is only 20
bytes long, but has been padded with 0
s to reach the 32
byte length.
Solidity events do support data types with values that can exceed this 32
byte max length, such as dynamically sized arrays and strings, and in these cases the keccak256
hash of the values are used as the topic instead of the values themselves.
Named Events
The above transaction receipt is the result of a transaction that interacted with the transfer
function of the Dai Stablecoin contract. We know this because the to
address specified by the transaction is a verified contract on Etherscan for Ethereum mainnet:
If we take a look at the verified contract code for this contract, we can see that on line 95
, an event with the name Transfer
is declared:
We can also see that this Transfer
event has 2 indexed
parameters, src
and dst
and an unindexed parameter, wad
. Going back to our topics
array from our transaction receipt:
you can see that we have 3
topics, when our event only defines 2 indexed
parameters, so what's the third topic? Well in Solidity, when events are given a name like Transfer
, Solidity takes the event signature, hashes it using the keccak256 hashing algorithm, and appends it to the topics
array as the first element. So in our topics
array, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
is the hash of the event signature of our Transfer
method. To further demonstrate this idea, lets follow the process Solidity takes to generate the hash of our event signature. Firstly, what's an event signature?
Event Signature
In Solidity, an event signature is a unique identifier for an event, generated from the event's name and its parameter types. For our Transfer
event, this means line 95
of the verified contract code of the Dai Stablecoin contract:
Now Solidity doesn't just take the above data, hash it, and then boom we have our hashed event signature. Instead, Solidity strips the event signature of it's keywords and argument names first. For our Transfer
event, these stripped values would be:
event
indexed
src
dst
wad
Any spaces
;
So that what we're left with is:
Keep in mind that while the verified contract code uses uint
as the data type for the value
parameter, uint
is an alias for uint256
, and Solidity will use the full type name when generating the hashed event signature, hence we use uint256
below
Now Solidity performs the hashing of the stripped event signature to generate our expected topic value. Using this online keccak256 hashing function, you can see that hashing the stripped event signature does indeed give us the expected value we see as the first element in our log's topics
array
Remaining Event Topics
So, we've got the first element in our log's topics
array figured out, what about the next two? Well we covered that the topics
array contains indexed
event parameters, so the other topics are src
and dst
, but where do these values come from? Well when we look at the transaction receipt on Etherscan, and click the + Click to show more button, we can see the Input Data for this transaction:
Clicking the Decode Input Data button yields us a more digestible version of this input data:
This is the data provided by the user whom submitted this transaction to Ethereum. As you can see, this transaction is calling the transfer
function on the Dai Stablecoin contract with the data: 0xfF07E558075bAc7b225A3FB8dD5f296804464cc1
as the dst
parameter, and 120000000000000000000
as the wad
parameter.
Looking at the verified contract code on Etherscan, we see that the transfer
function exists on lines 122 - 124
:
transfer
is calling another function transferFrom
(from lines 125 - 137
), so I've included this function as well so we have the additional context
One line 135
we see:
which is the exact code responsible for the event we see in our transaction receipt. So when the sender of the transaction calls the transfer
function, it calls the transferFrom
function, passing it msg.sender
for the src
parameter (which is the address of the sender of the transaction), and the provided dst
and wad
parameters. So when the Transfer
event is eventually emitted (i.e. logged) on line 135
, these are the values that are logged to the blockchain and show up in our event log in the transaction receipt.
For clarity, the below code example includes the values of the parameters being passed to the functions and the Transfer
event:
So when looking at our topics
array the log in our transaction receipt:
But why do the src
and dst
values look different than the values we passed when emitting the event? Well if you recall the beginning of the Ethereum Log Topics section:
Each topic has a maximum length of 32 bytes of data, and each topic is encoded to this maximum length, even if the data doesn't occupy 32 bytes.
Addresses are only 20
bytes long, so these values get padded with 0
s so that they become 32
bytes long (which is the length every event topic must be).
And What About the Missing wad Parameter?
Maybe you noticed that when we emit the Transfer
event on line 135
, we're passing values for the src
, dst
, and wad
event parameters, but only src
and dst
show up in the topics
array for the log - what happened to the wad
parameter? Well taking a look at the event signature for Transfer
:
We can see that the wad
parameter is not indexed
. In Solidity, all of the unindexed event parameters are ABI encoded and stored in the event's data
property. Taking a look at the transaction receipt, we can see the value of wad
is padded to 32
bytes and available under logs[0].data
:
The data passed to the Transfer
event was 120000000000000000000
, but Solidity will convert integers to hexadecimal to save space. 120000000000000000000
converted to hexadecimal is: 68155A43676E00000
Anonymous Events
So if the first topic for a named event is the hashed event signature, how could you have an event that uses LOG0
which has no logged topics? Enter the anonymous event!
When declaring an event in Solidity, you have the option of using the anonymous
keyword like so:
When an anonymous
event is emitted, the hashed event signature is not included as a topic in the event's topics
array.
Here is an example transaction receipt's event logs if RegularEvent
was emitted:
If AnonymousEvent
was emitted:
And if AnonymousEventWithParameter
was emitted:
Use Cases
Additional Custom Indexed Parameter
Because the EVM currently only supports the opcodes LOG0-4
, an event log can only have up to four topics
. For named events, the first topic is reserved for the hashed event signature, leaving room for only 3
custom indexed
parameters. If an event is declared anonymous
, the hashed signature is not logged, leaving room for one extra indexed
parameter. This can be useful in specific scenarios where more than 3
parameters need to be indexed.
Gas Savings
Because the event signature is not store in the log, you could reduce the gas cost of emitting an event. For example, if your contract had a limited number of events that could easily be distinguished by the number of event topics like so:
Some, albeit a very small amount, gas can be saved because we can rely on logs[].topics.length
to discern which anonymous event was emitted.
Obfuscation
Anonymous events can make it harder for someone examining the blockchain to determine what kind of event was emitted, as the event signature isn't included in the log. This could be seen as a way to obfuscate the actions of a contract, although it should be noted that it's generally considered best practice for smart contracts to be transparent in their operations.
For instance, take these two events:
If a contract were to emit several Decoy
events with one SuperSecret
event, it would make it difficult to tell what the actual secret was when reviewing just the logs of the transaction updating the secret. In the following logs, could you tell which is the SuperSecret
event as opposed to the Decoy
events?
Not that this is a concrete example, but it goes to show a potential use case of anonymous events.
Caveats
Difficulty Filtering Transactions
Probably the biggest deficiency of anonymous events is that it makes it difficult to filter transactions using them. As discussed in the above Obfuscation example, how would you be able to filter transaction that only update the secret and emit the SuperSecret
event? You wouldn't be able to without some additional knowledge of the contract that isn't apparent by just looking at the transaction receipt. You can, however, work around this limitation as discussed in the Gas Savings section, that uses different number of event topics to discern the different events.
Event Impersonation
Also depicted in the Obfuscation section, without the hash of the event signature acting as an event log's unique identifier, anonymous
events with the same event parameters are identical in structure when they are logged. So, it could look like a SuperSecret
event was emitted, but in actuality, all the events could be Decoy
events and you'd have no way of telling. This could be dangerous if a specific anonymous
event is being relied on to perform some off-chain action, and a fake event with the same indexed event parameters is emitted instead.
What Happened to My indexed
String?
indexed
String?While we're on the topic of event topics
, I want to point out a quick gotcha if you attempt to use string indexed
in your event. At some point you're going to want to emit an event with some string
value, and you're probably going to want to use indexed
because it's an important string for your dApp to have access to. This scenario will look similar to:
Now when we call this emitMyString
function, you're probably expecting to see something like:
Well...maybe you weren't expecting that because that's not our string, Super important string
An Aside About ABI Encoding
So if we emitted, Super important string
as our string
value, why would we expect to see this monstrosity, and not just Super important string
?
Well this is because of something called ABI Encoding, and I could write a whole other article diving into this topic, but for now I'll keep the explanation relatively brief.
So What is ABI Encoding? Well for starters, lets get an explanation from ChatGPT:
The Ethereum Application Binary Interface (ABI) is a standard for how data is encoded and decoded between the high-level code in a smart contract and the low-level machine language of the Ethereum Virtual Machine (EVM). It dictates the method for converting higher-level data types, like strings and arrays, into a standardized format that the EVM can process. This includes specifying how function calls, including their name and arguments, are encoded into byte arrays for the EVM. ABI plays a crucial role in interacting with smart contracts, allowing users and external programs to understand the contract's structure, functions, and variables, and interact with them accordingly.
So basically, ABI encoding is how we convert human readable data into standardized machine readable data the EVM can understand. To further this point, lets break down the process of how we get from Super important string
to it's ABI encoded representation.
First we need to understand that Super important string
is already using a form of data encoding called UTF-8. I've linked an article that gets pretty in-the-weeds of what UTF8 is and why we use it, but lets get ChatGPT to summarize:
The UTF-8 standard represents each character as a unique sequence of one to four bytes. ASCII characters (which include all the alphanumeric characters and some symbols) are a subset of UTF-8 and are represented as a single byte.
So, our first step in converting our human readable string into machine readable data is to convert our UTF-8 string into it's byte representation. Because we're using the ASCII subset of UTF-8, we know that each character is represented using 1
byte, but how do we do convert UTF-8 into bytes?
Well a straightforward solution that Ethereum has chosen to utilize is to use hexadecimals to represent each byte. You can look here to view a table that converts UTF-8 characters into hexadecimal bytes. Using this table, we can see that converting our string into hexadecimal bytes would look something like:
Putting the above together into a single line we get: 537570657220696d706f7274616e7420737472696e67
. A keen eye will notice that this combination of hexadecimal bytes is actually present in the ABI encoded data we're building up to:
So if we have found our ABI encoded string, what's the rest of the data there for? Well the EVM was built to work with 32
byte chunks of data, also called words. If you recall back to the beginning of the Ethereum Log Topics section, each event topic is also 32
byte words. So lets take the complete ABI encoding of our string and break it into these 32
bytes words:
Excluding the 0x
at the beginning of the data (which is just a prefix to denote that the following data is to be interpreted as hexadecimal), we have 3 EVM words:
0000000000000000000000000000000000000000000000000000000000000020
: Removing all the0
s from this first word, we get20
. Converting this from hexadecimal to a integer, we get32
. This first word is telling the EVM that there exists some data32
bytes from the beginning of this data blob. So starting from the0
after the prefix0x
, we count32
bytes (64hexadecimal
characters since1
byte is represented by2
hexadecimal characters) and we arrive at...0000000000000000000000000000000000000000000000000000000000000016
: Removing all the0
s from this second word, we get16
. Converting to an integer, we get22
. This second word is telling the EVM that there exists some data that's22
bytes long. So the EVM loads the next word...537570657220696d706f7274616e7420737472696e6700000000000000000000
: As you may already recognize, this is our string,Super important string
, encoded into it's hexadecimal format of the UTF-8 characters. The remaining0
s following our data is ensuring that our EVM word reaches the expected32
byte length (since our string is only22
bytes long)
So to summarize, our giant data blob is telling the EVM: We have some data that may not fit into a single 32
byte EVM word. This data begins 32
bytes from the beginning of this data blob, this data is 22
bytes long, and then finally it gives the EVM the data to parse and using the information we gave it, so it parse 22 bytes
and gets our hexadecimal UTF-8 string.
Why So Much Data to Represent our 22
Byte String?
22
Byte String?You may be wondering why we need the first 2 EVM words to understand our hexadecimal encoded string. Well this is because string
s can have an indeterminate length. Other values such as uint
s and int
s can fit into 32
byte EVM words because the maximum length of these values is 32
bytes (e.g. a uint256
is 256
bits long, 256
bits is 32
bytes (8
bits = 1
byte, so 256
/ 8
= 32
)).
While our string, Super important string
, fits into a 32
byte EVM word, we can easily imagine a string
so long that's no longer the case. Take supercalifragilisticexpialidocious
for instance. That string is 34
UTF-8 character long (i.e. 34
bytes long), which is just long enough to exceed a 32
byte EVM word (2
bytes too long). So, the ABI encoded version of supercalifragilisticexpialidocious
would be:
Without the first 2
EVM words telling us where our string
data starts and how long it is, we're left with:
Now if this is all the EVM had to work with, it would assume each 32
byte word is separate data, meaning our original word would be treated as two separate words:
supercalifragilisticexpialidocio
(737570657263616c6966726167696c697374696365787069616c69646f63696f
)us
(7573000000000000000000000000000000000000000000000000000000000000
)
So to avoid splitting our string
s into multiple words based on every 32
bytes, we tell the EVM where our string
data begins, and how many bytes it is. In the case of supercalifragilisticexpialidocious
, the second EVM word says it's 34
bytes long (0x22
= 34
), so the EVM parses the next 34
bytes as our string data (which is the entire 32
bytes of the third word, and 2
bytes of the fourth EVM word).
What Actually Happens to indexed
Strings
indexed
StringsWell we know that event topics
must be 32
bytes long, but string
s can be a length that exceeds 32
bytes, so what happens when you emit an event with a indexed
string parameter? Put simply, we use the keccak256 hash of the string value and use that as the topic
. This is possible because keccak256 hashes are always 32
bytes long, so this strategy will always work, regardless of how long our string data is.
Going back to our indexed
string event example:
When emitMyString
is called, our event log will actually look like:
Where 8415478cebd2e698dbda720fc2a07faf3d46dc907f1cc27ccd5cbc61609eea21
is the hash of Super important string
:
The Caveat of Using indexed
Strings
indexed
StringsWhile it's still very much possible to filter transactions using the hash of the original indexed
string data, only having the hash won't be very helpful if you need to use the original string data somewhere such as displaying it in your dApp. There is a convenient workaround for this though, by not using indexed
for you string event parameter, the emitted string data will be ABI encoded and will be available under the event log's data
property (logs[].data
):
Now when emitMyString
is called, our event log will look like:
Where logs[0].data
is the same data
we went over in the So What is ABI Encoding? section, and logs[0].topics[0]
is still the keccak256 hash of our WhatHappenedToMyString
event signature.
Event Data
We've actually already covered how we get an event log's data
in the An Aside About ABI Encoding section. For all the event parameters that are not indexed
, their values are ABI encoded and set as the data
property for the log event.
Lets just walk through a few examples to solidify this concept.
Emitting No Data
Because we're not emitting any un-indexed
data in NoEventData
, our data
property for our event log is simply: 0x
(meaning there is no data). The topic, 0x40271e61fe9aea6d3aa373c6769bd7b87bcbdfe249455c028ebb26ab321a4eeb
, is our keccak256 hashed event signature (keccak256(NoEventData())
.
Emitting Values Types
Something we didn't explicitly cover in the An Aside About ABI Encoding section, is the difference between Value and Reference types in Solidity.
Value types are data whose values fit into 32
byte EVM words. These types include:
bool
(A boolean is1
byte)uint
(Unsigned integer ranging from8
to256
bits, which is1
to32
bytes)int
(Signed integer ranging from8
to256
bits, which is1
to32
bytes)address
(An Ethereum address is20
bytes)bytes1
,bytes2
,bytes3
, ...,bytes32
(Fixed-size byte arrays, ranging from1
to32
bytes)enum
(User defined types with a finite number of values)
What this means is that Solidity can actually make use of this data without having to worry about the data being longer than 32
bytes (i.e. longer than a single EVM word). It also means that when Solidity uses a value type, like assigning it to a variable or passing it to a function/event, it utilizes a copy of this data instead of modifying the original.
As an example of the copying of value typed data, take a look at this makeACopy
function:
When we assign copy
to equal original
(uint256 copy = original;
), what Solidity is doing under the hood is taking the value of original
, making a copy of the data, and then assigning it to the variable copy
. So when we call this function, the first number returned to us will always be the number we called this function with, while the second number is the one we modified:
So, when we emit these value types as un-indexed
event parameters, we'll the see the value in the event log's data
property contained in single 32
byte EVM words. We won't see the extra two EVM words we discussed in the Why So Much Data to Represent our 22 Byte String? section explaining to the EVM where to find our value and how long it'll be.
Calling the emitEvent(42)
function will yield an event log like so:
Where logs[0].data
is a copy of the data we gave emitEvent
(0x2a
= 42
).
For the sake of clarification, lets emit another event with several of these value types:
Calling emitEvent
like so:
Would yield us the transaction log event:
And if we break logs[0].data
into 32
byte EVM words we get:
Emitting Reference Types
Reference types are what they sound like, they contain information that references where the data is being stored (also called a pointer, because this reference points to where the data is). We covered the reason for this distinction in the An Aside About ABI Encoding section, but essentially, reference typed data can be longer than our 32
byte EVM words, so we have to tell the EVM where the data starts and how long it is to ensure we don't loose any of the data (like when we cut off the last 2
bytes of supercalifragilisticexpialidocious
by only reading a single EVM word).
Reference types are data whose values can exceed a single 32
byte EVM word. These types include:
string
(Dynamic sized UTF-8 encoded string)bytes
(Dynamic sized byte array)array
(Dynamic sized arrays)struct
(User defined data structures)
So when these reference types are emitted as un-indexed
event parameters, they are ABI encoded and are appended to the event log's data
property (the same as value types, but we've also got the extra location and length data).
Calling emitEvent
like so:
Would yield us the transaction log event:
And if we break logs[0].data
into 32
byte EVM words we get:
Emitting Value and Reference Types
You can also emit any mixture of these types, and all the event parameters will be ABI encoded and made available under the data
property of the event log.
Calling emitEvent
like so:
Would yield us the transaction log event:
And if we break logs[0].data
into 32
byte EVM words we get:
Retrieving Past Dai Transfer Event Logs Using Web3.js
You can use several libraries to retrieve past event logs using JavaScript/TypeScript, such as ethers.js and viem, but for this guide I'm opting to use the latest version of web3.js, version 4.x
.
Earlier in the Ethereum Log Topics section we were looking at the Transfer
event log for the Dai contract. Lets write some code to retrieve past event logs using web3.js:
The code for this example can be found here
Running this code will console.log
something similar to:
Keep in mind that you may not receive any logs if there were no Dai transfers in your specified block range. If you run this example and receive the response: []
, trying increasing the NUMBER_OF_BLOCK
variable. However, also keep in mind that the larger your block range, the larger your response could be.
Something interesting about this Dai Transfer
past log fetcher we just setup, is by removing a single line, the address
property from our filter object, our fetcher goes from only getting Dai Transfer
events, to getting all Transfer
events from any ERC-20 (technically any contract that emits an event with the signature Transfer(address,address,uint256)
):
This past log fetcher is now configured to get any past event logs within our specified block range that contains the topic TRANSFER_EVENT_TOPIC
, regardless of what contract emitted the event.
Something like this could be useful if you wanted to get all the ERC20 transfers for a specific block range. However you would most likely need to do additional filtering, to remove any event log from a contract that's not an ERC20. To demonstrate this issue, our above code would capture the following event log created from the below code:
Calling emitEvent
like so:
Would create the event log:
That would get captured by our past log fetcher, because the only data we're filtering on is TRANSFER_EVENT_TOPIC
.
Listening to New Dai Transfer Events Using Web3.js
Being able to fetch for past event logs can be useful, but using web3.js, we can also subscribe to events as they happen. One key difference between subscribing to new events v.s. request for past events, is we need to use the WebSocket protocol (WS) over HTTP. This is because we are now subscribing to new events and need to keep an open line of communication between our code and our Web3 provider, and the WebSocket protocol was built to facilitate this. If you attempt to subscribe to event log using an HTTP provider with web3.js, you should see an error like so:
Now onto the correct implementation of listening to new Transfer
events:
The code for this example can be found here
Some other differences between the above code and the code for fetching past events include:
DAI_ABI
- The Application Binary Interface (ABI) is a JSON object that describes how the related contract can be interacted with. This interface includes the event signatures which is why we no longer need theTRANSFER_EVENT_TOPIC
from the fetcher example. web3.js is able to compute theTransfer
event topic using the provided contract ABI. The part of the ABI that specifies the event signature for theTransfer
event looks like:
You can see how web3.js is able to piece together the correct Transfer
event signature by taking each type
for each input from inputs
with the name
of the event. You may be wondering how I found the ABI for the Dai contract, and while there are multiple ways to obtain the ABI for a contract, because the Dai contract is verified on Etherscan, on the Contract Code page you will find the Contract ABI
section where I copied the ABI from:
We're instantiating an instance of
Contract
- As mentioned in the previous section, you could remove theaddress
property to fetch past events for any transaction that emitted aTransfer
event instead of those that only interacted with the Dai contract. However, that is not possible with this code example because we're instantiating an instance of web3.js'Contract
class specifically for the Dai contract since we're usingDAI_ABI
andDAI_VERIFIED_ADDRESS
. So, we'll only receive event logs forTransfer
events from the Dai contract, all otherTransfer
event logs from other contracts will be ignored.
Running this example's code will console.log
something similar to:
Keep in mind that you won't not receive any logs until there are transactions that call the transfer
function from the Dai contract in the latest block.
Listening to Your Contract's Events Using Web3.js
You might also be interested in subscribing to new events for your own contract. Well the code to do this is almost exactly the same as the code from the previous section:
The code for this example can be found here
YOUR_CONTRACT_ABI
- This is going to be the ABI for the contract you're deploying that you'd like to listen to events for. This ABI can be obtained using other libraries such as solc-js, or you can even make use of web3.js' new plugin functionality and use a plugin called web3-plugin-craftsman to be able to instantiate a web3.jsContract
instance using your contract's Solidity source files directlyYOUR_CONTRACTS_DEPLOYED_ADDRESS
- This would be the address for an already deployed instance of your contract, whether it be on mainnet Ethereum, a test network, or another EVM compatible chain. If you're interested in deploying your contract and setting up an event listener all in one go, the following web3.js code does just that:
The code for this example can be found here
YOUR_CONTRACT_BYTECODE
- A contract's bytecode is a low-level representation of your contract, it's what guarantees that the contract will always behave in the same way, regardless of the Ethereum client or the programming language that was used to write the contract. It's a hexadecimal string that does two things:Constructor Bytecode (or Initialization Code): This part is run only once, during contract deployment. It typically includes code that sets the initial state of the contract. After the contract is deployed, the constructor bytecode is not stored on the blockchain, only the runtime bytecode remains.
Runtime Bytecode: This is the part of the bytecode that is stored on the blockchain and executed every time someone interacts with the contract. It consists of the compiled version of the contract's functions and the state variables. Your contract's bytecode is likely to be obtained using the same software you use to compile your contract's ABI. Alternatively the previously mentioned web3-plugin-craftsman will also handle the implementation detail for you
References
Last updated