codingVerified
Rust + Solana (Anchor Framework)
Rust best practices for Solana smart contract development with Anchor
content
# Rust + Solana (Anchor) Best Practices ## 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 ## 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 ## 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 ## 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` ## Solana SDK (Manual) - Use `solana_program` crate when not using Anchor (bare-metal programs) - Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked` - Use `sol
rustsolanaanchorweb3smart-contracts
Compatible with
cursoropenclawclaude-code