Emit Events
Learn how to emit events in Anchor programs using emit! and emit_cpi! macros.
Examples
Anchor provides two macros for emitting events in your programs:
emit!()
- Emits events directly to program logs. This is the simpler, though program logs may be truncated by data providers in some casesemit_cpi!()
- Emits events through a Cross Program Invocation (CPI) by including the event data in the instruction data.
The emit_cpi()
approach was introduced an alternative to program logs, which
can sometimes be truncated by data providers. While CPI instruction data is less
likely to be truncated, this approach does incur additional compute costs from
the Cross Program Invocation.
emit
The
emit!()
macro provides a way to emit events through program logs. When called, it:
- Uses the
sol_log_data()
syscall to write the data to program logs - Encodes the event data as a
base64 string
prefixed with
Program Data:
To receive emitted events in your client application, use the
addEventListener()
method. This method automatically
parses and decodes
event data from the program logs.
Example usage:
The following is the output of the program logs. The event data is base64
encoded as Zb1eU3aiYdwOAAAASGVsbG8sIFNvbGFuYSE=
.
Ensure the RPC provider you use does not truncate the program logs from the transaction data.
emit_cpi
The
emit_cpi!()
macro emits events through Cross Program Invocations (CPIs) to the program
itself. The event data is encoded and included in the CPI's instruction data
(instead of program logs).
To emit events through CPIs, you need to enable the event-cpi
feature in your
program's Cargo.toml
:
Example usage:
The
event_cpi
attribute must be added to the #[derive(Accounts)]
struct for the instruction
instruction that emits events using the emit_cpi!()
macro. This attribute
automatically includes additional accounts
that are required for the self CPI.
To get the emitted event data in your client application, you need to fetch the transaction using the transaction signature and parse the event data from the CPI instruction data.
Below is an example transaction showing how event data appears in the
transaction details. When using emit_cpi!()
, the event data is encoded and
included in the data
field of an inner instruction (CPI).
In the example transaction below, the encoded event data is
"data": "6AJcBqZP8afBKheoif1oA6UAiLAcqYr2RaR33pFnEY1taQp"
in the
innerInstructions
array.
Currently, event data emitted through CPIs cannot be directly subscribed to. To access this data, you must fetch the complete transaction data and manually decode the event information from the instruction data of the CPI.