Version history: Solana / Anchor (Rust)
v1
scan: pass2026-08-11 — Ingested from sourceInitial version.
v2
currentscan: pass2026-11-02 — Currency pass 2026-11-01: retitled Solana / Anchor (Rust), which the body always was; globs now Rust-only (dropped tests/**/*.ts); fixed the bump] typo; Solidity msg.sender replaced by Signer/has_one/PDA checks; removed #[repr(packed)] and the redundant derive on #[account] structs; added InitSpace, ctx.bumps, checked math, #[error_code], init_if_needed caveat, Cargo.lock and IDL fixes.---- description: "Rust best practices for Solana smart contract development using Anchor framework and Solana SDK" - globs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts+ description: Rust best practices for Solana programs built with the Anchor framework and the Solana SDK + globs: "programs/**/*.rs, src/**/*.rs" alwaysApply: false ---- # Rust + Solana (Anchor) Best Practices+ # 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 standards - - Place program entrypoint logic in `lib.rs`, not `main.rs` - - Organize handlers into modules (e.g., `initialize`, `update`, `close`) - - Separate state definitions, errors, instructions, and utils - - Group reusable logic under a `utils` module (e.g., account validation) - - Use `declare_id!()` to define program ID+ - 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 all instruction contexts - - Validate accounts strictly using constraint macros (e.g., `#[account(mut)]`, `seeds`, `bump]`) - - Define all state structs with `#[account]` and `#[derive(AnchorSerialize, AnchorDeserialize)]` - - Prefer `Init`, `Close`, `Realloc`, `Mut`, and constraint macros to avoid manual deserialization - - Use `ctx.accounts` to access validated context accounts - - Handle CPI (Cross-Program Invocation) calls via Anchor’s CPI helpers+ - 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 - - Use **Borsh** or Anchor's custom serializer (not Serde) for on-chain data - - Always include `#[account(zero_copy)]` or `#[repr(C)]` for packed structures - - Avoid floating point types — use `u64`, `u128`, or fixed-point math - - Zero out or close unused accounts to reduce rent costs+ ## 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 - ## Testing - - Write tests in TypeScript using Anchor’s Mocha + Chai setup (`tests/*.ts`) - - Use `anchor.workspace.MyProgram` to load deployed contracts - - Use `provider.simulate()` to inspect failed txs - - Spin up a local validator (`anchor test`) and reset between tests - - Airdrop SOL to wallets with `provider.connection.requestAirdrop(...)` - - Validate program logs using `tx.confirmation.logMessages`+ ## 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 - ## Solana SDK (Manual) - - Use `solana_program` crate when not using Anchor (bare-metal programs) - - Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked` - - Use `solana_program::msg!` for lightweight debugging logs - - Verify accounts via `is_signer`, `is_writable`, `key == expected` - - Never panic! Use `ProgramError::Custom(u32)` or `ErrorCode` enums - ## Security Patterns- - Always validate `msg.sender`/signer with `account_info.is_signer` - - Prevent replay attacks via `seeds`, `bump`, and unique PDAs - - Use strict size checks before reallocating or deserializing - - Avoid unsafe unchecked casting; prefer Anchor deserialization - - For CPIs, validate `target_program` against expected program ID - - When using randomness, never rely on timestamps — use oracles or off-chain VRFs+ - 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 usage; avoid loops and recursion+ - Minimize compute units: avoid unbounded loops and recursion, and avoid cloning large account data - Avoid memory reallocations mid-instruction- - Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout - - Profile compute units with `solana logs` and `anchor run`+ - 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- - Add Anchor IDL support for front-end usage (JSON ABI) - - Use `anchor build`, `anchor deploy`, `anchor test` consistently - - Use separate `Anchor.toml` environments for devnet/mainnet/localnet+ - 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 `Cargo.lock` checked into `programs/` but not root+ - 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 accounts - - Include doc examples for each instruction - - Document PDA derivation logic and bump seed expectations - - Maintain up-to-date `README.md` with test commands and deployment steps+ - 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 `anchorProvider.wallet.publicKey` for signer verification in tests - - Do not hardcode keypairs — use env-based loading (`process.env.ANCHOR_WALLET`) - - Deploy with clear `cluster` targets (`localnet`, `devnet`, `mainnet`) - - Use `anchor keys sync` to propagate program ID changes - - Commit `target/idl/` and `target/types/` to share with front end+ - 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+ - Use GitHub Actions with `solana-cli`, `anchor-cli`, and Node installed; pin all three versions - Run `anchor test` in CI for every PR- - Use `solana program deploy` with explicit `--program-id` on production deploys - - Upload IDLs to a central registry (e.g., GitHub, IPFS, or `anchor.cloud`)+ - 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