The Solana Account Model & State Storage

14 min read

Module 2: The Solana Account Model & State Storage πŸ’Ύ

Welcome to Module 2 of the Basics of Solana Blockchain course! If you come from Ethereum, EVM-chains, or traditional backend systems, prepare for a mental paradigm shift.

On Ethereum, smart contracts are self-contained monoliths that hold their own logic and their own internal state (e.g., mapping(address => uint256)).

On Solana, programs are completely stateless.

Think of Solana as a massive, ultra-fast distributed operating system (much like Linux):

  • Programs are read-only executable binaries (like /bin/bash or /usr/bin/python).
  • Accounts are files that hold data and state (like documents sitting on a drive).

Let's dissect how this architecture works, why it exists, and how to manipulate it safely.


1. Executable Programs vs Data Accounts πŸ“„βš™οΈ

Definition

An Account on Solana is a 0-indexed memory buffer on the ledger, identified by a 32-byte public key (Pubkey). Every account shares an identical metadata envelope, regardless of whether it holds executable code, token balances, or a user profile.

The Problem

Traditional EVM blockchains bundle executable bytecode and contract state into the same contract address. When thousands of users interact with a contract concurrently, transactions queue up sequentially because each transaction might mutate the contract's shared global state. This makes parallel processing a nightmare.

The Solution: Separation of Code and State

Solana strictly separates executable instructions from the data those instructions mutate.

Every account on Solana matches this fundamental Rust schema:

rust
pub struct AccountInfo<'a> {
    pub key: &'a Pubkey,          // The account's unique address (32 bytes)
    pub is_signer: bool,          // Did this account sign the transaction?
    pub is_writable: bool,        // Can this account's data/lamports be modified?
    pub lamports: Rc<RefCell<&'a mut u64>>, // Account balance (1 SOL = 10^9 lamports)
    pub data: Rc<RefCell<&'a mut [u8]>>,   // Raw byte array storing custom data or code
    pub owner: &'a Pubkey,        // The program that controls writes to this account
    pub executable: bool,         // Flag: is this account a runnable program?
    pub rent_epoch: Epoch,        // Historical field (mostly preserved for runtime compatibility)
}
nix
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚             Solana Account           β”‚
                      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
                      β”‚ - key: Pubkey                        β”‚
                      β”‚ - lamports: u64                      β”‚
                      β”‚ - owner: Pubkey                      β”‚
                      β”‚ - rent_epoch: Epoch                  β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                         β”‚
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚                                               β”‚
                 β–Ό                                               β–Ό
     [ executable == true ]                          [ executable == false ]
   Executable Program Account                             Data Account
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ - data: SBF Bytecode        β”‚               β”‚ - data: Arbitrary State     β”‚
  β”‚ - owner: BPF Loader Program β”‚               β”‚ - owner: Custom Program     β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Executable Program Accounts

  • executable: true
  • data: Stores compiled Solana Bytecode Format (SBF) binary instructions.
  • owner: Must be owned by an official BPF Loader Program (e.g., BPFLoaderUpgradeab1e11111111111111111111111).
  • Behavior: Read-only during transaction execution. Multiple transactions can invoke the exact same program simultaneously across different validator CPU threads without race conditions.

Data Accounts

  • executable: false
  • data: Raw bytes holding serialized application state (e.g., custom structs, tokens, game state).
  • owner: Owned by a custom program (or the System Program).
  • Behavior: Can be marked as writable (is_writable: true) during execution. The runtime uses this flag to build the parallel dependency graph (Sealevel runtime).

Real-World Code Simulation: Fetching Accounts

Using @solana/web3.js (v1.x):

typescript
import { Connection, PublicKey } from "@solana/web3.js";

const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed");

async function inspectAccount(addressString: string) {
  const pubkey = new PublicKey(addressString);
  const accountInfo = await connection.getAccountInfo(pubkey);

  if (!accountInfo) {
    console.log("Account not found (unallocated or zero balance).");
    return;
  }

  console.log(`Address:     ${pubkey.toBase58()}`);
  console.log(`Lamports:    ${accountInfo.lamports} (${accountInfo.lamports / 1e9} SOL)`);
  console.log(`Owner:       ${accountInfo.owner.toBase58()}`);
  console.log(`Executable?: ${accountInfo.executable}`);
  console.log(`Data Length: ${accountInfo.data.length} bytes`);
}

// 1. Inspect an Executable Program (e.g., Token Program)
// TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
inspectAccount("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");

// 2. Inspect a standard Data Account (e.g., a user's token account)
inspectAccount("4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU");

Scope and Boundaries: What is Possible vs. Impossible

