RuleScan: pass
Solana / Anchor (Rust)
Rust rule for Solana programs built with Anchor 0.30+: program layout, account constraints, PDA and signer checks, checked math, error codes, zero-copy accounts, testing, and deploy workflow.
Add a trust badge to your README
[](https://waxmark.app/items/rust/scan)
---
description: Rust best practices for Solana programs built with the Anchor framework and the Solana SDK
globs: "programs/**/*.rs, src/**/*.rs"
alwaysApply: false
---
# Solana / Anchor (Rust) Best Practices
This rule is for on-chain Solana programs written in Rust with Anchor (0.30 or newer). It is not a general Rust style rule.
## Program Structure
- Structure Solana programs using Anchor framework conventions (`anchor init`)
- Place the program entrypoint (`#[program]`) in `lib.rs`, not `main.rs`
- Organize instruction handlers into modules (e.g., `instructions/initialize.rs`, `update.rs`, `close.rs`)
- Separate state definitions (`state/`), errors (`errors.rs`), instructions, and utils
- Group reusable logic under a `utils` module (e.g., shared account checks)
- Use `declare_id!()` to define the program ID and keep it in sync with `Anchor.toml` (`anchor keys sync`)
## Anchor Framework
- Use `#[derive(Accounts)]` for every instruction context
- Validate accounts with constraints, not manual code: `#[account(mut)]`, `seeds = [...]`, `bump`, `has_one = authority`, `constraint = ...`, `owner`, `address`
- Define state structs with `#[account]`; the macro already implements serialization, the owner check, and the 8-byte discriminator, so do not add `#[derive(AnchorSerialize, AnchorDeserialize)]` to them
- Prefer `init`, `init_if_needed`, `close`, `realloc`, and `mut` constraints to manual deserialization and manual lamport transfers
- Treat `init_if_needed` as opt-in and risky: it requires the `init-if-needed` feature and you must guard against re-initialization of an account that already holds state
- Use `ctx.accounts` to access validated accounts; use `ctx.bumps` for canonical PDA bumps instead of recomputing them
- Require signatures with `Signer<'info>` and typed program accounts with `Program<'info, T>`; use `UncheckedAccount` only with a `/// CHECK:` comment explaining why it is safe
- Perform CPIs through Anchor's generated CPI helpers (`CpiContext`, `CpiContext::new_with_signer` for PDA signers)
## Serialization and State
- Use Borsh via Anchor's derives (not Serde) for on-chain data
- Compute account sizes with `#[derive(InitSpace)]` and `8 + State::INIT_SPACE` instead of hand-counted byte totals
- Use `#[account(zero_copy)]` (which requires `#[repr(C)]`) only for large accounts that would otherwise exceed stack limits; never use `#[repr(packed)]`, which creates unaligned references and undefined behavior in safe-looking Rust
- Avoid floating point types; use `u64`, `u128`, or fixed-point math
- Close unused accounts with the `close = destination` constraint so rent is returned and the account cannot be revived
## Errors and Arithmetic
- Never `panic!` or `unwrap()` in handlers; define an `#[error_code]` enum and return with `require!`, `require_keys_eq!`, or `err!`
- Use checked arithmetic (`checked_add`, `checked_mul`, `checked_sub`) or `u128` intermediates; integer overflow in release builds is a security bug, not a crash
- Use `msg!` for lightweight debugging logs and remove noisy logs before deploying; every byte of log costs compute
## Security Patterns
- Signer checks: anything that authorizes an action must be a `Signer<'info>` and must be tied to the state it controls with `has_one` or a `constraint`
- Owner checks: use typed `Account<'info, T>` so Anchor verifies the owner program; never trust an `AccountInfo` without checking `owner`
- PDA checks: derive PDAs with `seeds` and `bump` constraints using the canonical bump; a client-supplied bump without validation enables account substitution
- Prevent duplicate-account attacks: when an instruction takes two accounts of the same type, assert their keys differ (`require_keys_neq!`)
- For CPIs, validate the target program against the expected program ID (`Program<'info, T>` or an `address =` constraint) so a malicious program cannot be substituted
- Validate sizes before `realloc` and before deserializing data you did not write
- When using randomness, never rely on slot hashes or timestamps as the sole source; use an oracle or off-chain VRF
## Performance
- Prefer zero-copy deserialization when accounts are large
- Minimize compute units: avoid unbounded loops and recursion, and avoid cloning large account data
- Avoid memory reallocations mid-instruction
- Measure compute with `solana logs` and the `ComputeBudget` values reported by `anchor test`; request a higher budget explicitly only when you have measured the need
## Testing
- Write integration tests in TypeScript with Anchor's Mocha setup (`tests/*.ts`, `anchor test`), or in Rust with `litesvm` or `solana-program-test` for faster unit-level tests
- Use `anchor.workspace.MyProgram` to load the program under test
- Use `program.methods.<ix>(...).simulate()` to inspect logs of failed transactions
- `anchor test` starts a fresh local validator; reset state between tests rather than depending on ordering
- Airdrop SOL to test wallets with `provider.connection.requestAirdrop(...)` and confirm before use
- Inspect program logs through `connection.getTransaction(signature, { commitment: "confirmed" }).meta.logMessages`
- Test the failure paths (wrong signer, wrong PDA, overflow), not only the happy path
## Solana SDK (Without Anchor)
- Use the `solana_program` crate for bare-metal programs
- Deserialize accounts explicitly from `AccountInfo` data and check length before reading
- Verify accounts via `is_signer`, `is_writable`, `owner`, and `key == expected`
- Return `ProgramError::Custom(u32)` from a custom error enum instead of panicking
## Dev Workflow
- Use `anchor init` to scaffold projects
- Use `anchor build`, `anchor deploy`, `anchor test` consistently; `anchor build` emits the IDL and TypeScript types in `target/`
- Use separate `Anchor.toml` cluster targets for `localnet`, `devnet`, and `mainnet`
- Format all Rust code with `cargo fmt`, lint with `cargo clippy`
- Keep the workspace `Cargo.lock` at the repository root checked in; programs are built as a single Cargo workspace
## Documentation
- Use `///` Rust doc comments for all instructions and account structs
- Document PDA derivation (seeds, bump) and who is expected to sign each instruction
- Maintain an up-to-date `README.md` with test commands and deployment steps
## Wallet & Network Handling
- Use `provider.wallet.publicKey` for the signer in tests
- Do not hardcode keypairs; load them from a path in `ANCHOR_WALLET` or `Anchor.toml`
- Deploy with explicit cluster targets (`localnet`, `devnet`, `mainnet`)
- Use `anchor keys sync` to propagate program ID changes to `declare_id!` and `Anchor.toml`
- Share `target/idl/` and `target/types/` with the front end through the build, not by hand-editing them
## CI/CD & Deploy
- Use GitHub Actions with `solana-cli`, `anchor-cli`, and Node installed; pin all three versions
- Run `anchor test` in CI for every PR
- Deploy with `anchor deploy --provider.cluster <cluster>` or `solana program deploy` with an explicit `--program-id` on production deploys
- Publish the IDL on-chain with `anchor idl init` / `anchor idl upgrade` so clients can fetch it
- Plan for upgrade authority: keep it on a multisig for mainnet programs or make the program immutable deliberately