- Published on
Working with an Indexed String in Web3 Events
- Authors
- Name
- Yair Mark
- @yairmark
In Solidity, you can index events which make for easier lookup of that event later. For example, say I have the following event:
event SomeEvent(string indexed name, uint8 indexed age);
On the web3 side age
behaves as expected it comes back as a BN (BigNumber).
But String is not so obvious it comes back as some sort of encoded value. Using web3.utils.toAscii
and web3.utils.toUtf8
do not work.
After a bit of Googling, I came across this issue. It turns out strings in events (possibly only strings that are indexed) are Keccak-256 hashed. This makes sense as strings can be any length and hashing them forces them to always be the same length making it easier to index.
This means that if the name was John
you would have to filter on web3.utils.sha3('John')
(0xbc99422d9e0abdd8ab52ce43a39333e401a87a9afa547572ea407e5699240479
). Hashes by definition are one-way functions meaning you cannot reverse the conversion hence you need to filter the other way around.