Action Allowed? Why the Boundary Exists
Executing a Data Account ❌ No The runtime checks executable == true. If false, execution halts immediately to prevent running unverified byte streams.
A program modifying its own bytecode during execution ❌ No Executable accounts are immutably locked as read-only during instruction execution to guarantee deterministic parallel execution.
Marking an account as executable after creation ⚠️ Highly Restricted Only a BPF Loader can mark an account as executable during the finalization of a program deployment or upgrade. Once marked executable, it cannot be converted back into a mutable data account.

2. Account Ownership, Rent, and Rent Exemption πŸͺ™πŸ›‘️

Definition

  • Account Ownership: A security rule where only the program declared in the account's owner field has write authority over its data field and the authority to debit its lamports.
  • Rent Exemption: A mechanism requiring accounts to hold a minimum balance of lamports proportional to their byte size, preventing ledger state bloat.

The Problem

If any transaction could alter any account's data or siphon funds, the network would collapse into anarchy. Furthermore, if storing data on-chain were free, bad actors could easily flood validator RAM with gigabytes of garbage data at negligible cost, crashing validator nodes.

The Solana "Constitution": Rules of Ownership

The Solana runtime strictly enforces cryptographic access boundaries at the instruction boundary:

  1. Only the owner program may modify an account's data.
  2. Only the owner program may debit lamports from an account.
  3. Anyone may credit (deposit) lamports to any account.
  4. Anyone may read the contents of any account.
  5. The owner can be reassigned only if:
    • The current owner signs off on the transfer, and
    • The account's data is empty/zeroed out.
pgsql
       Transaction Instruction
                 β”‚
                 β–Ό
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚  Attempts to mutate   β”‚
     β”‚      Account X        β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
                 β–Ό
     Is Caller Program ID == Account X.owner?
                / \
          YES  /   \  NO
              /     \
             β–Ό       β–Ό
    [Mutation]    [Runtime Error: "ExternalAccountDataModified"]
    [Allowed ]

A Quick Joke on Ownership:
Trying to write data to an account your program doesn’t own is like walking into your neighbor's house, painting their living room neon pink, and expecting the building inspector to applaud. The Solana runtime will throw an ExternalAccountDataModified error and throw you out.

The Modern Rent Model: Rent Exemption is Mandatory

Historically, Solana charged active "rent" per epoch, deducting lamports periodically until accounts ran out and were purged.

This is no longer true.

In modern Solana, rent collection is disabled, and rent-exemption is strictly enforced [1]:

  • Any new account created must hold enough lamports to be permanently rent-exempt [1].
  • The minimum balance is roughly calculated as:MinimumΒ Lamports=(AccountΒ OverheadΒ (128Β bytes)+DataΒ SizeΒ inΒ bytes)Γ—StaticΒ LamportΒ RateΒ perΒ Byte\text{Minimum Lamports} = (\text{Account Overhead (128 bytes)} + \text{Data Size in bytes}) \times \text{Static Lamport Rate per Byte}
  • If you try to execute a transaction that creates an account or shrinks an account's balance below this exemption threshold, the entire transaction fails.
  • When you close an account, all deposited lamports can be reclaimed back to your wallet!

Hands-on Calculation

To calculate the exact lamports required for an account of size NN:

typescript
import { Connection } from "@solana/web3.js";

const connection = new Connection("https://api.mainnet-beta.solana.com");

async function calculateStorageCost(bytes: number) {
  const rentExemptionAmount = await connection.getMinimumBalanceForRentExemption(bytes);
  console.log(`Space: ${bytes} bytes`);
  console.log(`Rent-exempt balance: ${rentExemptionAmount} lamports (${rentExemptionAmount / 1e9} SOL)`);
}

// Storing a simple 64-byte profile
calculateStorageCost(64);
// Space: 64 bytes -> ~0.00133 SOL

// Storing a 1,000,000-byte (1 MB) binary blob
calculateStorageCost(1_000_000);
// Space: 1,000,000 bytes -> ~6.96 SOL

Scope and Boundaries: What is Possible vs. Impossible

Action Allowed? Why the Boundary Exists
Siphoning lamports from an arbitrary account ❌ No Only the account's designated owner program can deduct lamports. Otherwise, unauthorized theft would be rampant.
Closing an account and taking back SOL βœ… Yes The owner program sets data length to zero, transfers all lamports to a destination address, and the runtime purges the account at the end of the transaction.
Creating an account with 0 lamports ❌ No Fails runtime verification. All accounts must satisfy rent-exemption requirements [1].

3. Program Derived Addresses (PDAs) and Seeds πŸ”‘πŸŒ±

Definition

A Program Derived Address (PDA) is a public key that does not have a corresponding private key. Instead, it is deterministically derived from a combination of user-defined string/byte arrays (seeds) and a Program ID, forced off the standard Ed25519 elliptic curve.

