Solana Blockchain Development Complete Guide
Solana is a high-performance blockchain supporting smart contracts with 65,000 transactions per second and sub-second finality. This guide covers the complete architecture, core concepts, and practical implementation for building on Solana.
Core Architecture
Solana's performance comes from eight key innovations working together:
Proof of History (PoH)
PoH is a cryptographic clock enabling distributed consensus without real-time communication:
use solana_program::hash::Hash;
pub struct ProofOfHistory {
last_hash: Hash,
counter: u64,
}
impl ProofOfHistory {
pub fn new() -> Self {
Self {
last_hash: Hash::default(),
counter: 0,
}
}
pub fn tick(&mut self) -> Hash {
let data = [
self.last_hash.to_bytes(),
self.counter.to_le_bytes(),
chrono::Utc::now().timestamp().to_le_bytes(),
].concat();
self.last_hash = solana_program::hash::hash(&data);
self.counter += 1;
self.last_hash
}
pub fn verify(&self, hash: Hash, timestamp: i64) -> bool {
let data = [
self.last_hash.to_bytes(),
self.counter.to_le_bytes(),
timestamp.to_le_bytes(),
].concat();
solana_program::hash::hash(&data) == hash
}
}
Tower BFT
Tower BFT leverages PoH for fast consensus:
pub struct TowerBFT {
validator_id: Pubkey,
current_slot: u64,
lockouts: Vec<u64>,
stake: u64,
}
impl TowerBFT {
pub fn new(validator_id: Pubkey, stake: u64) -> Self {
Self {
validator_id,
current_slot: 0,
lockouts: Vec::new(),
stake,
}
}
pub fn record_vote(&mut self, slot: u64) {
self.lockouts.push(slot);
self.current_slot = slot;
}
pub fn calculate_lockout(&self, index: usize) -> u64 {
if index == 0 {
return 1;
}
let base = self.lockouts[index - 1];
base.saturating_mul(2).min(1 << 31)
}
pub fn is_vote_valid(&self, proposed_slot: u64) -> bool {
proposed_slot > self.current_slot
}
}
Account Model vs Ethereum
Solana uses a fundamentally different account model:
| Feature | Solana | Ethereum |
|---|---|---|
| State Storage | External accounts | Contract storage |
| Account Data | Max 10MB | Unlimited |
| Rent | Yes (exempt or pay) | Storage gas |
| Execution | Parallel | Sequential |
| Address Space | 2^256 | 2^160 |
| Program Ownership | External | Self-owned |
Account Structure
use solana_program::account_info::AccountInfo;
pub struct Account {
pub lamports: u64,
pub data: Vec<u8>,
pub owner: Pubkey,
pub executable: bool,
pub rent_epoch: Epoch,
}
impl Account {
pub fn new(lamports: u64, space: usize, owner: &Pubkey) -> Self {
Self {
lamports,
data: vec![0u8; space],
owner: *owner,
executable: false,
rent_epoch: 0,
}
}
pub fn is_rent_exempt(&self) -> bool {
let min_balance = solana_program::rent::Rent::default()
.minimum_balance(self.data.len());
self.lamports >= min_balance
}
pub fn get_data<T: borsh::BorshDeserialize>(&self) -> Result<T, ProgramError> {
T::try_from_slice(&self.data)
.map_err(|_| ProgramError::InvalidAccountData)
}
}
Rent and Epochs
Rent Mechanics
Rent prevents spam by requiring minimum balance:
use solana_program::rent::Rent;
pub fn calculate_rent(space: usize) -> u64 {
let rent = Rent::default();
rent.minimum_balance(space)
}
pub fn check_rent_exempt(account_lamports: u64, data_len: usize) -> bool {
let rent = Rent::default();
let min_balance = rent.minimum_balance(data_len);
account_lamports >= min_balance
}
pub fn get_rent_per_byte_year() -> f64 {
let rent = Rent::default();
rent.lamports_per_byte_year as f64
}
Epoch Timeline
pub struct EpochSchedule {
pub slots_per_epoch: u64,
pub leader_schedule_slot_offset: u64,
pub warmup: bool,
pub first_normal_epoch: Epoch,
pub first_normal_slot: Slot,
}
impl EpochSchedule {
pub fn get_epoch_and_slot_index(&self, slot: Slot) -> (Epoch, usize) {
if slot < self.first_normal_slot {
let epoch = (slot / self.leader_schedule_slot_offset) as Epoch;
let slot_index = slot as usize % self.leader_schedule_slot_offset as usize;
(epoch, slot_index)
} else {
let normal_slot = slot - self.first_normal_slot;
let epoch = self.first_normal_epoch +
(normal_slot / self.slots_per_epoch) as Epoch;
let slot_index = normal_slot as usize % self.slots_per_epoch as usize;
(epoch, slot_index)
}
}
}
Program Derived Addresses (PDA)
PDAs are deterministic addresses without private keys:
use solana_program::pubkey::Pubkey;
pub fn find_pda(seeds: &[&[u8]], program_id: &Pubkey) -> (Pubkey, u8) {
Pubkey::find_program_address(seeds, program_id)
}
pub fn create_pda_account(
payer: &Pubkey,
seeds: &[&[u8]],
program_id: &Pubkey,
space: usize,
) -> (Pubkey, u8) {
let (pda, bump) = Pubkey::find_program_address(seeds, program_id);
let rent = Rent::default();
let lamports = rent.minimum_balance(space);
let create_account_ix = solana_program::system_instruction::create_account(
payer,
&pda,
lamports,
space as u64,
program_id,
);
(pda, bump)
}
pub fn invoke_signer(
program_id: &Pubkey,
accounts: &[AccountInfo],
data: &[u8],
pda: &Pubkey,
seeds: &[&[u8]],
bump: u8,
) -> Result<(), ProgramError> {
let seed_with_bump: Vec<&[u8]> = seeds.iter()
.chain(std::iter::once(&[bump]))
.collect();
solana_program::program::invoke_signed(
&solana_program::instruction::Instruction::new_with_bytes(
*program_id,
data,
accounts.to_vec(),
),
accounts,
&[&seed_with_bump],
)
}
Transaction Structure
Transaction Anatomy
use solana_sdk::transaction::Transaction;
use solana_sdk::signature::Keypair;
pub struct TransactionConfig {
pub recent_blockhash: Hash,
pub fee_payer: Pubkey,
pub compute_budget: u32,
pub priority_fee: u64,
}
impl TransactionConfig {
pub fn create_transaction(
&self,
instructions: Vec<Instruction>,
signers: &[&Keypair],
) -> Transaction {
let mut tx = Transaction::new_with_payer(
&instructions,
Some(&self.fee_payer),
);
tx.sign(signers, self.recent_blockhash);
tx
}
pub fn add_compute_budget(&self) -> Instruction {
solana_sdk::compute_budget::ComputeBudgetInstruction::set_compute_unit_limit(
self.compute_budget
)
}
pub fn add_priority_fee(&self) -> Instruction {
solana_sdk::compute_budget::ComputeBudgetInstruction::set_compute_unit_price(
self.priority_fee
)
}
}
Transaction Size Limits
| Limit Type | Value | Description |
|---|---|---|
| Max Transaction Size | 1232 bytes | Serialized transaction |
| Max Instructions | 64 | Per transaction |
| Max Accounts | 64 | Referenced accounts |
| Max Signers | 12 | Per transaction |
| Max Program Data | 964 bytes | Per instruction |
Cluster Architecture
Validator Components
pub struct ValidatorConfig {
pub identity: Keypair,
pub vote_account: Pubkey,
pub storage_account: Option<Pubkey>,
pub gossip_port: u16,
pub tvu_port: u16,
pub tpu_port: u16,
pub rpc_port: u16,
pub dynamic_port_range: PortRange,
pub accounts_db_caching_enabled: bool,
pub accounts_db_shrink_ratio: f64,
}
impl ValidatorConfig {
pub fn new() -> Self {
Self {
identity: Keypair::new(),
vote_account: Pubkey::default(),
storage_account: None,
gossip_port: 8000,
tvu_port: 8001,
tpu_port: 8002,
rpc_port: 8899,
dynamic_port_range: (8000, 8100),
accounts_db_caching_enabled: true,
accounts_db_shrink_ratio: 0.8,
}
}
pub fn get_rpc_url(&self) -> String {
format!("http://localhost:{}", self.rpc_port)
}
pub fn get_ws_url(&self) -> String {
format!("ws://localhost:{}", self.rpc_port)
}
}
Gossip Protocol
The gossip protocol enables validators to communicate and share state efficiently across the network.
Complete Project Setup
Project Structure
solana-project/
βββ Anchor.toml
βββ Cargo.toml
βββ package.json
βββ programs/
β βββ my-program/
β βββ Cargo.toml
β βββ src/
β βββ lib.rs
β βββ state.rs
β βββ instructions/
β β βββ mod.rs
β β βββ initialize.rs
β β βββ deposit.rs
β β βββ withdraw.rs
β βββ errors.rs
β βββ utils.rs
βββ tests/
β βββ my-program.ts
βββ migrations/
β βββ deploy.ts
βββ app/
βββ src/
β βββ components/
β βββ hooks/
β βββ contexts/
β βββ utils/
βββ package.json
Cargo.toml
[package]
name = "my-program"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []
[dependencies]
borsh = "0.10"
borsh-derive = "0.10"
solana-program = "1.17"
thiserror = "1.0"
[dev-dependencies]
solana-program-test = "1.17"
solana-sdk = "1.17"
Anchor.toml
[features]
resolution = true
skip-lint = false
[programs.devnet]
my_program = "11111111111111111111111111111111"
[registry]
url = "https://api.apr.dev"
[provider]
cluster = "devnet"
wallet = "~/.config/solana/id.json"
[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
Main Program File
use anchor_lang::prelude::*;
pub mod state;
pub mod instructions;
pub mod errors;
pub mod utils;
use instructions::*;
use state::*;
use errors::*;
declare_id!("11111111111111111111111111111111");
#[program]
pub mod my_program {
use super::*;
pub fn initialize(
ctx: Context<Initialize>,
config: ProgramConfig,
) -> Result<()> {
let account = &mut ctx.accounts.state_account;
account.authority = ctx.accounts.authority.key();
account.config = config;
account.bump = ctx.bumps.state_account;
emit!(InitializedEvent {
authority: account.authority,
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}
pub fn deposit(
ctx: Context<Deposit>,
amount: u64,
) -> Result<()> {
let account = &mut ctx.accounts.user_account;
let vault = &mut ctx.accounts.vault;
let transfer_ix = solana_program::system_instruction::transfer(
&ctx.accounts.user.key(),
&vault.key(),
amount,
);
solana_program::program::invoke(
&transfer_ix,
&[
ctx.accounts.user.to_account_info(),
vault.to_account_info(),
],
)?;
account.amount += amount;
account.last_deposit = Clock::get()?.unix_timestamp;
emit!(DepositEvent {
user: ctx.accounts.user.key(),
amount,
timestamp: account.last_deposit,
});
Ok(())
}
pub fn withdraw(
ctx: Context<Withdraw>,
amount: u64,
) -> Result<()> {
let account = &mut ctx.accounts.user_account;
require!(account.amount >= amount, ProgramError::InsufficientFunds);
let seeds = &[
b"vault".as_ref(),
&[ctx.accounts.state_account.bump],
];
let signer_seeds = &[&seeds[..]];
solana_program::program::invoke_signed(
&solana_program::system_instruction::transfer(
&ctx.accounts.vault.key(),
&ctx.accounts.user.key(),
amount,
),
&[
ctx.accounts.vault.to_account_info(),
ctx.accounts.user.to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
signer_seeds,
)?;
account.amount -= amount;
account.last_withdrawal = Clock::get()?.unix_timestamp;
emit!(WithdrawalEvent {
user: ctx.accounts.user.key(),
amount,
timestamp: account.last_withdrawal,
});
Ok(())
}
}
State Definitions
use anchor_lang::prelude::*;
#[account]
#[derive(Default)]
pub struct StateAccount {
pub authority: Pubkey,
pub config: ProgramConfig,
pub total_deposits: u64,
pub total_withdrawals: u64,
pub user_count: u64,
pub bump: u8,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct ProgramConfig {
pub min_deposit: u64,
pub max_deposit: u64,
pub fee_percentage: u64,
pub is_paused: bool,
}
#[account]
#[derive(Default)]
pub struct UserAccount {
pub owner: Pubkey,
pub amount: u64,
pub last_deposit: i64,
pub last_withdrawal: i64,
pub bump: u8,
}
#[event]
pub struct InitializedEvent {
pub authority: Pubkey,
pub timestamp: i64,
}
#[event]
pub struct DepositEvent {
pub user: Pubkey,
pub amount: u64,
pub timestamp: i64,
}
#[event]
pub struct WithdrawalEvent {
pub user: Pubkey,
pub amount: u64,
pub timestamp: i64,
}
Error Definitions
use anchor_lang::prelude::*;
#[error_code]
pub enum ProgramError {
#[msg("Invalid configuration")]
InvalidConfig,
#[msg("Insufficient funds")]
InsufficientFunds,
#[msg("Amount exceeds maximum")]
AmountExceedsMax,
#[msg("Amount below minimum")]
AmountBelowMin,
#[msg("Program is paused")]
ProgramPaused,
#[msg("Unauthorized access")]
Unauthorized,
#[msg("Invalid account data")]
InvalidAccountData,
#[msg("Math overflow")]
MathOverflow,
}
Performance Comparison
| Metric | Solana | Ethereum | Polygon |
|---|---|---|---|
| TPS | 65,000 | 15-30 | 7,000 |
| Finality | 400ms | 12 min | 2s |
| Cost per TX | 5-50 | $0.01 | |
| Smart Contract Language | Rust | Solidity | Solidity |
| VM | Sealevel | EVM | EVM |
Trade-offs
Solana Advantages
- Ultra-high throughput (65,000 TPS)
- Low transaction costs ($0.00025)
- Sub-second finality
- Parallel execution via Sealevel
Solana Disadvantages
- Hardware requirements for validators
- Network outages history
- Centralization concerns
- Different programming model from EVM
When to Choose Solana
- High-frequency trading applications
- Real-time gaming
- Social platforms with millions of users
- Payment systems requiring instant finality
Interview Questions
-
How does Proof of History improve consensus efficiency in Solana?
- PoH creates a cryptographic timestamp for transactions before consensus
- Eliminates need for validators to communicate about transaction ordering
- Enables parallel transaction processing
- Reduces consensus overhead by providing verifiable ordering
-
Explain the difference between Solana's account model and Ethereum's state model.
- Solana: Programs are stateless, data stored in separate accounts
- Ethereum: Contracts have their own storage
- Solana enables parallel execution via separate accounts
- Ethereum contracts can access each other's storage
-
What are Program Derived Addresses and why are they important?
- PDAs are deterministic addresses without private keys
- Enable programs to sign for accounts
- Used for escrow, vaults, and cross-program invocations
- Created with seeds and program ID
Quiz Questions
-
What is the maximum transaction size on Solana?
- A) 128 bytes
- B) 1232 bytes
- C) 1MB
- D) 10MB
- Answer: B) 1232 bytes
-
Which consensus mechanism does Solana use?
- A) Proof of Work
- B) Proof of Stake
- C) Tower BFT with PoH
- D) Delegated Proof of Stake
- Answer: C) Tower BFT with PoH
-
What is the purpose of rent on Solana?
- A) Reward validators
- B) Prevent state bloat
- C) Pay for computation
- D) Store transaction history
- Answer: B) Prevent state bloat
Real-World Example: Payment System
use anchor_lang::prelude::*;
use anchor_spl::token::{self, Mint, Token, TokenAccount, Transfer};
declare_id!("PaymentProgram11111111111111111111111111111111");
#[program]
pub mod payment_system {
use super::*;
pub fn initialize_payment_channel(
ctx: Context<InitializeChannel>,
amount: u64,
) -> Result<()> {
let channel = &mut ctx.accounts.channel;
channel.merchant = ctx.accounts.merchant.key();
channel.customer = ctx.accounts.customer.key();
channel.total_deposited = amount;
channel.is_active = true;
// Transfer tokens to channel
let cpi_accounts = Transfer {
from: ctx.accounts.customer_token_account.to_account_info(),
to: ctx.accounts.channel_token_account.to_account_info(),
authority: ctx.accounts.customer.to_account_info(),
};
let cpi_ctx = CpiContext::new(
ctx.accounts.token_program.to_account_info(),
cpi_accounts,
);
token::transfer(cpi_ctx, amount)?;
Ok(())
}
pub fn process_payment(
ctx: Context<ProcessPayment>,
amount: u64,
) -> Result<()> {
let channel = &mut ctx.accounts.channel;
require!(channel.is_active, ProgramError::ChannelInactive);
require!(channel.total_deposited >= amount, ProgramError::InsufficientFunds);
// Transfer to merchant
let seeds = &[
b"channel".as_ref(),
channel.customer.as_ref(),
channel.merchant.as_ref(),
&[channel.bump],
];
let signer_seeds = &[&seeds[..]];
let cpi_accounts = Transfer {
from: ctx.accounts.channel_token_account.to_account_info(),
to: ctx.accounts.merchant_token_account.to_account_info(),
authority: ctx.accounts.channel.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, amount)?;
channel.total_deposited -= amount;
channel.total_paid += amount;
Ok(())
}
}
Conclusion
Solana provides a unique blockchain architecture optimized for performance and scalability. Understanding its core componentsβPoH, Tower BFT, Sealevel, and the account modelβis essential for building efficient decentralized applications. The parallel execution model and low costs make it ideal for high-frequency applications.