use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
use crate::{Result, ToolkitError};
pub fn account_discriminator(account_name: &str) -> [u8; 8] {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let preimage = format!("account:{}", account_name);
let mut hasher = DefaultHasher::new();
preimage.hash(&mut hasher);
let hash = hasher.finish();
hash.to_le_bytes()
}
pub fn instruction_discriminator(instruction_name: &str) -> [u8; 8] {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let preimage = format!("global:{}", instruction_name);
let mut hasher = DefaultHasher::new();
preimage.hash(&mut hasher);
let hash = hasher.finish();
hash.to_le_bytes()
}
pub fn namespaced_discriminator(namespace: &str, name: &str) -> [u8; 8] {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let preimage = format!("{}:{}", namespace, name);
let mut hasher = DefaultHasher::new();
preimage.hash(&mut hasher);
let hash = hasher.finish();
hash.to_le_bytes()
}
pub mod programs {
use solana_sdk::pubkey::Pubkey;
pub const SYSTEM_PROGRAM: Pubkey = solana_sdk::system_program::ID;
pub fn token_program() -> Pubkey {
spl_token::id()
}
pub fn associated_token_program() -> Pubkey {
spl_associated_token_account::id()
}
pub fn token_metadata_program() -> Pubkey {
mpl_token_metadata::ID
}
pub fn rent_sysvar() -> Pubkey {
solana_sdk::sysvar::rent::id()
}
pub fn clock_sysvar() -> Pubkey {
solana_sdk::sysvar::clock::id()
}
}
#[derive(Default)]
pub struct CpiInstructionBuilder {
program_id: Option<Pubkey>,
accounts: Vec<AccountMeta>,
data: Vec<u8>,
}
impl CpiInstructionBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn program(mut self, program_id: Pubkey) -> Self {
self.program_id = Some(program_id);
self
}
pub fn signer(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new(pubkey, true));
self
}
pub fn signer_readonly(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new_readonly(pubkey, true));
self
}
pub fn writable(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new(pubkey, false));
self
}
pub fn readonly(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new_readonly(pubkey, false));
self
}
pub fn account(mut self, meta: AccountMeta) -> Self {
self.accounts.push(meta);
self
}
pub fn accounts(mut self, metas: Vec<AccountMeta>) -> Self {
self.accounts.extend(metas);
self
}
pub fn data(mut self, data: Vec<u8>) -> Self {
self.data = data;
self
}
pub fn anchor_data(mut self, instruction_name: &str, args: &[u8]) -> Self {
let discriminator = instruction_discriminator(instruction_name);
self.data = Vec::with_capacity(8 + args.len());
self.data.extend_from_slice(&discriminator);
self.data.extend_from_slice(args);
self
}
pub fn build(self) -> Result<Instruction> {
let program_id = self.program_id.ok_or_else(|| {
ToolkitError::Custom("Program ID not set".to_string())
})?;
Ok(Instruction {
program_id,
accounts: self.accounts,
data: self.data,
})
}
}
pub mod system_cpi {
use super::*;
use solana_sdk::system_instruction;
pub fn transfer(from: &Pubkey, to: &Pubkey, lamports: u64) -> Instruction {
system_instruction::transfer(from, to, lamports)
}
pub fn allocate(account: &Pubkey, space: u64) -> Instruction {
system_instruction::allocate(account, space)
}
pub fn create_account(
from: &Pubkey,
to: &Pubkey,
lamports: u64,
space: u64,
owner: &Pubkey,
) -> Instruction {
system_instruction::create_account(from, to, lamports, space, owner)
}
pub fn assign(account: &Pubkey, owner: &Pubkey) -> Instruction {
system_instruction::assign(account, owner)
}
}
pub mod token_cpi {
use super::*;
use spl_token::instruction as token_instruction;
pub fn transfer(
source: &Pubkey,
destination: &Pubkey,
authority: &Pubkey,
amount: u64,
) -> Result<Instruction> {
token_instruction::transfer(
&spl_token::id(),
source,
destination,
authority,
&[],
amount,
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn mint_to(
mint: &Pubkey,
destination: &Pubkey,
authority: &Pubkey,
amount: u64,
) -> Result<Instruction> {
token_instruction::mint_to(
&spl_token::id(),
mint,
destination,
authority,
&[],
amount,
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn burn(
account: &Pubkey,
mint: &Pubkey,
authority: &Pubkey,
amount: u64,
) -> Result<Instruction> {
token_instruction::burn(
&spl_token::id(),
account,
mint,
authority,
&[],
amount,
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn close_account(
account: &Pubkey,
destination: &Pubkey,
authority: &Pubkey,
) -> Result<Instruction> {
token_instruction::close_account(
&spl_token::id(),
account,
destination,
authority,
&[],
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn approve(
source: &Pubkey,
delegate: &Pubkey,
authority: &Pubkey,
amount: u64,
) -> Result<Instruction> {
token_instruction::approve(
&spl_token::id(),
source,
delegate,
authority,
&[],
amount,
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn revoke(source: &Pubkey, authority: &Pubkey) -> Result<Instruction> {
token_instruction::revoke(&spl_token::id(), source, authority, &[])
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn initialize_account(
account: &Pubkey,
mint: &Pubkey,
owner: &Pubkey,
) -> Result<Instruction> {
token_instruction::initialize_account(
&spl_token::id(),
account,
mint,
owner,
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn set_authority(
account: &Pubkey,
current_authority: &Pubkey,
authority_type: spl_token::instruction::AuthorityType,
new_authority: Option<&Pubkey>,
) -> Result<Instruction> {
token_instruction::set_authority(
&spl_token::id(),
account,
new_authority,
authority_type,
current_authority,
&[],
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn freeze_account(
account: &Pubkey,
mint: &Pubkey,
authority: &Pubkey,
) -> Result<Instruction> {
token_instruction::freeze_account(
&spl_token::id(),
account,
mint,
authority,
&[],
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
pub fn thaw_account(
account: &Pubkey,
mint: &Pubkey,
authority: &Pubkey,
) -> Result<Instruction> {
token_instruction::thaw_account(
&spl_token::id(),
account,
mint,
authority,
&[],
)
.map_err(|e| ToolkitError::TokenError(e.to_string()))
}
}
pub mod ata_cpi {
use super::*;
use spl_associated_token_account::instruction as ata_instruction;
pub fn create(
payer: &Pubkey,
wallet: &Pubkey,
mint: &Pubkey,
) -> Instruction {
ata_instruction::create_associated_token_account(
payer,
wallet,
mint,
&spl_token::id(),
)
}
pub fn create_idempotent(
payer: &Pubkey,
wallet: &Pubkey,
mint: &Pubkey,
) -> Instruction {
ata_instruction::create_associated_token_account_idempotent(
payer,
wallet,
mint,
&spl_token::id(),
)
}
pub fn get_address(wallet: &Pubkey, mint: &Pubkey) -> Pubkey {
spl_associated_token_account::get_associated_token_address(wallet, mint)
}
}
pub mod validation {
use super::*;
use solana_sdk::account::Account;
pub fn validate_discriminator(
account: &Account,
expected: &[u8; 8],
) -> Result<()> {
if account.data.len() < 8 {
return Err(ToolkitError::InvalidAccountData(
"Account data too short for discriminator".to_string(),
));
}
let discriminator: &[u8; 8] = account.data[..8].try_into().map_err(|_| {
ToolkitError::InvalidAccountData("Invalid discriminator".to_string())
})?;
if discriminator != expected {
return Err(ToolkitError::InvalidAccountData(format!(
"Invalid discriminator: expected {:?}, got {:?}",
expected, discriminator
)));
}
Ok(())
}
pub fn validate_owner(account: &Account, expected_owner: &Pubkey) -> Result<()> {
if &account.owner != expected_owner {
return Err(ToolkitError::InvalidAccountData(format!(
"Invalid owner: expected {}, got {}",
expected_owner, account.owner
)));
}
Ok(())
}
pub fn validate_data_len(account: &Account, min_len: usize) -> Result<()> {
if account.data.len() < min_len {
return Err(ToolkitError::InvalidAccountData(format!(
"Account data too short: expected at least {}, got {}",
min_len,
account.data.len()
)));
}
Ok(())
}
pub fn validate_rent_exempt(account: &Account, rent: &solana_sdk::rent::Rent) -> Result<()> {
if !rent.is_exempt(account.lamports, account.data.len()) {
return Err(ToolkitError::InsufficientBalance {
required: rent.minimum_balance(account.data.len()),
available: account.lamports,
});
}
Ok(())
}
pub fn validate_writable(account: &Account) -> Result<()> {
if account.executable {
return Err(ToolkitError::InvalidAccountData(
"Account is executable and cannot be written to".to_string(),
));
}
Ok(())
}
pub fn validate_anchor_account(
account: &Account,
account_name: &str,
expected_owner: &Pubkey,
) -> Result<()> {
validate_owner(account, expected_owner)?;
let discriminator = account_discriminator(account_name);
validate_discriminator(account, &discriminator)?;
Ok(())
}
}
pub mod serialization {
use super::*;
use borsh::BorshSerialize;
pub fn serialize_anchor_ix<T: BorshSerialize>(
instruction_name: &str,
args: &T,
) -> Result<Vec<u8>> {
let discriminator = instruction_discriminator(instruction_name);
let mut data = Vec::with_capacity(256);
data.extend_from_slice(&discriminator);
args.serialize(&mut data)
.map_err(|e| ToolkitError::Custom(format!("Serialization error: {}", e)))?;
Ok(data)
}
pub fn serialize_with_discriminator<T: BorshSerialize>(
discriminator: &[u8; 8],
args: &T,
) -> Result<Vec<u8>> {
let mut data = Vec::with_capacity(256);
data.extend_from_slice(discriminator);
args.serialize(&mut data)
.map_err(|e| ToolkitError::Custom(format!("Serialization error: {}", e)))?;
Ok(data)
}
pub fn serialize_args<T: BorshSerialize>(args: &T) -> Result<Vec<u8>> {
let mut data = Vec::new();
args.serialize(&mut data)
.map_err(|e| ToolkitError::Custom(format!("Serialization error: {}", e)))?;
Ok(data)
}
}
#[derive(Default)]
pub struct RemainingAccountsBuilder {
accounts: Vec<AccountMeta>,
}
impl RemainingAccountsBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn writable(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new(pubkey, false));
self
}
pub fn readonly(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new_readonly(pubkey, false));
self
}
pub fn signer(mut self, pubkey: Pubkey) -> Self {
self.accounts.push(AccountMeta::new(pubkey, true));
self
}
pub fn writables(mut self, pubkeys: &[Pubkey]) -> Self {
for pubkey in pubkeys {
self.accounts.push(AccountMeta::new(*pubkey, false));
}
self
}
pub fn readonlys(mut self, pubkeys: &[Pubkey]) -> Self {
for pubkey in pubkeys {
self.accounts.push(AccountMeta::new_readonly(*pubkey, false));
}
self
}
pub fn build(self) -> Vec<AccountMeta> {
self.accounts
}
pub fn len(&self) -> usize {
self.accounts.len()
}
pub fn is_empty(&self) -> bool {
self.accounts.is_empty()
}
}
pub mod sizes {
pub const DISCRIMINATOR: usize = 8;
pub const PUBKEY: usize = 32;
pub const U64: usize = 8;
pub const U128: usize = 16;
pub const I64: usize = 8;
pub const BOOL: usize = 1;
pub const U8: usize = 1;
pub const U16: usize = 2;
pub const U32: usize = 4;
pub const fn string(max_len: usize) -> usize {
4 + max_len }
pub const fn vec<const ELEMENT_SIZE: usize>(max_elements: usize) -> usize {
4 + (ELEMENT_SIZE * max_elements) }
pub const fn option(inner_size: usize) -> usize {
1 + inner_size }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_account_discriminator() {
let disc = account_discriminator("TestAccount");
assert_eq!(disc.len(), 8);
}
#[test]
fn test_instruction_discriminator() {
let disc = instruction_discriminator("initialize");
assert_eq!(disc.len(), 8);
}
#[test]
fn test_cpi_builder() {
let program_id = Pubkey::new_unique();
let account = Pubkey::new_unique();
let ix = CpiInstructionBuilder::new()
.program(program_id)
.signer(account)
.data(vec![1, 2, 3])
.build()
.unwrap();
assert_eq!(ix.program_id, program_id);
assert_eq!(ix.accounts.len(), 1);
assert_eq!(ix.data, vec![1, 2, 3]);
}
#[test]
fn test_remaining_accounts_builder() {
let pubkey1 = Pubkey::new_unique();
let pubkey2 = Pubkey::new_unique();
let accounts = RemainingAccountsBuilder::new()
.writable(pubkey1)
.readonly(pubkey2)
.build();
assert_eq!(accounts.len(), 2);
assert!(accounts[0].is_writable);
assert!(!accounts[1].is_writable);
}
#[test]
fn test_sizes() {
assert_eq!(sizes::DISCRIMINATOR, 8);
assert_eq!(sizes::PUBKEY, 32);
assert_eq!(sizes::string(100), 104);
}
}