A Solana program is stateless executable code. All data lives in separate accounts, every instruction lists the accounts it will read or write, and a program may only modify accounts it owns. Anchor is a Rust framework that turns this into declarations: you describe each instruction's accounts in a #[derive(Accounts)] struct with constraints, and Anchor generates the deserialisation, ownership and signer checks, account type tags and a client-side IDL. A program derived address (PDA) is an account address computed from seeds plus the program's ID and deliberately placed off the ed25519 curve, so no private key exists for it. That gives you predictable addresses for per-user state, and accounts that only your program can sign for.
How do Solana programs store state?
Every account on Solana has the same fields: a balance in lamports, a byte array of data, an owner program, and an executable flag. Your program is one account (executable), and each piece of state it manages is another account whose owner is your program's ID. The runtime enforces two rules: only the owner can change an account's data or debit its lamports, and an account must hold enough lamports to be rent-exempt for its size, which is the cause of the "insufficient funds for rent" error.
Coming from the EVM, the shift looks like this:
| EVM contract | Solana program | |
|---|---|---|
| Code and state | Together in one contract | Code in the program, state in separate accounts |
| Per-user data | mapping(address => Data) inside the contract | One account per user, usually at a PDA |
| What a call touches | Discovered during execution | Declared up front in the instruction's account list |
| Who checks inputs | The contract, implicitly via its own storage | The program must validate every account it is handed |
| Upgrades | Proxy contracts | Programs are upgradeable in place by their upgrade authority |
The up-front account list is what lets Solana schedule non-overlapping transactions in parallel, without the speculative re-execution that optimistic engines like Sei's parallel EVM rely on. The cost is that a program receives accounts chosen by the caller. A raw program that forgets to check an account's owner, type or relationship to other accounts will happily operate on a fake one. Most Solana exploits are some form of that missing check, and it is the main problem Anchor exists to solve.
What does Anchor generate for you?
Anchor programs have three parts: a #[program] module with one function per instruction, a #[derive(Accounts)] struct per instruction, and #[account] data types. Here is a counter with one account per user, stored at a PDA:
use anchor_lang::prelude::*;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"); // set to your program ID by `anchor keys sync`
#[program]
pub mod counter {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let counter = &mut ctx.accounts.counter;
counter.authority = ctx.accounts.authority.key();
counter.count = 0;
counter.bump = ctx.bumps.counter; // canonical bump found during init
Ok(())
}
pub fn increment(ctx: Context<Increment>) -> Result<()> {
let counter = &mut ctx.accounts.counter;
counter.count = counter.count.checked_add(1).ok_or(CounterError::Overflow)?;
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(
init,
payer = authority,
space = 8 + Counter::INIT_SPACE,
seeds = [b"counter", authority.key().as_ref()],
bump
)]
pub counter: Account<'info, Counter>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(
mut,
seeds = [b"counter", authority.key().as_ref()],
bump = counter.bump,
has_one = authority @ CounterError::Unauthorized
)]
pub counter: Account<'info, Counter>,
pub authority: Signer<'info>,
}
#[account]
#[derive(InitSpace)]
pub struct Counter {
pub authority: Pubkey,
pub count: u64,
pub bump: u8,
}
#[error_code]
pub enum CounterError {
#[msg("count overflowed")]
Overflow,
#[msg("signer is not the counter's authority")]
Unauthorized,
}
Those few attributes expand into a lot of checks:
Account<'info, Counter>verifies the account is owned by this program and that its data starts with the 8-byte discriminator forCounter(by default the first 8 bytes ofsha256("account:Counter")). That stops someone passing a different account type with a similar layout. The8 +inspaceis room for that tag.Signerverifies the account signed the transaction.initcreates the account through a cross-program invocation (CPI) to the System Program, funds it frompayerwith the rent-exempt minimum, assigns it to your program and writes the discriminator.seedsandbumpre-derive the PDA and reject any account at a different address.has_one = authoritychecks thatcounter.authority == authority.key().Program<'info, System>checks that the right program was passed, not a look-alike.
anchor build also emits an IDL, a JSON description of instructions, accounts and types that client libraries use to build transactions and decode account data.
At the time of writing, Anchor's stable line is 1.x, now maintained by OtterSec, with a rewritten 2.0 in release-candidate testing. Anchor 1.0 renamed the TypeScript package from @coral-xyz/anchor to @anchor-lang/core, simplified Context lifetimes and made CpiContext take a program ID instead of an AccountInfo. Older tutorials still show the 0.x forms, so match examples to your version.
What is a PDA, exactly?
A normal Solana address is an ed25519 public key with a private key behind it. A PDA is derived like this:
- Concatenate the seeds (up to 16, each at most 32 bytes), a one-byte bump, the program ID and the string
"ProgramDerivedAddress". - Hash the result with SHA-256.
- If the hash happens to be a valid point on the ed25519 curve, it could have a private key, so reject it and try the next bump.
find_program_address starts at bump 255 and counts down until it finds an off-curve result. That first valid value is the canonical bump. Because no private key exists, nobody can sign a transaction for a PDA. Instead, the program that derived it can sign for it in a CPI by supplying the seeds, and the runtime re-derives the address to confirm it.
Clients compute the same address off-chain:
import { PublicKey } from "@solana/web3.js";
const [counterPda, bump] = PublicKey.findProgramAddressSync(
[Buffer.from("counter"), authority.toBuffer()],
programId,
);
// With the Anchor client, PDAs declared in the IDL are resolved automatically:
await program.methods.initialize().accounts({ authority }).rpc();
const counter = await program.account.counter.fetch(counterPda);
console.log(counter.count.toString());
(With @solana/kit, the equivalent is getProgramDerivedAddress({ programAddress, seeds }).)
PDAs serve two purposes:
- Deterministic storage addresses. Seeds like
["counter", user]act like a mapping key: anyone can compute where a user's data lives without an index. Associated token accounts are exactly this, PDAs of the Associated Token Program seeded by wallet, token program and mint. - Program-controlled authorities. A PDA can own tokens or SOL, act as a mint authority or hold an escrow, and only your program's logic can move what it holds.
How does a program sign for a PDA?
A SOL vault per user shows the signing side. The vault is a plain System-owned account at a PDA, so moving lamports out of it needs a System Program transfer signed with the vault's seeds:
use anchor_lang::system_program::{transfer, Transfer};
#[derive(Accounts)]
pub struct Withdraw<'info> {
#[account(mut, seeds = [b"vault", user.key().as_ref()], bump)]
pub vault: SystemAccount<'info>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
let user_key = ctx.accounts.user.key();
let bump = ctx.bumps.vault;
let signer_seeds: &[&[&[u8]]] = &[&[b"vault", user_key.as_ref(), &[bump]]];
let cpi = CpiContext::new_with_signer(
System::id(), // Anchor 0.x: ctx.accounts.system_program.to_account_info()
Transfer {
from: ctx.accounts.vault.to_account_info(),
to: ctx.accounts.user.to_account_info(),
},
signer_seeds,
);
transfer(cpi, amount)
}
Because the seeds constraint includes the signer's key, user A can never pass user B's vault: the derived address wouldn't match. Note that a System-owned vault must keep at least the rent-exempt minimum if any lamports remain, or the transfer fails.
Which PDA and Anchor mistakes cause bugs?
Using a non-canonical bump. Roughly half of the 256 possible bumps produce valid PDAs for the same seeds. If an instruction accepts a bump from the caller, an attacker may create a second, parallel account. Use the canonical bump from ctx.bumps at creation, store it, and verify with bump = account.bump afterwards.
Ambiguous seeds. Seeds are concatenated before hashing, so ["ab", "c"] and ["a", "bc"] derive the same address. Put variable-length values last, use fixed-length values such as pubkeys and u64::to_le_bytes(), or add a distinguishing prefix.
Missing relationship checks. Account<T> proves the type, not that this account belongs with the others. Add seeds, has_one or explicit constraint = ... checks linking accounts to the signer and to each other.
UncheckedAccount without checks. Anchor requires a /// CHECK: comment explaining why it is safe. Treat each one as a review item.
init_if_needed. It is behind a feature flag for a reason: if the instruction doesn't guard against existing state, it can be used to reset or re-initialise an account.
Closing accounts carelessly. Use the close = destination constraint, which zeroes the data and moves the lamports, rather than draining lamports by hand.
Compute and size. init and PDA derivation cost compute units, and find_program_address inside an instruction can loop through many bumps. Passing the stored bump is cheaper. If transactions start failing on compute, see how to set compute unit limits and priority fees.
How should I test an Anchor program?
anchor init scaffolds tests and anchor test builds, deploys to a local validator and runs them. Anchor 1.x defaults to Surfpool for the local network and generates a LiteSVM test template, which runs programs in-process and is much faster than a full validator. Write a negative test for every constraint: pass another user's PDA, a wrong signer, a non-canonical bump and an account of the wrong type, and assert each one fails with the expected error. When moving to devnet or mainnet, transactions can also expire before landing; handling "Blockhash not found" and dropped transactions covers the retry logic.
Summary
| Concept | What it means |
|---|---|
| Program | Stateless code; state lives in accounts it owns |
| Account list | Every instruction declares the accounts it touches |
#[derive(Accounts)] | Declarative validation of owner, type, signer and relationships |
| Discriminator | 8-byte type tag at the start of Anchor account data |
| PDA | Address from seeds plus program ID, off-curve, no private key |
| Canonical bump | First bump from 255 down that yields an off-curve address; store and reuse it |
invoke_signed / new_with_signer | How a program signs a CPI on behalf of its PDA |
Design rule of thumb: decide what seeds identify each piece of state, make every account relationship a constraint, and test that every wrong account is rejected.
Get the weekly commit
New blockchain deep dives every week.