Skip to main content
rule

rust · patrickjs — Cursor rule: what it does, how to install

Guides Solana smart contract engineering with the Anchor framework and Rust SDK. Targets account safety, compute efficiency, and TypeScript testing.

Install into Cursor · Manually: put the files in place All methods and platforms ↓
.cursor/rules/rust.mdc
Open on GitHub

What rust does

This rule aligns the AI assistant with Anchor conventions for Solana programs. Program logic starts in lib.rs, instructions split into separate handler modules, and IDs rely on declare_id!(). All account structs require #[derive(Accounts)] alongside constraint attributes like mut, seeds, and bump to prevent missing verification checks.

On-chain calculations avoid floating-point math entirely, enforcing u64, u128, or fixed-point arithmetic instead. For large data structs, the instructions recommend #[account(zero_copy)] and Borsh serialization to keep compute unit usage low. Tests execute against a local validator via Mocha, Chai, and anchor test.

Local builds and CI pipelines require both solana-cli and anchor-cli installed in the development environment.

What it helps with

  • scaffold Anchor smart contracts with modular handler structures in lib.rs
  • enforce account constraints and signer verification on Solana instructions
  • write TypeScript test suites with local test validators and airdrops
  • minimize compute unit consumption with zero-copy deserialization

Example prompts for the agent

  • Create an Anchor program structure in programs/escrow/src/lib.rs with an initialize handler
  • Write a TypeScript test in tests/escrow.ts that simulates transaction execution
  • Add account validation attributes with seeds and bump constraints for a PDA

How to install rust

Manually: put the files in place

.cursor/rules/rust.mdc

Frontmatter: description, globs, alwaysApply

Step by step, with commands for each platform: Cursor rules: .mdc files, four modes and what replaced .cursorrules

Questions about rust

How do I install rust in Cursor?

Place the rule file at .cursor/rules/rust.mdc in your repository root.

What files does this rule target?

It targets Rust sources in programs/**/*.rs and src/**/*.rs, plus TypeScript files in tests/**/*.ts.

What serialization approach does the rule enforce?

It requires Borsh or Anchor serialization for on-chain structs, specifically advising against Serde.

Source text

rust.mdc · CC0-1.0
---
description: "Rust best practices for Solana smart contract development using Anchor framework and Solana SDK"
globs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts
alwaysApply: false
---
# 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 `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

## Performance
- Prefer zero-copy deserialization when accounts are large
- Minimize compute usage; avoid loops and recursion
- Avoid memory reallocations mid-instruction
- Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout
- Profile compute units with `solana logs` and `anchor run`

## 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
- Format all Rust code with `cargo fmt`, lint with `cargo clippy`
- Keep `Cargo.lock` checked into `programs/` but not root

## 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

## 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

## CI/CD & Deploy
- Use GitHub Actions with `solana-cli`, `anchor-cli`, and `node` installed
- 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`)

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Similar IDE rules

All IDE rules for Programming languages →

rust by other authors comes first.

From the same set234

The whole set →
shopify-theme-dev-liquid A Cursor rule collecting Shopify theme practices across Liquid, JavaScript, CSS, accessibility and performance. Useful when you build a theme and want the agent to keep the structure. ★ 41,024repo stars semiotic-react-dataviz-cursorrules-prompt-file Guides Cursor when building data charts with Semiotic in React, covering HOC props and event callbacks. ★ 41,024repo stars security-devsecops-ssdls-appsec This rule guides Cursor on secure coding, dependencies, access control, and security checks. Use it when you want these requirements applied while editing project files. ★ 41,024repo stars salesforce-apex-cursorrules-prompt-file A Cursor rule that points the agent at Salesforce Apex work: queueables instead of @future, GoF patterns, and almost no comments. ★ 41,024repo stars rust-general This rule guides safe, idiomatic Rust work. It fits projects where .rs, Cargo.toml, and Cargo.lock need consistent coding guidance. ★ 41,024repo stars rtl-right-to-left-i18n-cursorrules-prompt-file A Cursor rule that pushes the agent toward logical CSS and Tailwind utilities instead of left/right. Useful when the app has to run in Arabic, Hebrew, Persian or Urdu. ★ 41,024repo stars ros-ros2 Enforces conventions for ROS and ROS2 workspaces, covering composable nodes, package layout, and launch testing. ★ 41,024repo stars readme-best-practices-cursorrules-prompt-file This rule guides an agent writing project READMEs, from the opening pitch to a runnable Quick Start. Use it when you want documentation readers can scan and try. ★ 41,024repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor