Rust Programming for Solana Smart Contracts
Rust is the primary language for Solana smart contract development. This guide covers Rust fundamentals essential for writing efficient, secure Solana programs.
Rust Basics for Solana
Ownership System
Rust's ownership system prevents data races and memory leaks:
// Ownership transfer
fn transfer_ownership() {
let data = vec![1, 2, 3, 4, 5];
let owner = data; // Ownership transferred
// println!("{:?}", data); // Error: data moved
println!("{:?}", owner); // Works
}
// Clone for explicit copying
fn clone_data() {
let data = vec![1, 2, 3, 4, 5];
let cloned = data.clone(); // Explicit clone
println!("Original: {:?}", data);
println!("Cloned: {:?}", cloned);
}
// Move semantics in functions
fn process_data(data: Vec<u8>) -> Vec<u8> {
// data is owned by this function
let processed = data.iter()
.map(|x| x * 2)
.collect();
processed // Return ownership
}
fn main() {
let original = vec![1, 2, 3];
let processed = process_data(original);
// original is no longer accessible
println!("Processed: {:?}", processed);
}
Borrowing and References
// Immutable borrowing (multiple allowed)
fn calculate_sum(data: &[u32]) -> u32 {
data.iter().sum()
}
// Mutable borrowing (only one allowed)
fn increment_all(data: &mut [u32]) {
for item in data.iter_mut() {
*item += 1;
}
}
// Lifetime annotations
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Complex lifetime example
struct Database {
data: Vec<String>,
}
impl Database {
fn new() -> Self {
Self { data: Vec::new() }
}
fn add(&mut self, item: String) {
self.data.push(item);
}
fn find(&self, query: &str) -> Option<&String> {
self.data.iter().find(|s| s.contains(query))
}
fn find_mut(&mut self, query: &str) -> Option<&mut String> {
self.data.iter_mut().find(|s| s.contains(query))
}
}
// Lifetime in structs
struct Reference<'a> {
data: &'a str,
}
impl<'a> Reference<'a> {
fn new(data: &'a str) -> Self {
Self { data }
}
fn get_data(&self) -> &str {
self.data
}
}
Error Handling
use std::fmt;
#[derive(Debug)]
enum ProgramError {
InvalidInput,
InsufficientFunds,
ArithmeticOverflow,
AccountNotFound,
Unauthorized,
}
impl fmt::Display for ProgramError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ProgramError::InvalidInput => write!(f, "Invalid input provided"),
ProgramError::InsufficientFunds => write!(f, "Insufficient funds"),
ProgramError::ArithmeticOverflow => write!(f, "Arithmetic overflow"),
ProgramError::AccountNotFound => write!(f, "Account not found"),
ProgramError::Unauthorized => write!(f, "Unauthorized access"),
}
}
}
impl std::error::Error for ProgramError {}
type Result<T> = std::result::Result<T, ProgramError>;
fn transfer(from: &mut u64, to: &mut u64, amount: u64) -> Result<()> {
if amount > *from {
return Err(ProgramError::InsufficientFunds);
}
*from = from.checked_sub(amount)
.ok_or(ProgramError::ArithmeticOverflow)?;
*to = to.checked_add(amount)
.ok_or(ProgramError::ArithmeticOverflow)?;
Ok(())
}
// Using the Result type
fn process_transfer() {
let mut balance_a = 1000;
let mut balance_b = 500;
match transfer(&mut balance_a, &mut balance_b, 300) {
Ok(()) => println!("Transfer successful"),
Err(e) => println!("Transfer failed: {}", e),
}
}
Solana Program Structure
Program Entry Point
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
// Process instruction based on data
let instruction = Instruction::unpack(instruction_data)?;
match instruction {
Instruction::Initialize { amount } => {
process_initialize(program_id, accounts, amount)
}
Instruction::Transfer { amount } => {
process_transfer(program_id, accounts, amount)
}
Instruction::Close => {
process_close(program_id, accounts)
}
}
}
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub enum Instruction {
Initialize { amount: u64 },
Transfer { amount: u64 },
Close,
}
impl Instruction {
pub fn unpack(data: &[u8]) -> Result<Self, ProgramError> {
Self::try_from_slice(data)
.map_err(|_| ProgramError::InvalidInstructionData)
}
pub fn pack(&self) -> Vec<u8> {
let mut data = Vec::new();
self.serialize(&mut data).unwrap();
data
}
}
Account Validation
Account validation ensures that only authorized accounts can interact with your program. Solana programs must validate all accounts passed to instructions.
Serialization (Borsh)
Borsh Serialization/Deserialization
use borsh::{BorshSerialize, BorshDeserialize};
use std::io::{Write, Read};
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct AccountState {
pub is_initialized: bool,
pub authority: Pubkey,
pub balance: u64,
pub data: Vec<u8>,
pub timestamp: i64,
}
impl AccountState {
pub fn new(authority: Pubkey, balance: u64) -> Self {
Self {
is_initialized: true,
authority,
balance,
data: Vec::new(),
timestamp: chrono::Utc::now().timestamp(),
}
}
pub fn pack(&self) -> Vec<u8> {
let mut data = Vec::new();
self.serialize(&mut data).unwrap();
data
}
pub fn unpack(data: &[u8]) -> Result<Self, ProgramError> {
Self::try_from_slice(data)
.map_err(|_| ProgramError::InvalidAccountData)
}
pub fn update_balance(&mut self, amount: i64) -> Result<(), ProgramError> {
if amount > 0 {
self.balance = self.balance.checked_add(amount as u64)
.ok_or(ProgramError::ArithmeticOverflow)?;
} else {
self.balance = self.balance.checked_sub(amount.abs() as u64)
.ok_or(ProgramError::ArithmeticOverflow)?;
}
self.timestamp = chrono::Utc::now().timestamp();
Ok(())
}
}
// Complex nested structures
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct Vault {
pub authority: Pubkey,
pub token_mint: Pubkey,
pub token_account: Pubkey,
pub total_deposited: u64,
pub total_withdrawn: u64,
pub last_transaction: i64,
pub is_active: bool,
pub bump: u8,
}
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct Transaction {
pub from: Pubkey,
pub to: Pubkey,
pub amount: u64,
pub timestamp: i64,
pub memo: Option<String>,
}
// Custom serialization for complex types
impl Vault {
pub fn calculate_fee(&self, amount: u64, fee_basis_points: u64) -> Result<(u64, u64), ProgramError> {
let fee = amount
.checked_mul(fee_basis_points)
.ok_or(ProgramError::ArithmeticOverflow)?
.checked_div(10000)
.ok_or(ProgramError::ArithmeticOverflow)?;
let net_amount = amount
.checked_sub(fee)
.ok_or(ProgramError::ArithmeticOverflow)?;
Ok((net_amount, fee))
}
}
Complete Program Examples
Token Vault Program
The Token Vault program demonstrates a complete DeFi vault with fee calculation, deposit/withdrawal functionality, and PDA authority management.
NFT Staking Program
use anchor_lang::prelude::*;
use anchor_spl::token::{self, Mint, Token, TokenAccount, Transfer};
declare_id!("NFTStakingProgram11111111111111111111111111111");
#[program]
pub mod nft_staking {
use super::*;
pub fn initialize(
ctx: Context<Initialize>,
rewards_per_day: u64,
lock_period: i64,
) -> Result<()> {
let config = &mut ctx.accounts.config;
config.authority = ctx.accounts.authority.key();
config.rewards_per_day = rewards_per_day;
config.lock_period = lock_period;
config.total_staked = 0;
config.total_rewards_distributed = 0;
config.is_active = true;
config.bump = ctx.bumps.config;
Ok(())
}
pub fn stake_nft(ctx: Context<StakeNft>) -> Result<()> {
let config = &mut ctx.accounts.config;
let stake_record = &mut ctx.accounts.stake_record;
require!(config.is_active, StakingError::ConfigInactive);
// Transfer NFT to vault
let cpi_accounts = Transfer {
from: ctx.accounts.user_nft_account.to_account_info(),
to: ctx.accounts.vault_nft_account.to_account_info(),
authority: ctx.accounts.user.to_account_info(),
};
let cpi_ctx = CpiContext::new(
ctx.accounts.token_program.to_account_info(),
cpi_accounts,
);
token::transfer(cpi_ctx, 1)?;
// Update stake record
stake_record.owner = ctx.accounts.user.key();
stake_record.nft_mint = ctx.accounts.nft_mint.key();
stake_record.stake_time = Clock::get()?.unix_timestamp;
stake_record.is_active = true;
stake_record.bump = ctx.bumps.stake_record;
config.total_staked += 1;
emit!(NftStaked {
user: ctx.accounts.user.key(),
nft_mint: ctx.accounts.nft_mint.key(),
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}
pub fn unstake_nft(ctx: Context<UnstakeNft>) -> Result<()> {
let config = &mut ctx.accounts.config;
let stake_record = &mut ctx.accounts.stake_record;
require!(stake_record.is_active, StakingError::NotStaked);
let current_time = Clock::get()?.unix_timestamp;
let staked_duration = current_time
.checked_sub(stake_record.stake_time)
.ok_or(StakingError::ArithmeticOverflow)?;
require!(
staked_duration >= config.lock_period,
StakingError::LockPeriodNotMet
);
// Calculate rewards
let days_staked = staked_duration
.checked_div(86400) // seconds in a day
.ok_or(StakingError::ArithmeticOverflow)?;
let rewards = days_staked
.checked_mul(config.rewards_per_day)
.ok_or(StakingError::ArithmeticOverflow)?;
// Transfer NFT back
let seeds = &[
b"vault".as_ref(),
&[ctx.accounts.vault.bump],
];
let signer_seeds = &[&seeds[..]];
let cpi_accounts = Transfer {
from: ctx.accounts.vault_nft_account.to_account_info(),
to: ctx.accounts.user_nft_account.to_account_info(),
authority: ctx.accounts.vault.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
cpi_accounts,
signer_seeds,
);
token::transfer(cpi_ctx, 1)?;
// Transfer rewards
if rewards > 0 {
let cpi_accounts = Transfer {
from: ctx.accounts.vault_rewards_account.to_account_info(),
to: ctx.accounts.user_rewards_account.to_account_info(),
authority: ctx.accounts.vault.to_account_info(),
};
let cpi_ctx = CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
cpi_accounts,
signer_seeds,
);
token::transfer(cpi_ctx, rewards)?;
config.total_rewards_distributed = config.total_rewards_distributed
.checked_add(rewards)
.ok_or(StakingError::ArithmeticOverflow)?;
}
// Update state
stake_record.is_active = false;
config.total_staked = config.total_staked
.checked_sub(1)
.ok_or(StakingError::ArithmeticOverflow)?;
emit!(NftUnstaked {
user: ctx.accounts.user.key(),
nft_mint: ctx.accounts.nft_mint.key(),
rewards,
timestamp: current_time,
});
Ok(())
}
}
#[account]
pub struct StakingConfig {
pub authority: Pubkey,
pub rewards_per_day: u64,
pub lock_period: i64,
pub total_staked: u64,
pub total_rewards_distributed: u64,
pub is_active: bool,
pub bump: u8,
}
#[account]
pub struct StakeRecord {
pub owner: Pubkey,
pub nft_mint: Pubkey,
pub stake_time: i64,
pub is_active: bool,
pub bump: u8,
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(
init,
payer = authority,
space = StakingConfig::INIT_SPACE,
seeds = [b"config"],
bump,
)]
pub config: Account<'info, StakingConfig>,
#[account(
init,
payer = authority,
token::mint = rewards_mint,
token::authority = vault,
seeds = [b"vault", b"rewards"],
bump,
)]
pub vault_rewards_account: Account<'info, TokenAccount>,
pub rewards_mint: Account<'info, Mint>,
#[account(
init,
payer = authority,
space = 8 + 32 + 8,
seeds = [b"vault"],
bump,
)]
pub vault: Account<'info, Vault>,
pub system_program: Program<'info, System>,
pub token_program: Program<'info, Token>,
pub rent: Sysvar<'info, Rent>,
}
#[derive(Accounts)]
pub struct StakeNft<'info> {
#[account(mut)]
pub user: Signer<'info>,
#[account(
mut,
seeds = [b"config"],
bump = config.bump,
)]
pub config: Account<'info, StakingConfig>,
#[account(
init_if_needed,
payer = user,
space = StakeRecord::INIT_SPACE,
seeds = [b"stake", user.key().as_ref(), nft_mint.key().as_ref()],
bump,
)]
pub stake_record: Account<'info, StakeRecord>,
pub nft_mint: Account<'info, Mint>,
#[account(
mut,
constraint = user_nft_account.owner == user.key(),
constraint = user_nft_account.mint == nft_mint.key(),
constraint = user_nft_account.amount == 1,
)]
pub user_nft_account: Account<'info, TokenAccount>,
#[account(
mut,
token::mint = nft_mint,
token::authority = vault,
seeds = [b"nft_vault", nft_mint.key().as_ref()],
bump,
)]
pub vault_nft_account: Account<'info, TokenAccount>,
#[account(
mut,
seeds = [b"vault"],
bump,
)]
pub vault: Account<'info, Vault>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UnstakeNft<'info> {
#[account(mut)]
pub user: Signer<'info>,
#[account(
mut,
seeds = [b"config"],
bump = config.bump,
)]
pub config: Account<'info, StakingConfig>,
#[account(
mut,
seeds = [b"stake", user.key().as_ref(), nft_mint.key().as_ref()],
bump = stake_record.bump,
)]
pub stake_record: Account<'info, StakeRecord>,
pub nft_mint: Account<'info, Mint>,
#[account(
mut,
constraint = user_nft_account.owner == user.key(),
constraint = user_nft_account.mint == nft_mint.key(),
)]
pub user_nft_account: Account<'info, TokenAccount>,
#[account(
mut,
token::mint = nft_mint,
token::authority = vault,
seeds = [b"nft_vault", nft_mint.key().as_ref()],
bump,
)]
pub vault_nft_account: Account<'info, TokenAccount>,
#[account(
mut,
token::mint = rewards_mint,
token::authority = vault,
seeds = [b"vault", b"rewards"],
bump,
)]
pub vault_rewards_account: Account<'info, TokenAccount>,
#[account(
init_if_needed,
payer = user,
token::mint = rewards_mint,
token::authority = user,
)]
pub user_rewards_account: Account<'info, TokenAccount>,
pub rewards_mint: Account<'info, Mint>,
#[account(
mut,
seeds = [b"vault"],
bump,
)]
pub vault: Account<'info, Vault>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Vault {
pub bump: u8,
}
#[error_code]
pub enum StakingError {
#[msg("Config is inactive")]
ConfigInactive,
#[msg("NFT is not staked")]
NotStaked,
#[msg("Lock period not met")]
LockPeriodNotMet,
#[msg("Arithmetic overflow")]
ArithmeticOverflow,
#[msg("Invalid NFT")]
InvalidNFT,
#[msg("Already staked")]
AlreadyStaked,
}
#[event]
pub struct NftStaked {
pub user: Pubkey,
pub nft_mint: Pubkey,
pub timestamp: i64,
}
#[event]
pub struct NftUnstaked {
pub user: Pubkey,
pub nft_mint: Pubkey,
pub rewards: u64,
pub timestamp: i64,
}
Performance Optimization
Optimizing Solana programs is crucial for reducing compute costs and improving efficiency. Key techniques include using efficient data structures and minimizing storage usage.
Trade-offs
Rust for Solana Advantages
- Memory safety without garbage collector
- Zero-cost abstractions
- Ownership system prevents data races
- Excellent performance
Rust for Solana Disadvantages
- Steep learning curve
- Longer compile times
- Borrow checker constraints
- Limited ecosystem compared to JavaScript
Interview Questions
-
How does Rust's ownership system help in Solana program development?
- Prevents memory leaks and data races
- Ensures proper resource cleanup
- Enables safe concurrent execution
- Reduces runtime errors
-
Explain the difference between
&and&mutin Rust contexts.&is immutable borrowing (multiple allowed)&mutis mutable borrowing (only one allowed)- Prevents data races at compile time
- Enables safe shared access
-
What are the benefits of Borsh serialization for Solana programs?
- Compact binary format
- Fast serialization/deserialization
- Cross-language compatibility
- Deterministic output
Quiz Questions
-
What is the purpose of the
#[account]attribute in Anchor?- A) Marks a struct as an account
- B) Defines account constraints
- C) Both A and B
- D) None of the above
- Answer: C) Both A and B
-
How do you handle errors in Rust Solana programs?
- A) Use panic!
- B) Use
Result<T, E> - C) Use println!
- D) Use unwrap()
- Answer: B) Use
Result<T, E>
-
What is the maximum size for a Solana account?
- A) 10 KB
- B) 100 KB
- C) 10 MB
- D) 100 MB
- Answer: C) 10 MB
Real-World Example: Escrow Program
The escrow program demonstrates a complete Solana program with token transfers, time-based logic, and PDA authority patterns.
Conclusion
Rust's unique features make it ideal for Solana smart contract development. Understanding ownership, borrowing, and error handling is crucial for writing secure, efficient programs. The examples provided demonstrate real-world patterns used in production Solana applications.