1

I have used the emit macro in Anchor to emit events from the smart contract as follows,

use anchor_lang::prelude::*;

// handler function inside #[program]
pub fn initialize(_ctx: Context<Initialize>) -> Result<()> {
    emit!(MyEvent {
        data: 5,
        label: [1,2,3,4,5],
    });
    Ok(())
}

#[event]
pub struct MyEvent {
    pub data: u64,
    pub label: [u8; 5],
}

Now I want to subscribe to these events from my TS frontend. I want the ability to subscribe to new events as well as the ability to query past events. Is this possible on Solana and if so, how can I do this?

2 Answers2

2

The final answer I found was using getSignaturesForAddress on your program, followed by getTransaction for each one returned, and then looking through the logMessages for MyEvent.

For further reference,
https://docs.solana.com/developing/clients/jsonrpc-api#getsignaturestatuses https://docs.solana.com/developing/clients/jsonrpc-api#gettransaction

0

You can use the addEventListener function on your program, ie:

anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.Events;
let listener = null;

let [event, slot] = await new Promise((resolve, _reject) => {
  listener = program.addEventListener("MyEvent", (event, slot) => {
    resolve([event, slot]);
  });
  program.rpc.initialize();
});
await program.removeEventListener(listener);

assert.isAbove(slot, 0);
assert.strictEqual(event.data.toNumber(), 5);
assert.strictEqual(event.label, "hello");

You can read through the full tests for this feature at https://github.com/coral-xyz/anchor/blob/master/tests/events/tests/events.js

Jon C
  • 7,019
  • 10
  • 17
  • Thanks for the answer. But using this method we can't pick up any events emitted previously. For example if my server goes down and comes back up again the next day how can I listen to the events emitted during the past day which had already occurred – Senuda Jayalath Jun 27 '22 at 06:04
  • There's no way to do this easily, unfortunately. You need to fetch all of the transactions for the program, including the logs, and sift through them yourself to find the events. That means doing `getSignaturesForAddress` on your program, followed by `getTransaction` for each one returned, and then looking through the `logMessages` for `MyEvent`. – Jon C Jun 28 '22 at 14:37