Events
Events enable data to be recorded publicly on the blockchain. Each log entry includes the contract’s address, up to four topics, and binary data of arbitrary length.
Stylus Framework makes events compatible with the EVM event model, allowing seamless interaction between Move contracts and EVM-based tools and libraries.
Declaring Events
Events are common structs annotated with the #[ext(event(..)] attribute. This attribute indicates that the struct is intended to be used as an event.
#[ext(event(indexes = 2))]
public struct Event has copy, drop {
a: u32,
b: address,
c: u128,
d: vector<u8>,
}
Events must have the copy and drop abilities. In the example above, the Event struct has four fields: a, b, c, and d. The indexes = 2 parameter specifies that the first two fields (a and b) will be indexed topics in the event log.
You can also declare events as anonymous by annoating anonymous inside the event attribute:
#[ext(event(indexes = 2, anonymous))]
public struct Event has copy, drop {
a: u32,
b: address,
c: u128,
d: vector<u8>,
}
An anonymous event does not include the event signature as the first topic in the log entry.
Note
If an event struct has more indexed fields than allowed (maximum of 4 for anonymous events, maximum of 3 for non-anonymous events), the Move compiler will raise a compilation error.
Emitting Events
To emit an event, use the stylus::event::emit function followed by an instance of the event struct.
use stylus::event::{Self};
public fun emit_event_example() {
let event_instance = Event {
a: 42,
b: @0x1,
c: 1000,
d: vec![1, 2, 3, 4, 5],
};
stylus::event::emit(event_instance);
}
In the example above, the emit_event_example function creates an instance of the Event struct and emits it using the stylus::event::emit function. The emitted event will be recorded on the blockchain with the specified indexed topics and data.
Warning
If an event struct is not annotated with the
#[ext(event(..)]attribute, it will not be recognized as an event, and attempting to emit it will result in a compilation error.