events module provides types for publishing events from smart contracts. Events allow contracts to emit notifications about important state changes or actions.
Overview
Access event publishing functions throughenv.events() in your contracts. Events include topics (for indexing) and data.
Types
Events
Publishes events for the currently executing contract.env.events() in contract code.
Functions
publish_event
Publishes an event defined using the#[contractevent] macro.
#[contractevent] macro for type-safe events.
Example:
publish (deprecated)
Publishes an event with topics and data.#[contractevent] and publish_event instead for better type safety.
Parameters:
topics- Event topics for indexing (tuple or Vec)data- Event data (any serializable value)
Topics
Event topics are used for indexing and filtering events. Topics can be specified as:()- No topics(T,)- Single topic(T1, T2)- Two topics(T1, T2, T3)- Three topics(T1, T2, T3, T4)- Four topicsVec<T>- Any number of topics
Topic Restrictions
Topics must not contain:VecMapBytes/BytesNlonger than 32 bytes- Contract types (types defined with
#[contracttype])
Event Trait
TheEvent trait is automatically implemented for types annotated with #[contractevent].
Examples
Simple Event
Event with Multiple Fields
Using Event Publish Method
Test Utilities
When thetestutils feature is enabled, additional functions are available for testing events:
all
Returns all contract events emitted during the last invocation.ContractEvents
A collection of contract events for testing.events() -> &[ContractEvent]- Returns events in XDR formfilter_by_contract(&self, addr: &Address) -> Self- Filters events by contract address
Best Practices
- Use #[contractevent]: Always use the
#[contractevent]macro for type-safe, well-structured events - Keep topics small: Topics are for indexing - keep them simple and under 32 bytes
- Use descriptive names: Event names should clearly describe what happened
- Include relevant data: Add all data needed to understand the event context
- Document events: Document what triggers each event and what the fields mean
See Also
- #[contractevent] - For defining events
- Env - For accessing events
- Address - Often used in events