{"filename":"rust.mdc","content":"---\ndescription: \"Rust best practices for Solana smart contract development using Anchor framework and Solana SDK\"\nglobs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts\nalwaysApply: false\n---\n# Rust + Solana (Anchor) Best Practices\n\n## Program Structure\n- Structure Solana programs using `Anchor` framework standards\n- Place program entrypoint logic in `lib.rs`, not `main.rs`\n- Organize handlers into modules (e.g., `initialize`, `update`, `close`)\n- Separate state definitions, errors, instructions, and utils\n- Group reusable logic under a `utils` module (e.g., account validation)\n- Use `declare_id!()` to define program ID\n\n## Anchor Framework\n- Use `#[derive(Accounts)]` for all instruction contexts\n- Validate accounts strictly using constraint macros (e.g., `#[account(mut)]`, `seeds`, `bump]`)\n- Define all state structs with `#[account]` and `#[derive(AnchorSerialize, AnchorDeserialize)]`\n- Prefer `Init`, `Close`, `Realloc`, `Mut`, and constraint macros to avoid manual deserialization\n- Use `ctx.accounts` to access validated context accounts\n- Handle CPI (Cross-Program Invocation) calls via Anchor’s CPI helpers\n\n## Serialization\n- Use **Borsh** or Anchor's custom serializer (not Serde) for on-chain data\n- Always include `#[account(zero_copy)]` or `#[repr(C)]` for packed structures\n- Avoid floating point types — use `u64`, `u128`, or fixed-point math\n- Zero out or close unused accounts to reduce rent costs\n\n## Testing\n- Write tests in TypeScript using Anchor’s Mocha + Chai setup (`tests/*.ts`)\n- Use `anchor.workspace.MyProgram` to load deployed contracts\n- Use `provider.simulate()` to inspect failed txs\n- Spin up a local validator (`anchor test`) and reset between tests\n- Airdrop SOL to wallets with `provider.connection.requestAirdrop(...)`\n- Validate program logs using `tx.confirmation.logMessages`\n\n## Solana SDK (Manual)\n- Use `solana_program` crate when not using Anchor (bare-metal programs)\n- Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked`\n- Use `solana_program::msg!` for lightweight debugging logs\n- Verify accounts via `is_signer`, `is_writable`, `key == expected`\n- Never panic! Use `ProgramError::Custom(u32)` or `ErrorCode` enums\n\n## Security Patterns\n- Always validate `msg.sender`/signer with `account_info.is_signer`\n- Prevent replay attacks via `seeds`, `bump`, and unique PDAs\n- Use strict size checks before reallocating or deserializing\n- Avoid unsafe unchecked casting; prefer Anchor deserialization\n- For CPIs, validate `target_program` against expected program ID\n- When using randomness, never rely on timestamps — use oracles or off-chain VRFs\n\n## Performance\n- Prefer zero-copy deserialization when accounts are large\n- Minimize compute usage; avoid loops and recursion\n- Avoid memory reallocations mid-instruction\n- Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout\n- Profile compute units with `solana logs` and `anchor run`\n\n## Dev Workflow\n- Use `anchor init` to scaffold projects\n- Add Anchor IDL support for front-end usage (JSON ABI)\n- Use `anchor build`, `anchor deploy`, `anchor test` consistently\n- Use separate `Anchor.toml` environments for devnet/mainnet/localnet\n- Format all Rust code with `cargo fmt`, lint with `cargo clippy`\n- Keep `Cargo.lock` checked into `programs/` but not root\n\n## Documentation\n- Use `///` Rust doc comments for all instructions and accounts\n- Include doc examples for each instruction\n- Document PDA derivation logic and bump seed expectations\n- Maintain up-to-date `README.md` with test commands and deployment steps\n\n## Wallet & Network Handling\n- Use `anchorProvider.wallet.publicKey` for signer verification in tests\n- Do not hardcode keypairs — use env-based loading (`process.env.ANCHOR_WALLET`)\n- Deploy with clear `cluster` targets (`localnet`, `devnet`, `mainnet`)\n- Use `anchor keys sync` to propagate program ID changes\n- Commit `target/idl/` and `target/types/` to share with front end\n\n## CI/CD & Deploy\n- Use GitHub Actions with `solana-cli`, `anchor-cli`, and `node` installed\n- Run `anchor test` in CI for every PR\n- Use `solana program deploy` with explicit `--program-id` on production deploys\n- Upload IDLs to a central registry (e.g., GitHub, IPFS, or `anchor.cloud`)\n"}