LightHasher

Derive Macro LightHasher 

Source
#[derive(LightHasher)]
{
    // Attributes available to this derive:
    #[hash]
    #[skip]
}
Expand description

Makes the annotated struct hashable by implementing the following traits:

  • ToByteArray, which makes the struct convertable to a 2D byte vector.
  • DataHasher, which makes the struct hashable with the hash() method, based on the byte inputs from ToByteArray implementation.

This macro assumes that all the fields of the struct implement the AsByteVec trait. The trait is implemented by default for the most of standard Rust types (primitives, String, arrays and options carrying the former). If there is a field of a type not implementing the trait, there will be a compilation error.

§Example

use light_sdk_macros::LightHasher;
use solana_pubkey::Pubkey;

#[derive(LightHasher)]
pub struct UserRecord {
    pub owner: Pubkey,
    pub name: String,
    pub score: u64,
}

§Hash attribute

Fields marked with #[hash] will be hashed to field size (31 bytes) before being included in the main hash calculation. This is useful for fields that exceed the field size limit (like Pubkeys which are 32 bytes).

use light_sdk_macros::LightHasher;
use solana_pubkey::Pubkey;

#[derive(LightHasher)]
pub struct GameState {
    #[hash]
    pub player: Pubkey,  // Will be hashed to 31 bytes
    pub level: u32,
}