Macro anchor_lang::emit_cpi

source ·
emit_cpi!() { /* proc-macro */ }
Available on crate feature event-cpi only.
Expand description

Log an event by making a self-CPI that can be subscribed to by clients.

This way of logging events is more reliable than emit! because RPCs are less likely to truncate CPI information than program logs.

Uses a invoke_signed syscall to store the event data in the ledger, which results in the data being stored in the transaction metadata.

This method requires the usage of an additional PDA to guarantee that the self-CPI is truly being invoked by the same program. Requiring this PDA to be a signer during invoke_signed syscall ensures that the program is the one doing the logging.

The necessary accounts are added to the accounts struct via #[event_cpi] attribute macro.

§Example

use anchor_lang::prelude::*;

#[program]
pub mod my_program {
    use super::*;

    pub fn my_instruction(ctx: Context<MyInstruction>) -> Result<()> {
        emit_cpi!(MyEvent { data: 42 });
        Ok(())
    }
}

#[event_cpi]
#[derive(Accounts)]
pub struct MyInstruction {}

#[event]
pub struct MyEvent {
    pub data: u64,
}

NOTE: This macro requires ctx to be in scope.

Only available with event-cpi feature enabled.