# Solana/Anchor Project Guide

## Architecture

This is a Solana program built with the Anchor framework.

```
programs/             Anchor programs (Rust)
  my-program/
    src/
      lib.rs          Program entry point, instruction handlers
      state.rs        Account data structures
      error.rs        Custom error definitions
      instructions/   Instruction handler modules
tests/                TypeScript integration tests
migrations/           Deployment migration scripts
Anchor.toml           Anchor project configuration
Cargo.toml            Rust workspace configuration
```

## Program Structure

### Account Definitions

Define account data structures using `#[account]`:

```rust
#[account]
pub struct GameState {
    pub authority: Pubkey,
    pub score: u64,
    pub bump: u8,
}
```

Always include a `bump` field for PDA accounts. Calculate space with `8 (discriminator) + field sizes`.

### Instructions

Define instruction contexts using `#[derive(Accounts)]`:

```rust
#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub authority: Signer<'info>,
    #[account(
        init,
        payer = authority,
        space = 8 + GameState::INIT_SPACE,
        seeds = [b"game", authority.key().as_ref()],
        bump,
    )]
    pub game_state: Account<'info, GameState>,
    pub system_program: Program<'info, System>,
}
```

### PDAs (Program Derived Addresses)

- Use `seeds` and `bump` constraints in account validation.
- Derive PDAs with meaningful seed combinations (e.g., `[b"user", user_pubkey]`).
- Store the bump in the account to avoid recomputing it.
- Use `#[account(seeds = [...], bump = account.bump)]` for subsequent accesses.

### CPIs (Cross-Program Invocations)

Use `CpiContext` for calling other programs:

```rust
let cpi_ctx = CpiContext::new(
    ctx.accounts.token_program.to_account_info(),
    Transfer {
        from: ctx.accounts.source.to_account_info(),
        to: ctx.accounts.destination.to_account_info(),
        authority: ctx.accounts.authority.to_account_info(),
    },
);
token::transfer(cpi_ctx, amount)?;
```

For CPIs from PDA-owned accounts, use `CpiContext::new_with_signer` with the PDA seeds.

## Commands

```bash
anchor build              # compile the program
anchor test               # build and run all tests
anchor deploy             # deploy to configured cluster
anchor keys list          # show program keypairs
cargo clippy -- -D warnings  # lint Rust code
```

## TypeScript Client

The TypeScript client is auto-generated by Anchor from the IDL.

```typescript
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { MyProgram } from "../target/types/my_program";

const program = anchor.workspace.MyProgram as Program<MyProgram>;

// Call an instruction
await program.methods
  .initialize()
  .accounts({
    authority: wallet.publicKey,
    gameState: gameStatePda,
    systemProgram: anchor.web3.SystemProgram.programId,
  })
  .rpc();

// Fetch account data
const state = await program.account.gameState.fetch(gameStatePda);
```

## Testing

### With Bankrun (Recommended)

Bankrun provides a fast, lightweight test environment:

```typescript
import { startAnchor } from "solana-bankrun";
import { BankrunProvider } from "anchor-bankrun";

const context = await startAnchor(".", [], []);
const provider = new BankrunProvider(context);
```

### With Local Validator

```typescript
import * as anchor from "@coral-xyz/anchor";

describe("my-program", () => {
  anchor.setProvider(anchor.AnchorProvider.env());
  const program = anchor.workspace.MyProgram;

  it("initializes", async () => {
    // test code
  });
});
```

### Testing Best Practices

- Test all instruction handlers with valid inputs.
- Test constraint violations (wrong signer, wrong PDA, insufficient funds).
- Test edge cases (zero amounts, max values, duplicate operations).
- Verify account state after each instruction.
- Test PDA derivation matches expected addresses.

## Coding Conventions

- Use `msg!()` for logging (visible in transaction logs).
- Define custom errors with `#[error_code]` for meaningful error messages.
- Use `require!()` and `require_keys_eq!()` for input validation.
- Keep instruction handlers thin. Extract business logic into helper functions.
- Use `impl` blocks on account structs for data methods.
- Follow Rust naming conventions: `snake_case` for functions, `PascalCase` for types.
