Rust best practices for Solana smart contract development using Anchor framework and Solana SDK
Add this skill
npx mdskills install PatrickJS/cursor-rustComprehensive Solana/Anchor ruleset with strong security, testing, and workflow guidance
1---2description: Rust best practices for Solana smart contract development using Anchor framework and Solana SDK3globs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts4---56# Rust + Solana (Anchor) Best Practices78## Program Structure9- Structure Solana programs using `Anchor` framework standards10- Place program entrypoint logic in `lib.rs`, not `main.rs`11- Organize handlers into modules (e.g., `initialize`, `update`, `close`)12- Separate state definitions, errors, instructions, and utils13- Group reusable logic under a `utils` module (e.g., account validation)14- Use `declare_id!()` to define program ID1516## Anchor Framework17- Use `#[derive(Accounts)]` for all instruction contexts18- Validate accounts strictly using constraint macros (e.g., `#[account(mut)]`, `seeds`, `bump]`)19- Define all state structs with `#[account]` and `#[derive(AnchorSerialize, AnchorDeserialize)]`20- Prefer `Init`, `Close`, `Realloc`, `Mut`, and constraint macros to avoid manual deserialization21- Use `ctx.accounts` to access validated context accounts22- Handle CPI (Cross-Program Invocation) calls via Anchor’s CPI helpers2324## Serialization25- Use **Borsh** or Anchor's custom serializer (not Serde) for on-chain data26- Always include `#[account(zero_copy)]` or `#[repr(C)]` for packed structures27- Avoid floating point types — use `u64`, `u128`, or fixed-point math28- Zero out or close unused accounts to reduce rent costs2930## Testing31- Write tests in TypeScript using Anchor’s Mocha + Chai setup (`tests/*.ts`)32- Use `anchor.workspace.MyProgram` to load deployed contracts33- Use `provider.simulate()` to inspect failed txs34- Spin up a local validator (`anchor test`) and reset between tests35- Airdrop SOL to wallets with `provider.connection.requestAirdrop(...)`36- Validate program logs using `tx.confirmation.logMessages`3738## Solana SDK (Manual)39- Use `solana_program` crate when not using Anchor (bare-metal programs)40- Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked`41- Use `solana_program::msg!` for lightweight debugging logs42- Verify accounts via `is_signer`, `is_writable`, `key == expected`43- Never panic! Use `ProgramError::Custom(u32)` or `ErrorCode` enums4445## Security Patterns46- Always validate `msg.sender`/signer with `account_info.is_signer`47- Prevent replay attacks via `seeds`, `bump`, and unique PDAs48- Use strict size checks before reallocating or deserializing49- Avoid unsafe unchecked casting; prefer Anchor deserialization50- For CPIs, validate `target_program` against expected program ID51- When using randomness, never rely on timestamps — use oracles or off-chain VRFs5253## Performance54- Prefer zero-copy deserialization when accounts are large55- Minimize compute usage; avoid loops and recursion56- Avoid memory reallocations mid-instruction57- Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout58- Profile compute units with `solana logs` and `anchor run`5960## Dev Workflow61- Use `anchor init` to scaffold projects62- Add Anchor IDL support for front-end usage (JSON ABI)63- Use `anchor build`, `anchor deploy`, `anchor test` consistently64- Use separate `Anchor.toml` environments for devnet/mainnet/localnet65- Format all Rust code with `cargo fmt`, lint with `cargo clippy`66- Keep `Cargo.lock` checked into `programs/` but not root6768## Documentation69- Use `///` Rust doc comments for all instructions and accounts70- Include doc examples for each instruction71- Document PDA derivation logic and bump seed expectations72- Maintain up-to-date `README.md` with test commands and deployment steps7374## Wallet & Network Handling75- Use `anchorProvider.wallet.publicKey` for signer verification in tests76- Do not hardcode keypairs — use env-based loading (`process.env.ANCHOR_WALLET`)77- Deploy with clear `cluster` targets (`localnet`, `devnet`, `mainnet`)78- Use `anchor keys sync` to propagate program ID changes79- Commit `target/idl/` and `target/types/` to share with front end8081## CI/CD & Deploy82- Use GitHub Actions with `solana-cli`, `anchor-cli`, and `node` installed83- Run `anchor test` in CI for every PR84- Use `solana program deploy` with explicit `--program-id` on production deploys85- Upload IDLs to a central registry (e.g., GitHub, IPFS, or `anchor.cloud`)86
Full transparency — inspect the skill content before installing.