0

When testing a contract with Truffle, I have found that the variables that are emitted by the event do not match the values that are passed into the event emission. Why does the event not return the exact value that is passed into it?

For example:

event ExampleEvent(string indexed myString);

function eventTest() public {
    string memory strTest = "Hello, world!";
    emit ExampleEvent(strTest);
}

When eventTest() is called, the event emits 0xb6e16d27ac5ab427a7f68900ac5559ce272dc6c37c82b3e052246c82244c50e4, instead of "Hello, world!". Why is this the case?

2

The reason is because what is being emitted is an indexed dynamic variable, not static. Solidity stores a keccak256-hash when indexing a dynamic variable, so the string you are getting, 0xb6e... is the keccack256-hash of the string "Hello, world!". More information can be seen here in the Solidity docs.


There are two ways you can handle this:

1) Remove the indexed keyword from the event. When a value is not indexed, it returns the true value, even if it is a dynamic variable. If you do this, your code would look as follows:

event ExampleEvent(string myString);

function eventTest() public {
    string memory strTest = "Hello, world!";
    emit ExampleEvent(strTest);
}

In this case, the event emission output would be "Hello, world!".

2) Handle the event emission off-chain by taking the keccack256-hash of the expected output. You can do this by using the util, web3.utils.keccak256("Hello, world!").

Either case is acceptable, and both have their tradeoffs. From the Solidity docs:

For dynamic-length types, application developers face a trade-off between fast search for predetermined values (if the argument is indexed) and legibility of arbitrary values (which requires that the arguments not be indexed). Developers may overcome this tradeoff and achieve both efficient search and arbitrary legibility by defining events with two arguments — one indexed, one not — intended to hold the same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.