Consider the following Solidity contract snippet that emits an event. What will be the output when the triggerEvent function is called?
pragma solidity ^0.8.0; contract EventTest { event NumberSet(uint indexed number); function triggerEvent() public { emit NumberSet(42); } }
Events in Solidity are used to log information on the blockchain and do not return values from functions.
The emit keyword triggers the event NumberSet with the value 42. This event is logged on the blockchain and can be listened to by external applications. The function itself does not return any value.
When testing events emitted by smart contracts, which of the following is correct?
Think about how events are stored and accessed after a transaction.
Events are stored in the transaction logs on the blockchain. Testing frameworks can access these logs after the transaction is mined to verify that the correct events were emitted with expected data.
Given the following test code snippet for a Solidity contract event, why does the test fail to detect the event?
const tx = await contract.triggerEvent(); const receipt = await tx.wait(); const event = receipt.events.find(e => e.event === 'NumberSet'); assert(event.args.number === 42);
Check the exact spelling and capitalization of the event name in the contract and test.
Event names in Solidity are case-sensitive. If the emitted event is named 'Numberset' but the test looks for 'NumberSet', the event will not be found, causing the test to fail.
Choose the correct Solidity code snippet that declares an event with two parameters and emits it properly.
Remember that events must be declared with a semicolon and emitted with the emit keyword including all parameters.
Option B correctly declares the event with a semicolon and emits it with both parameters using emit. Option B misses the semicolon after the event declaration. Option B does not use emit. Option B emits the event with missing parameters.
Given the following Solidity function, how many events are emitted and what are their values when multiEmit() is called?
pragma solidity ^0.8.0; contract MultiEvent { event Log(uint indexed id, string message); function multiEmit() public { for (uint i = 1; i <= 3; i++) { emit Log(i, string(abi.encodePacked("Event", uint2str(i)))); } } function uint2str(uint _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bstr[k] = bytes1(temp); _i /= 10; } str = string(bstr); } }
Look at the loop and how the event is emitted each iteration with the current index.
The function emits the Log event three times with the index from 1 to 3 and the message "Event" concatenated with the index number. The helper function uint2str converts the number to a string correctly.