The Problem

Smart contracts often need to autonomously manage assets, hold deposits, or maintain deterministic state mappings (e.g., finding Alice’s specific account inside an escrow program).

If a program had to hold a private key to sign transactions, where would it store that private key? If stored in plaintext on-chain, anyone could read it and steal everything!

The Solution: Off-Curve Cryptography

The standard Ed25519 signature scheme produces valid public keys that satisfy the curve equation:

βˆ’x2+y2=1βˆ’121665121666x2y2-x^2 + y^2 = 1 - \frac{121665}{121666} x^2 y^2

Solana's runtime searches for a address that does not lie on this curve. Because it does not lie on the curve, no mathematical scalar multiplier (private key) exists for it.

To derive a PDA:

  1. You pass custom seeds (e.g., ["user-profile", user_pubkey.as_ref()]) and the program_id.
  2. Solana appends an extra 1-byte number called a bump seed, starting at 255 and counting down to 0.
  3. It runs SHA-256 over (seeds + bump + program_id).
  4. The moment the resulting hash falls off the Ed25519 curve, the function returns that Pubkey and the winning bump [2].
vbnet
Seeds: ["escrow", Alice_Pubkey] + Program ID
                   β”‚
                   β–Ό
       Hash with bump = 255
                   β”‚
         Is point on Ed25519 curve?
                /     \
         YES   /       \   NO
              /         \
   Try bump = 254        β–Ό
         ...       Valid PDA Found!
                   (No private key exists)

Because no private key exists, an external hacker cannot sign for this address off-chain. Only the designated program can sign on-chain on its behalf by providing the correct seeds to the runtime using the invoke_signed syscall!

Hands-on: Deriving a PDA in TypeScript

typescript
import { PublicKey } from "@solana/web3.js";

const PROGRAM_ID = new PublicKey("G1D8dNEndsgv2K3cwopG4f5U5rV42LgU6qN18GqXF9p5");
const userWallet = new PublicKey("4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU");

// Derive Alice's Profile PDA using two seeds: the string "profile" + her wallet address
const [profilePda, bump] = PublicKey.findProgramAddressSync(
  [Buffer.from("profile"), userWallet.toBuffer()],
  PROGRAM_ID
);

console.log(`Derived PDA: ${profilePda.toBase58()}`);
console.log(`Canonical Bump: ${bump}`);

How Programs Sign for PDAs (In Rust)

When a program calls another program (Cross-Program Invocation / CPI), it doesn't supply a cryptographic signature. Instead, it supplies the original seeds and bump via invoke_signed:

rust
// Inside a Solana Native / Anchor program
use anchor_lang::solana_program::program::invoke_signed;
use anchor_lang::solana_program::system_instruction;

let bump_seed = &[bump];
let signer_seeds: &[&[&[u8]]] = &[&[
    b"profile",
    user_account.key.as_ref(),
    bump_seed,
]];

// Transfer funds out of the PDA using the PDA's derived authority!
invoke_signed(
    &system_instruction::transfer(pda_account.key, recipient.key, 1_000_000),
    &[pda_account.clone(), recipient.clone(), system_program.clone()],
    signer_seeds,
)?;

The runtime inspects the seeds, executes findProgramAddress internally, verifies that the calling program owns that address derivation, and marks is_signer = true for that PDA during execution!

Scope and Boundaries: What is Possible vs. Impossible

Action Allowed? Why the Boundary Exists
Signing a transaction off-chain with a PDA ❌ No There is literally no private key in the mathematical universe for that address.
Signing for a PDA derived from Program B inside Program A ❌ No The runtime embeds the caller's Program ID into the derivation check. Program A can never forge Program B's PDAs.
Max Seed Length & Quantity ⚠️ Max 16 seeds, max 32 bytes per seed Keeps runtime computation within tight, predictable verification limits.

4. System Program Operations and Account Allocation πŸ—οΈβš™οΈ

Definition

The System Program (11111111111111111111111111111111) is the core foundational program of Solana. It handles base-level ledger mechanics: creating uninitialized accounts, allocating heap memory, reallocating account sizes, assigning ownership, and transferring native SOL.

The Problem

When you generate a keypair locally (e.g., using Keypair.generate()), you hold a valid cryptographic keypair, but that account does not physically exist on the blockchain.

If you attempt to write data to it, the runtime rejects the call. You must first register it on the ledger, fund it with rent-exemption lamports, and allocate a defined byte space.

Key Low-Level Operations

