In Solana, public keys are 32-byte arrays. Let's build a simplified Pubkey type!
// Actual Solana SDK
pub struct Pubkey([u8; 32]);Every account, program, and wallet in Solana is identified by a 32-byte public key. Understanding byte manipulation is essential!
// Creating arrays
let zeros = [0u8; 32]; // All zeros
let ones = [1u8; 32]; // All ones
let mixed = [1, 2, 3, 0, 0, ...]; // Specific values
// Comparing arrays
zeros == [0u8; 32] // true
zeros != ones // trueWrap a type for type safety:
#[derive(Debug, Clone, Copy, PartialEq)]
struct Pubkey([u8; 32]);
impl Pubkey {
const fn new(bytes: [u8; 32]) -> Self {
Pubkey(bytes)
}
}impl Pubkey {
// Check if all zeros
fn is_zero(&self) -> bool {
self.0 == [0u8; 32]
}
// Get as slice
fn as_bytes(&self) -> &[u8] {
&self.0
}
// Get first n bytes
fn first_bytes<const N: usize>(&self) -> [u8; N] {
self.0[..N].try_into().unwrap()
}
}impl Pubkey {
// Constant pubkey (like system program)
const SYSTEM_PROGRAM: Pubkey = Pubkey([0u8; 32]);
fn is_system_program(&self) -> bool {
*self == Self::SYSTEM_PROGRAM
}
}Implement for Pubkey:
default() - returns a pubkey with all zerosis_zero() - checks if all bytes are zeroas_bytes() - returns the bytes as a slicePubkey::default().is_zero() → truePubkey::new([1u8; 32]).is_zero() → falsePubkey::new([1u8; 32]).as_bytes()[0] → 1fn default() -> Self {
Pubkey([0u8; 32])
}
fn is_zero(&self) -> bool {
self.0 == [0u8; 32]
}
fn as_bytes(&self) -> &[u8] {
&self.0
}