Solana: How to display the event passed by emit! on the block explorer

Displaying Events in Solana Block Explorer

In this article, we will look at how to display events passed by emit! in the Solana block explorer.

What is “emit!”?

On the Solana blockchain, “emit!” is a function that sends events to the network. It allows you to define and execute custom functions that interact with other contracts or the blockchain itself. In this case, we will use it to display an event in the block explorer.

Defining the Event Structure

First, let’s define the event structure:

#[event]

pub struct ClaimEvent {

pub commit: u64,

}

This defines a simple "ClaimEvent" structure with a single "commit" field representing the number of commits (or interactions) in the contract.

Usingemit!

Now we useemit!to sendClaimEventto the block browser:

emit!(ClaimEvent { commit: 123 });

However, as mentioned earlier, this only works if we define an event structure. To fix this, we need to add a new event type and use the eventmacro (available in Solana's Rust SDK) to define a custom event:

use solana_sdk::event::{Event, EventRecord};

#[event]

pub struct ClaimEvent {

pub engagement: u64,

}

impl Event for ClaimEvent {

fn signature(&own) -> &[u8] {

// Return the signature of the event (not shown in this example)

unimplemented!()

}

}

In this updated code, we define a new “ClaimEvent” struct and implement the “Event” property. Calling the signature() method returns the event metadata, but for now it returns an empty byte slice.

Showing Events in Block Explorer

To show events in the block explorer, you need to use the “blockchain” module:

using blockchain::{block, event, blockId};

fn main() {

// Get the current block ID

let block_id = block::BlockId::new();

// Define an event record for our custom event

let event_record = EventRecord::new();

event_record.set_field("engagement", 123);

// Create a new block object

let block_data = block_data! {

id: block_id.to_string(),

events: Some(vec![event_record.clone()]),

};

// Send the block data to the blockchain

let mut tx = block::Transaction::new().set_data(block_data).signer().build();

blockchain::send_transaction(&tx, "own-transaction");

}

In this example, we use the blockchain' module to create a new block object and add our custom event record. Then, we send the block data to the blockchain using thesend_transaction()` function.

Example Use Cases

This example demonstrates how to display events in the Solana block explorer. You can apply similar logic to other contracts or integrations, such as:

  • Displaying user engagement metrics
  • Displaying transaction history
  • Logging API calls

Please note that this is a simplified example and you will need to consider factors such as event persistence, logging, and security when implementing custom events on the Solana blockchain.