I would love a primer on
The difference between listening to events being emitted from my program vs listening to program logs
The pros and cons of using either
If you mean anchor events i'm pretty sure they do the same thing as logging and listening to program logs. They log smth and in the client listen to the logs via ws connection. (https://github.com/coral-xyz/anchor/blob/master/lang/attribute/event/src/lib.rs#L114)
So only advantage of events is that its straight forward to use. Both use high CU due to logging and are not super performant i think.
A different way of achieving smth similar if you don't need to save the events in the ledger for later use would be having an events array in an account and listing to that one via ws connection. That costs some extra space though. So would be good to know your use case.
Here is an example: https://github.com/solana-developers/solana-game-examples/blob/main/seven-seas/program/programs/seven-seas/src/state/game.rs#L76
#[account]
pub struct GameActionHistory {
id_counter: u64,
game_actions: Vec<GameAction>,
}
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct GameAction {
action_id: u64, // 1
action_type: u8, // 1
player: Pubkey, // 32
target: Pubkey, // 32
damage: u64, // 8
}
And then you can add new event for example like this:
fn add_new_game_action(
&mut self,
game_actions: &mut GameActionHistory,
game_action: GameAction,
) {
{
let option_add = self.action_id.checked_add(1);
match option_add {
Some(val) => {
self.action_id = val;
}
None => {
self.action_id = 0;
}
}
}
game_actions.game_actions.push(game_action);
if game_actions.game_actions.len() > 30 {
game_actions.game_actions.drain(0..5);
}
}