20,000 USDC
View results
Submission Details
Severity: gas
Valid

Use assembly to emit an event

Summary Using assembly to emit an event instead of using Solidity's emit keyword can potentially save gas in certain scenarios. Let's explore how and when this gas optimization can be beneficial.

In Solidity, emitting an event using the emit keyword involves executing a function call to the EVM's event logging opcode. This incurs gas costs due to the overhead of the function call.
By using assembly, you can directly invoke the EVM's event logging opcode, bypassing the Solidity function call overhead. This can result in gas savings, especially when you need to emit events multiple times or in complex scenarios.
Here's an example of using assembly to emit an event:
contract MyContract {
event MyEvent(uint256 value);

function emitEventUsingAssembly(uint256 value) external {
    assembly {
        let eventPtr := mload(0x40)
        mstore(eventPtr, 32)                   // Length of the event data
        mstore(add(eventPtr, 0x20), value)     // Event data

        // Emit the event using the LOG2 opcode
        // LOG2(address, eventPtr, length)
        log2(0, eventPtr, 0x40)                // 0x40 is the size of the event data

        // Free memory
        mstore(0x40, add(eventPtr, 0x60))
    }
}

}

In the above example, the emitEventUsingAssembly function uses assembly to directly invoke the LOG2 opcode to emit the event. The event data is loaded into memory, and the opcode is called with the appropriate parameters.
By using assembly, you eliminate the gas costs associated with the Solidity function call, resulting in potential gas savings.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.