The System Program exposes several primary primitive instructions:

  1. CreateAccount: An all-in-one atomic operation:
    • Debits a funding account for rent-exemption lamports.
    • Allocates XX bytes of data space.
    • Assigns the owner to a target program ID.
  2. Allocate: Allocates memory space (zero-filled bytes) to an existing account.
  3. Assign: Reassigns the owner field from the System Program to a custom program ID.
  4. Transfer: Transfers native lamports between accounts.

Practical Simulation: Creating an Account Atomically

Here is how you initialize a custom data account using @solana/web3.js:

typescript
import {
  Connection,
  Keypair,
  Transaction,
  SystemProgram,
  sendAndConfirmTransaction,
} from "@solana/web3.js";

async function createNewAccount(
  connection: Connection,
  payer: Keypair,
  targetProgramOwner: Keypair
) {
  // 1. Generate an identity for the new data account
  const newAccount = Keypair.generate();
  
  // 2. Define data footprint
  const SPACE = 256; // 256 bytes

  // 3. Query required rent exemption balance
  const lamports = await connection.getMinimumBalanceForRentExemption(SPACE);

  // 4. Construct the CreateAccount instruction
  const createAccountIx = SystemProgram.createAccount({
    fromPubkey: payer.publicKey,
    newAccountPubkey: newAccount.publicKey,
    lamports: lamports,
    space: SPACE,
    programId: targetProgramOwner.publicKey, // New owner!
  });

  const tx = new Transaction().add(createAccountIx);

  // 5. Send transaction. Notice: both payer AND newAccount must sign!
  const txSig = await sendAndConfirmTransaction(connection, tx, [
    payer,
    newAccount, // Proves ownership of the private key for the new account
  ]);

  console.log(`Account created successfully! TX: ${txSig}`);
  console.log(`New Account: ${newAccount.publicKey.toBase58()}`);
}

Dynamic Resizing with realloc

What happens if you allocate 100 bytes for a user profile, and later need to add a 200-byte shopping history?

Historically, accounts were fixed in size forever. In modern Solana, owner programs can dynamically resize accounts during execution via realloc.

rust
// Native Rust realloc snippet inside your program instruction:
let new_size = 300;
account_info.realloc(new_size, false)?;

// Adjust rent exemption balance to accommodate new size!
let rent = Rent::get()?;
let new_minimum_balance = rent.minimum_balance(new_size);
let lamports_diff = new_minimum_balance.saturating_sub(account_info.lamports());

if lamports_diff > 0 {
    // Transfer additional lamports from the user to maintain rent-exemption
    invoke(
        &system_instruction::transfer(user_info.key, account_info.key, lamports_diff),
        &[user_info.clone(), account_info.clone(), system_program.clone()],
    )?;
}

Scope and Boundaries: Hard Constraints

Solana imposes strict engineering boundaries on accounts to protect validator hardware:

fortran
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   ACCOUNT LIMITS                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Max Total Account Size:        10 Megabytes (10 MiB)  β”‚
β”‚  Max Size Increment (realloc):  10,240 Bytes (10 KiB)  β”‚
β”‚  Base Account Overhead:         128 Bytes              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • Why does the 10 MiB hard cap exist?
    Solana accounts reside in validator physical memory (RAM) or memory-mapped files via AccountsDB to sustain 2,000+ real TPS. Massive gigabyte-sized accounts would exhaust validator resources and stall consensus.
  • Why does the 10 KiB realloc boundary exist?
    When an instruction executes, the runtime must allocate and shift memory buffers in memory within predictable compute unit budgets (CU). Expanding an account by megabytes inside a single microsecond execution window could cause transaction timeouts. If you need an account to grow by 50 KB, you must expand it across multiple 10 KiB realloc invocations.

Architecture Summary Matrix 🧭

Concept Who Controls It? Key Constraint Real-World Analog
Executable Program BPF Upgradeable Loader Read-only during execution; code cannot be mutated in-flight. An application binary (/usr/bin/git)
Data Account Program designated in owner Only the owner program can write data or debit funds. A database record or user profile file
PDA Program that derived it Off-curve; cannot hold or use a private key. An escrow deposit box unlocked only by contract rules
System Program Built-in native program ID 111...111 Max 10 MiB per account; max 10 KiB expansion per instruction. The OS kernel filesystem allocator

References & Further Reading πŸ“š

Challenge

Solana Architecture: Ownership and Determinism Challenge

Solana operates on a unique model where programs (code) are separated from accounts (state). Understanding the boundaries of ownership and the constraints of Program Derived Addresses (PDAs) is fundamental to building secure Solana applications. Please answer the following conceptual questions concisely.

*Note: This is a conceptual challenge. Answer using complete sentences or technical phrases.

Expected result

The expected output is the user's written answers to the three questions provided in the initial code block.

plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.