Skip to content
Writing

· 3 min read

Anchor in production: account design, CPIs and compute that hold up

Lessons from shipping a multi-program Solana system: how I split programs, lay out accounts, sign CPIs with PDAs and keep every instruction inside its compute budget.

Jose Rai

Senior software engineer

Anchor makes your first Solana program easy. The tenth one, calling three others and holding real value, is where design decisions start to matter. These are the patterns I rely on after shipping a system of four Anchor programs that call each other.

Split programs by trust, not by feature

My rule: a program should own exactly the state it's responsible for protecting. In a privacy protocol, that gave me a mixer program that only knows about the Merkle tree and nullifiers, a staking program that only knows about stakes and seasons, a payment program for treasury flows, and a factory that users actually call. The factory holds the vaults and orchestrates the others through CPIs.

The payoff is review scope. Whoever audits the mixer reads one small program with one job, and the factory's job of moving tokens is checked on its own. The cost is CPIs, which is the next topic.

PDAs as signers

When the factory calls the mixer, the mixer needs to know the call really came from the factory and not from a user pretending to be it. The clean way is a PDA owned by the factory that signs the CPI, plus a constraint in the mixer that requires exactly that PDA:

rust
// Factory: sign the CPI with the factory's authority PDA.
let seeds: &[&[u8]] = &[b"authority", &[ctx.bumps.authority]];
let cpi_ctx = CpiContext::new_with_signer(
    ctx.accounts.mixer_program.to_account_info(),
    mixer::cpi::accounts::InsertCommitment {
        authority: ctx.accounts.authority.to_account_info(),
        tree: ctx.accounts.tree.to_account_info(),
    },
    &[seeds],
);
mixer::cpi::insert_commitment(cpi_ctx, commitment)?;

// Mixer: only the factory's authority PDA may insert.
#[derive(Accounts)]
pub struct InsertCommitment<'info> {
    #[account(seeds = [b"authority"], bump, seeds::program = FACTORY_PROGRAM_ID)]
    pub authority: Signer<'info>,
    #[account(mut)]
    pub tree: AccountLoader<'info, MerkleTree>,
}

seeds::program is the important line. It checks that the PDA is derived from the factory's program ID, so no other program can produce a valid signer.

Lay out accounts for the life of the program

Account size is fixed when the account is created, and migrating live accounts is painful. A few habits help:

  • Large state, like a Merkle tree, goes in a zero-copy account (#[account(zero_copy)] with AccountLoader), so the program reads it in place instead of deserializing kilobytes on every call.
  • Fixed-size arrays and explicit padding instead of Vec for anything on a hot path.
  • A version byte and some reserved space in every config account. It costs a little rent and saves a migration.
  • One PDA per user per thing (a stake position, a nullifier) instead of a growing shared list. Solana can only run transactions in parallel when they don't write the same accounts, so this scales better too.
rust
#[account(zero_copy)]
#[repr(C)]
pub struct MerkleTree {
    pub version: u8,
    pub _padding: [u8; 7],
    pub next_index: u64,
    pub current_root_index: u64,
    pub filled_subtrees: [[u8; 32]; 24],
    pub roots: [[u8; 32]; 32], // recent roots, so slightly old proofs still verify
}

Treat compute like a budget

Every transaction runs under a compute limit, and hashing, proof verification and CPIs add up fast. What works for me:

  • Measure every instruction in tests, and fail the build if one grows past its threshold.
  • Set the compute unit limit explicitly from the client, sized to the measured cost plus headroom, and add a priority fee when the network is busy.
  • Keep formatted msg! logging out of hot paths. Logging isn't free.
  • Move work off-chain when the chain only needs to verify it. Clients compute Merkle paths; the program only checks them.
ts
import { ComputeBudgetProgram } from "@solana/web3.js";

await program.methods
  .withdraw(proofA, proofB, proofC, root, nullifierHash, fee)
  .accounts({ /* ... */ })
  .preInstructions([
    ComputeBudgetProgram.setComputeUnitLimit({ units: 400_000 }),
    ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFee }),
  ])
  .rpc();

Errors and math

Every require! gets its own error code with a clear name, and the codes are documented for the frontend team, because silent failures turn into support tickets. Arithmetic on balances always uses checked math (checked_add, checked_sub) and returns an error instead of panicking or wrapping. Overflow checks in the release profile are a backstop, not the plan.

Testing and deploying

  • Fast tests run against an in-process validator, so the whole suite, including CPIs between programs, finishes in seconds.
  • A devnet suite runs the real deploy and initialize scripts end to end before anything ships.
  • The upgrade authority sits behind a multisig from the first mainnet deploy, and every upgrade comes with a written diff of account layouts.

None of this is exotic. It's the difference between a program that works in a demo and one you can hand to auditors, upgrade safely and keep running when traffic spikes.