> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Build Your First Solana Program

> Create a local Anchor program, build and test it, and walk through every file in the default counter program.

This quickstart uses the [Anchor framework](https://www.anchor-lang.com/docs)
starter project generated by `anchor init`. You will create the project locally,
run its tests, build the program, and walk through the program code that Anchor
generates.

## Prerequisites

Before you start,
[install the Solana development tools](/developers/docs/quickstart). The
installation includes Rust, the Solana CLI, and the Anchor CLI.

Use Anchor CLI version 1.1.2 or higher for this template. Check your installed
version:

```bash Terminal
anchor --version
```

<Steps titleSize="h3">

<Step title="Create the project">

Run the following commands in your terminal:

```bash Terminal
anchor init my-program
cd my-program
```

The starter project includes one Solana program under `programs/my-program`. The
program includes two instructions: one to initialize a counter account and one
to increment the counter.

Some parts of the template demonstrate common Solana program patterns: deriving
[PDA](/developers/docs/core/pda) account addresses, making a cross-program invocation
([CPI](/developers/docs/core/cpi)) to transfer SOL, and using custom error checks to stop
an instruction when a condition fails.

<Tree>
  <Tree.Folder name="my-program" defaultOpen>
    <Tree.File name="Anchor.toml" />
    <Tree.File name="Cargo.toml" />
    <Tree.Folder name="programs" defaultOpen>
      <Tree.Folder name="my-program" defaultOpen>
        <Tree.File name="Cargo.toml" />
        <Tree.Folder name="src" defaultOpen>
          <Tree.File name="lib.rs" />
          <Tree.File name="constants.rs" />
          <Tree.File name="error.rs" />
          <Tree.File name="instructions.rs" />
          <Tree.Folder name="instructions" defaultOpen>
            <Tree.File name="initialize.rs" />
            <Tree.File name="increment.rs" />
          </Tree.Folder>
          <Tree.File name="state.rs" />
        </Tree.Folder>
        <Tree.Folder name="tests" defaultOpen>
          <Tree.File name="test_initialize.rs" />
        </Tree.Folder>
      </Tree.Folder>
    </Tree.Folder>
  </Tree.Folder>
</Tree>

</Step>

<Step title="Build Program">

Run `anchor build` to compile the starter program:

```bash Terminal
anchor build
```

The compiled program is written to `target/deploy/my_program.so`. When the
program is deployed, the contents of this `.so` file are stored in an account
onchain.

</Step>

<Step title="Run Test">

Run the default test:

```bash Terminal
anchor test
```

This template's `Anchor.toml` uses the Rust test command:

```toml Anchor.toml
skip_local_validator = true

[scripts]
test = "cargo test"
```

The test loads the compiled program into [LiteSVM](https://www.litesvm.com/),
creates a payer, sends the `initialize`, and `increment` instructions,
then checks the counter account state.

Running `anchor test` also compiles the program, so you do not need to run
`anchor build` first when testing locally.

<Warning>
**`anchor build` or `anchor test` fails?** Programs can be built for different
SBPF versions, and recent Solana CLI releases build SBPF v3 by default. What
works depends on how you installed Anchor:

- **Anchor 1.1.2 with AVM**, as the installer sets it up: the first time
  `anchor` runs (the installer runs `anchor --version`), AVM installs Solana
  CLI 3.1.10, the release it pairs with Anchor 1.1.2, makes it your active
  Solana CLI, and prints `3.1.10 initialized`. `anchor build` and
  `anchor test` then work as shown.
  This page was tested with Anchor CLI 1.1.2, AVM 1.1.2, and Solana CLI 3.1.10.
- **Anchor 1.1.x without AVM, on Solana CLI 4.3 or later**: `anchor build`
  fails with `Platform tools v1.52 is incompatible with SBPFv3`. Build the
  program for SBPF v0 without the IDL, build the IDL on its own, then test
  without rebuilding (tested with Solana CLI 4.3.2):

  ```bash Terminal
  anchor build --no-idl -- --arch v0
  anchor idl build -o target/idl/my_program.json
  anchor test --skip-build
  ```

- **Anchor 1.2.0 or 1.2.1**: Anchor builds SBPF v3 programs, but the template
  that `anchor init` creates pins LiteSVM 0.10, which can't load them, so
  `anchor test` fails with `Err(Instruction(InvalidAccountData))` in
  `test_initialize.rs`. Build for v0, then test without rebuilding:

  ```bash Terminal
  anchor build --arch v0
  anchor test --skip-build
  ```

  Anchor 1.2.2 and later pin LiteSVM 0.15, which loads SBPF v3 programs, so
  `anchor test` works as shown.
</Warning>

</Step>

<Step title="Deploy Program">

Local tests are the fastest feedback loop. When you are ready to deploy to a
network, for example devnet, build first, then deploy to a cluster.

Deploying a Solana program requires SOL because the program is stored in an
account, and the account must pay for the space it uses. On devnet, get free
devnet SOL for your wallet from the [Solana Faucet](https://faucet.solana.com/).
Print your wallet address to paste into the faucet:

```bash Terminal
solana address
```

The devnet RPC faucet is closed, so `solana airdrop` works only against a local
validator. See [Airdrops and faucets](/developers/cookbook/development/airdrops-and-faucets)
for other ways to get test SOL.

```bash Terminal
anchor build
anchor program deploy --provider.cluster devnet
```

If you built with one of the workarounds in the warning above, build the same
way before you deploy.

`anchor program deploy` deploys the program that `anchor build` last wrote to
`target/deploy`. It replaces `anchor deploy`, which still works but prints
`Warning: 'anchor deploy' is deprecated. Use 'anchor program deploy' instead.`

</Step>

</Steps>

## Source files

The `src` directory contains the Solana program. Anchor's
[Program Structure](https://www.anchor-lang.com/docs/basics/program-structure)
docs explain the core macros used here, including `declare_id!`,
`#[program]`, `#[derive(Accounts)]`, and `#[account]`. This section
walks through the template files.

### lib.rs

`lib.rs` is the program entrypoint. It connects the source files, defines the
program address, and defines the program instructions that users can call.

```rust programs/my-program/src/lib.rs
pub mod constants;
pub mod error;
pub mod instructions;
pub mod state;

use anchor_lang::prelude::*;

pub use constants::*;
pub use instructions::*;
pub use state::*;

declare_id!("82sFkffP9wxwpyfZyeaKHH2chQoJPUGsJZSPi9mrUuXd");

#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        crate::instructions::initialize::handle_initialize(ctx)
    }

    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        crate::instructions::increment::handle_increment(ctx)
    }
}
```

<Note>
  **`pub mod constants`**

  `pub mod constants` makes `constants.rs` part of the program crate. This is
  where the template keeps shared program values such as the PDA seed, transfer
  amount, and maximum counter value.

  **`pub mod error`**

  `pub mod error` makes `error.rs` part of the program crate. This file
  defines the custom errors that the program can return when an instruction is
  invalid.

  **`pub mod instructions`**

  `pub mod instructions` makes `instructions.rs` part of the program crate.
  That file works like an index for the instruction-specific files in
  `src/instructions/`.

  **`pub mod state`**

  `pub mod state` makes `state.rs` part of the program crate. This file
  defines the data layout for accounts owned by this program, including the
  `Counter` account.

  **`anchor_lang::prelude`**

  `anchor_lang::prelude::*` imports the Anchor types and macros used to define
  a Solana program, including `Context`, `Result`, `Pubkey`,
  `Account`, `Signer`, and Anchor account attributes.

  The `pub use` lines make public items from the child modules available from
  the crate root. That keeps the instruction entrypoints short, such as
  `Context<Initialize>` instead of a longer module path.

  **`declare_id!`**

  `declare_id!` defines the program's address. It should match the address in
  `Anchor.toml`, the deployed program account, and any users or tests that call
  the program.

  **`#[program]`**

  `#[program]` tells Anchor to generate the Solana program entrypoint and
  instruction dispatch code. Public functions in this module become the
  instructions that users can call.

  **`pub fn initialize`, `pub fn increment`**

  `initialize` and `increment` are the two instruction names users can
  call. Each receives a `Context<T>`. The type inside `Context` defines
  the accounts required by that instruction, and Anchor validates those accounts
  before the instruction runs.

  **`handle_initialize`, `handle_increment`**

  The handler function contains the logic for the instruction.
</Note>

<Columns cols={2}>
  <div>
    ```toml Anchor.toml highlight={2} wrap
    [programs.localnet]
    my_program = "82sFkffP9wxwpyfZyeaKHH2chQoJPUGsJZSPi9mrUuXd"
    ```
  </div>

  <div>
    ```rust lib.rs highlight={1} wrap
    declare_id!("82sFkffP9wxwpyfZyeaKHH2chQoJPUGsJZSPi9mrUuXd");
    ```
  </div>
</Columns>

The same program address appears in configuration and code. `Anchor.toml` tells
Anchor which address to deploy or call for a cluster. `declare_id!` defines
the program address in the program for security checks.

### constants.rs

`constants.rs` keeps shared values in one place. In this template,
`COUNTER_SEED` derives the counter PDA, `HELLO_WORLD_LAMPORTS` is
transferred during initialization, and `MAX_COUNT` is checked before
incrementing.

```rust programs/my-program/src/constants.rs
use anchor_lang::prelude::*;

#[constant]
pub const COUNTER_SEED: &[u8] = b"counter";

#[constant]
pub const HELLO_WORLD_LAMPORTS: u64 = 1;

#[constant]
pub const MAX_COUNT: u64 = 10;
```

<Note>
  **`#[constant]`**

  `#[constant]` tells Anchor to include the value in the program IDL. That
  makes important program constants visible to generated clients and tooling.

  **`COUNTER_SEED`**

  `COUNTER_SEED` is the byte string used to derive the counter PDA. The
  program and test both use this seed so they agree on the account address without
  storing a separate keypair. This template uses one fixed seed, so the program
  has one counter address. Real programs often include a user's address or another
  identifier in the seeds to create many related accounts.

  **`HELLO_WORLD_LAMPORTS`**

  `HELLO_WORLD_LAMPORTS` is the amount of lamports transferred from the payer
  to the counter account inside `initialize`. It is deliberately tiny because
  the template is demonstrating a CPI to the System Program.

  **`MAX_COUNT`**

  `MAX_COUNT` is the upper bound checked by `increment`. Keeping it here
  gives the program, tests, and generated IDL one shared name for the rule.
</Note>

<Columns cols={2}>
  <div>
    ```rust initialize.rs highlight={8,18} wrap
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        // ...
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        // ...
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        // ...

        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        Ok(())
    }
    ```
  </div>

  <div>
    `initialize.rs` uses two constants:

    - `COUNTER_SEED` derives the counter PDA address.
    - `HELLO_WORLD_LAMPORTS` sets the amount
      transferred from the payer to the counter account.
  </div>
</Columns>

<Columns cols={2}>
  <div>
    ```rust increment.rs highlight={5} wrap
    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        // ...

        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        Ok(())
    }
    ```
  </div>

  <div>
    `increment.rs` uses `MAX_COUNT` as the counter's upper
    bound. If the current count is already at the maximum, `require!` returns
    `CounterOverflow` and the account data is not changed.
  </div>
</Columns>

### state.rs

`state.rs` defines custom data types for accounts the program creates and owns.
The program defines instructions to create, initialize, and update that data,
but the counter data is not stored inside the program itself. It is stored in a
separate account with its own address.

```rust programs/my-program/src/state.rs
use anchor_lang::prelude::*;

#[account]
#[derive(InitSpace)]
pub struct Counter {
    pub count: u64,
    pub authority: Pubkey,
}
```

<Note>
  **`#[account]`**

  `#[account]` tells Anchor this struct is data that can be stored in an
  onchain account owned by this program. Anchor uses it to serialize, deserialize,
  and validate `Counter` accounts.

  **`InitSpace`**

  `InitSpace` lets Anchor calculate `Counter::INIT_SPACE`, the number of
  bytes needed for this struct's fields. The 8-byte Anchor account discriminator
  is added separately when the account is created.

  **`count`**

  `count` is the counter value stored inside the account data.

  **`authority`**

  `authority` stores the address allowed to increment the counter.
  `initialize` writes this address, and `increment` requires that same
  address to sign.
</Note>

<Columns cols={2}>
  <div>
    ```rust initialize.rs highlight={4,12-13} wrap
    #[account(
        init,
        payer = payer,
        space = 8 + Counter::INIT_SPACE,
        seeds = [COUNTER_SEED],
        bump
    )]
    pub counter: Account<'info, Counter>,
    // ...

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        Ok(())
    }
    ```

    ```rust increment.rs highlight={4} wrap
    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        // ...

        ctx.accounts.counter.count += 1;
        Ok(())
    }
    ```
  </div>

  <div>
    `state.rs` defines the `Counter` account data. The instruction files use
    that type when they create and update the account:

    - `Counter::INIT_SPACE` sizes the account for the
      fields defined in `state.rs`.
    - `count` and `authority` are the field
      values written when the account is initialized.
    - `count += 1` updates the stored counter value
      after validation passes.
  </div>
</Columns>

### error.rs

`error.rs` defines the program's custom errors. In this template, the errors
demonstrate how instruction handlers stop when a caller is not allowed to update
the counter or the counter has already reached `MAX_COUNT`.

```rust programs/my-program/src/error.rs
use anchor_lang::prelude::*;

#[error_code]
pub enum ErrorCode {
    #[msg("Only the counter authority can update this counter")]
    Unauthorized,
    #[msg("Counter has reached the maximum value")]
    CounterOverflow,
}
```

<Note>
  **`#[error_code]`**

  `#[error_code]` tells Anchor to turn these variants into custom program
  errors. Clients and tests can use those errors instead of guessing from raw
  error codes.

  **`Unauthorized`**

  `Unauthorized` is returned when the transaction signer is not the authority
  stored in the counter account.

  **`CounterOverflow`**

  `CounterOverflow` is returned when incrementing would break the program's
  `MAX_COUNT` rule.
</Note>

<Columns cols={2}>
  <div>
    ```rust increment.rs highlight={5,9} wrap
    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </div>

  <div>
    `error.rs` names the errors that the instruction can return:

    - `ErrorCode::Unauthorized` is returned when
      the signer is not the authority stored in the counter account.
    - `ErrorCode::CounterOverflow` is returned when
      the counter has already reached `MAX_COUNT`.
  </div>
</Columns>

### instructions.rs

`instructions.rs` connects the instruction files to the program crate so
`lib.rs` can access the `initialize` and `increment` instruction code.
Each instruction file defines the accounts required by that instruction and the
handler logic that runs after Anchor validates those accounts.

```rust programs/my-program/src/instructions.rs
pub mod initialize;
pub mod increment;

pub use initialize::*;
pub use increment::*;
```

<Note>
  **`pub mod initialize`**

  The `pub mod` lines make `src/instructions/initialize.rs` and
  `src/instructions/increment.rs` part of the program crate.

  **`pub use initialize`**

  The `pub use` lines re-export public items from those files. That makes the
  instruction account structs and handler functions available through the
  `instructions` module.
</Note>

### initialize.rs

`initialize.rs` defines the accounts required to create the counter account, and
then writes the account's first values. The `#[derive(Accounts)]` struct
uses Anchor
[account constraints](https://www.anchor-lang.com/docs/references/account-constraints)
to say which accounts are required and how the new counter account is created.

```rust programs/my-program/src/instructions/initialize.rs
use anchor_lang::prelude::*;

use crate::{constants::*, state::Counter};

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    #[account(
        init,
        payer = payer,
        space = 8 + Counter::INIT_SPACE,
        seeds = [COUNTER_SEED],
        bump
    )]
    pub counter: Account<'info, Counter>,
    pub system_program: Program<'info, System>,
}

pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
    ctx.accounts.counter.count = 0;
    ctx.accounts.counter.authority = ctx.accounts.payer.key();

    let cpi_accounts = anchor_lang::system_program::Transfer {
        from: ctx.accounts.payer.to_account_info(),
        to: ctx.accounts.counter.to_account_info(),
    };
    let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
    anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

    msg!("Hello, world! Counter initialized");
    Ok(())
}
```

<Note>
  This file imports the shared constants and the `Counter` account type. The
  instruction uses those definitions to derive the PDA, choose the transfer
  amount, and allocate the account with the right data size.

  **`derive(Accounts)`**

  `Initialize` is the account context for the `initialize` instruction.
  Each field in the struct represents a separate account that must be included
  when the instruction is called. Anchor uses the struct to validate those
  incoming accounts before the handler runs.

  **`#[account(mut)]`**

  `#[account(mut)]` tells Anchor the payer account must be writable. This is
  required because account creation and the transfer CPI both deduct lamports from
  the payer.

  **`Signer<'info>`**

  `Signer<'info>` tells Anchor the payer must sign the transaction.

  **`#[account(`**

  The `#[account(...)]` block tells Anchor how to create and validate the
  counter account before the handler runs.

  **`init`**

  `init` tells Anchor to create the `counter` account before the handler
  runs. The new account is owned by this program so this program can store
  `Counter` data in it.

  **`payer = payer`**

  `payer = payer` specifies the `payer` account as the payer for creating
  the new counter account.

  **`space = 8 + Counter::INIT_SPACE`**

  `space = 8 + Counter::INIT_SPACE` allocates bytes for Anchor's account
  discriminator plus the `Counter` fields from `state.rs`. The discriminator
  helps Anchor confirm the account stores the expected type before reading it.

  **`seeds = [COUNTER_SEED]`**

  `seeds = [COUNTER_SEED]` says the counter account address must be the PDA
  derived from this seed and the program ID. With one fixed seed, there is one
  counter PDA for this program. To create separate counters in a real program, you
  would usually add another seed such as a user's address.

  **`bump`**

  `bump` tells Anchor to find and validate the PDA bump, which is the extra
  byte that makes the derived address valid as a PDA.

  **`Account<'info, Counter>`**

  `Account<'info, Counter>` tells Anchor to treat the account data as the
  `Counter` type from `state.rs`. Anchor also checks that the account is owned
  by this program.

  **`Program<'info, System>`**

  `Program<'info, System>` requires the caller to provide the System Program.
  Anchor uses it for the `init` account creation constraint. The handler's
  transfer CPI also invokes the System Program.

  **`handle_initialize`**

  The handler runs after Anchor validates the accounts and creates the counter
  account, so it can safely write the account's initial data.

  **`counter.count = 0`**

  Sets the `count` field in the counter account to `0`.

  **`counter.authority = ctx.accounts.payer.key()`**

  Sets the `authority` field in the counter account to the payer's address.

  **`system_program::Transfer`**

  These are the accounts passed to the System Program transfer instruction. This
  transfer CPI is included only to demonstrate how a CPI passes accounts to
  another program.

  **`CpiContext::new`**

  `CpiContext` packages the target program and required accounts for a
  cross-program invocation. Creating the context prepares the CPI by pairing the
  program you want to call with the accounts that program expects.

  **`system_program::transfer`**

  This CPI invokes the System Program's transfer instruction and moves
  `HELLO_WORLD_LAMPORTS` from the payer to the counter account.

  **`msg!`**

  `msg!` writes a message to the program logs when the program is invoked.
</Note>

<Steps>
  <Step title="Account Context">
    The `Initialize` struct defines the accounts that must be included when a
    user calls the `initialize` instruction. Anchor checks these accounts before
    the handler runs.

    ```rust initialize.rs focus={1-2}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="Payer Account">
    The `payer` account pays to create the counter account. The
    `Signer<'info>` type means the payer must sign the transaction, and
    `#[account(mut)]` means the payer account can be changed because lamports
    will be deducted.

    ```rust initialize.rs focus={3-4}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="Counter Account">
    The `counter` account stores the `Counter` data from `state.rs`.
    `init` tells Anchor to create this account before the handler runs, and
    `payer = payer` tells Anchor which account pays for creation.

    ```rust initialize.rs focus={5-12}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="Account Size">
    The `space` constraint tells Anchor how much account data to allocate.
    Anchor stores an 8-byte discriminator first, then the bytes needed for the
    `Counter` fields. The discriminator lets Anchor recognize this account as a
    `Counter` account before it deserializes the account data.

    ```rust initialize.rs focus={8}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="Counter Address">
    The `seeds` and `bump` constraints define the expected PDA address for
    the counter account. Anchor verifies that the provided `counter` account
    matches that address. The template uses a PDA so users can derive the counter
    address from the program ID and seed, making the counter address deterministic.

    ```rust initialize.rs focus={9-10}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="System Program">
    The `system_program` account is required because creating a new account uses
    the System Program.

    ```rust initialize.rs focus={13}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```
  </Step>

  <Step title="Handler Function">
    The `handle_initialize` function runs after Anchor validates the accounts in
    `Initialize`. The `ctx` value gives the handler access to those checked
    accounts.

    ```rust initialize.rs focus={16}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>

  <Step title="Initial Data">
    The handler writes the first values into the new counter account. The count
    starts at `0`, and the payer becomes the authority allowed to increment the
    counter later.

    ```rust initialize.rs focus={17-18}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>

  <Step title="Transfer Accounts">
    This transfer CPI is included only to demonstrate how a CPI passes accounts to
    another program. The `Transfer` struct lists the accounts used by the System
    Program transfer.

    ```rust initialize.rs focus={20-23}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>

  <Step title="CPI Context">
    `CpiContext::new` combines the program being called with the accounts passed
    to that program. This is the basic shape of a CPI: choose the program to invoke,
    collect the accounts that program expects, then pass both into the invocation.
    Here, the program being called is the System Program.

    ```rust initialize.rs focus={24}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>

  <Step title="Invoke Transfer">
    `anchor_lang::system_program::transfer` invokes the System Program transfer
    instruction. In this template, the transfer is a small example of calling
    another program from your program. If the transfer CPI fails, the
    `initialize` instruction fails as well.

    ```rust initialize.rs focus={25}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>

  <Step title="Log Message">
    `msg!` writes a message to the program logs. `Ok(())` indicates the
    instruction returned successfully.

    ```rust initialize.rs focus={27-28}
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }

    pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        ctx.accounts.counter.authority = ctx.accounts.payer.key();

        let cpi_accounts = anchor_lang::system_program::Transfer {
            from: ctx.accounts.payer.to_account_info(),
            to: ctx.accounts.counter.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(anchor_lang::system_program::ID, cpi_accounts);
        anchor_lang::system_program::transfer(cpi_ctx, HELLO_WORLD_LAMPORTS)?;

        msg!("Hello, world! Counter initialized");
        Ok(())
    }
    ```
  </Step>
</Steps>

### increment.rs

`increment.rs` defines the accounts required to update an existing counter
account. The handler checks that the signer is the stored authority, checks that
the count has not reached the specified `MAX_COUNT`, and then increments the
count.

```rust programs/my-program/src/instructions/increment.rs
use anchor_lang::prelude::*;

use crate::{constants::*, error::ErrorCode, state::Counter};

#[derive(Accounts)]
pub struct Increment<'info> {
    #[account(
        mut,
        seeds = [COUNTER_SEED],
        bump
    )]
    pub counter: Account<'info, Counter>,
    pub authority: Signer<'info>,
}

pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
    require_keys_eq!(
        ctx.accounts.counter.authority,
        ctx.accounts.authority.key(),
        ErrorCode::Unauthorized,
    );
    require!(
        ctx.accounts.counter.count < MAX_COUNT,
        ErrorCode::CounterOverflow,
    );

    ctx.accounts.counter.count += 1;
    msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
    Ok(())
}
```

<Note>
  **`derive(Accounts)`**

  `Increment` is the account context for the `increment` instruction.
  Anchor uses it to validate the mutable counter account and required signer.

  **`mut`**

  `mut` tells Anchor the counter account must be writable because the handler
  updates the stored `count` value.

  **`seeds = [COUNTER_SEED]`**

  `seeds = [COUNTER_SEED]` verifies that the provided counter account is the
  PDA derived from this seed and the program ID.

  **`bump`**

  `bump` tells Anchor to find and validate the PDA bump for the counter
  account.

  **`Account<'info, Counter>`**

  `Account<'info, Counter>` tells Anchor to deserialize the account data as
  the `Counter` type from `state.rs`. Anchor also checks that the account is
  owned by this program.

  **`Signer`**

  `Signer` requires the authority's signature. The handler then compares this
  signer's address to the authority stored in the counter account.

  **`handle_increment`**

  The handler runs after Anchor validates the account list, checks ownership, and
  deserializes the counter account.

  **`require_keys_eq!`**

  `require_keys_eq!` compares two public keys and stops the instruction unless
  the signer's address matches the authority stored in the counter account. This
  is the template's application-level authorization rule.

  **`require!`**

  `require!` checks a boolean rule and stops the instruction with
  `CounterOverflow` if the counter has already reached `MAX_COUNT`. This
  template rule demonstrates custom errors and failing before mutation.

  **`count += 1`**

  Only after both checks pass does the handler update the counter account data. If
  either check fails, the transaction fails and the account is not changed.

  **`msg!`**

  `msg!` writes a message to the program logs when the program is invoked.
</Note>

<Steps>
  <Step title="Account Context">
    The `Increment` struct defines the accounts that must be included when a
    user calls the `increment` instruction. Anchor checks these accounts before
    the handler runs.

    ```rust increment.rs focus={1-2}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }
    ```
  </Step>

  <Step title="Counter Account">
    The `counter` account stores the `Counter` data. The `mut`
    constraint allows the handler to update the stored count, and the `seeds`
    and `bump` constraints verify the counter PDA address.

    ```rust increment.rs focus={3-8}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }
    ```
  </Step>

  <Step title="Authority Signer">
    The `authority` account must sign the transaction. The handler later checks
    that this signer matches the authority stored in the counter account.

    ```rust increment.rs focus={9}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }
    ```
  </Step>

  <Step title="Handler Function">
    The `handle_increment` function runs after Anchor validates the accounts in
    `Increment`. The `ctx` value gives the handler access to those checked
    accounts.

    ```rust increment.rs focus={12}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }

    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </Step>

  <Step title="Authority Check">
    The first check makes sure the signer is allowed to update this counter. If the
    signer's address does not match `counter.authority`, the instruction stops
    with `ErrorCode::Unauthorized`. This demonstrates application-level
    authorization: the program owns the counter data, but it implements a rule for
    which signer may change that data.

    ```rust increment.rs focus={13-17}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }

    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </Step>

  <Step title="Max Count Check">
    The second check keeps the counter from going past `MAX_COUNT`. If the
    counter is already at the limit, the instruction stops with
    `ErrorCode::CounterOverflow`. This limit is an artificial rule in the
    template so you can see how custom errors stop an instruction before account
    data is changed.

    ```rust increment.rs focus={18-21}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }

    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </Step>

  <Step title="Update Count">
    Only after both checks pass does the handler update the account data. This line
    adds one to the stored counter value.

    ```rust increment.rs focus={23}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }

    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </Step>

  <Step title="Log Message">
    `msg!` writes the updated count to the program logs. `Ok(())` indicates
    the instruction returned successfully.

    ```rust increment.rs focus={24-25}
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }

    pub fn handle_increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.counter.authority,
            ctx.accounts.authority.key(),
            ErrorCode::Unauthorized,
        );
        require!(
            ctx.accounts.counter.count < MAX_COUNT,
            ErrorCode::CounterOverflow,
        );

        ctx.accounts.counter.count += 1;
        msg!("Hello, world! Counter is now {}", ctx.accounts.counter.count);
        Ok(())
    }
    ```
  </Step>
</Steps>

## Test file

`programs/my-program/tests/test_initialize.rs` is a Rust integration test. It
does not start a local validator. Instead, it loads the compiled `.so` file into
LiteSVM, builds transactions that call the program, and reads the counter
account after each transaction. The test builds instructions for a Solana
transaction by specifying the program ID of the program to invoke, providing
instruction data, and passing the required accounts.

<Columns cols={2}>
  <div>
    ```rust initialize.rs highlight={4,12-13} wrap
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(
            init,
            payer = payer,
            space = 8 + Counter::INIT_SPACE,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub system_program: Program<'info, System>,
    }
    ```

    ```rust test_initialize.rs highlight={5-7} wrap
    let instruction = Instruction::new_with_bytes(
        program_id,
        &my_program::instruction::Initialize {}.data(),
        my_program::accounts::Initialize {
            payer: payer.pubkey(),
            counter,
            system_program: system_program::ID,
        }
        .to_account_metas(None),
    );
    ```
  </div>

  <div>
    The `Initialize` account context defines the accounts required by the
    `initialize` instruction. The test passes those same accounts to the
    generated `my_program::accounts::Initialize` helper:

    - `payer` is passed as
      `payer: payer.pubkey()`.
    - `counter` is passed as `counter`.
    - `system_program` is passed as
      `system_program::ID`.

    `my_program::instruction::Initialize {}.data()`
    creates the instruction data. This is where instruction arguments would be
    encoded, but this `initialize` instruction does not require any arguments.
  </div>
</Columns>

<Columns cols={2}>
  <div>
    ```rust increment.rs highlight={8-9} wrap
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(
            mut,
            seeds = [COUNTER_SEED],
            bump
        )]
        pub counter: Account<'info, Counter>,
        pub authority: Signer<'info>,
    }
    ```

    ```rust test_initialize.rs highlight={5-6} wrap
    let instruction = Instruction::new_with_bytes(
        program_id,
        &my_program::instruction::Increment {}.data(),
        my_program::accounts::Increment {
            counter,
            authority: payer.pubkey(),
        }
        .to_account_metas(None),
    );
    ```
  </div>

  <div>
    The `Increment` account context defines the accounts required by the
    `increment` instruction. The test passes those same accounts to the
    generated `my_program::accounts::Increment` helper:

    - `counter` is passed as `counter`.
    - `authority` is passed as
      `authority: payer.pubkey()`.

    `my_program::instruction::Increment {}.data()`
    creates the instruction data. This is where instruction arguments would be
    encoded, but this `increment` instruction does not require any arguments.
  </div>
</Columns>

```rust programs/my-program/tests/test_initialize.rs
use {
    anchor_lang::{
        prelude::Pubkey,
        solana_program::{instruction::Instruction, system_program},
        AccountDeserialize, InstructionData, ToAccountMetas,
    },
    litesvm::LiteSVM,
    solana_keypair::Keypair,
    solana_message::{Message, VersionedMessage},
    solana_signer::Signer,
    solana_transaction::versioned::VersionedTransaction,
};

#[test]
fn test_initialize() {
    let program_id = my_program::id();
    let payer = Keypair::new();
    let counter = Pubkey::find_program_address(
        &[my_program::constants::COUNTER_SEED],
        &program_id,
    )
    .0;
    let mut svm = LiteSVM::new();
    let bytes = include_bytes!(concat!(
        env!("CARGO_TARGET_TMPDIR"),
        "/../deploy/my_program.so"
    ));
    svm.add_program(program_id, bytes).unwrap();
    svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap();

    let instruction = Instruction::new_with_bytes(
        program_id,
        &my_program::instruction::Initialize {}.data(),
        my_program::accounts::Initialize {
            payer: payer.pubkey(),
            counter,
            system_program: system_program::ID,
        }
        .to_account_metas(None),
    );

    let blockhash = svm.latest_blockhash();
    let msg = Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(msg), &[&payer]).unwrap();

    let res = svm.send_transaction(tx);
    assert!(res.is_ok());

    let counter_account = svm.get_account(&counter).unwrap();
    let mut data: &[u8] = &counter_account.data;
    let counter_state = my_program::state::Counter::try_deserialize(&mut data).unwrap();
    assert_eq!(counter_state.count, 0);
    assert_eq!(counter_state.authority, payer.pubkey());

    let instruction = Instruction::new_with_bytes(
        program_id,
        &my_program::instruction::Increment {}.data(),
        my_program::accounts::Increment {
            counter,
            authority: payer.pubkey(),
        }
        .to_account_metas(None),
    );

    let blockhash = svm.latest_blockhash();
    let msg = Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &blockhash);
    let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(msg), &[&payer]).unwrap();

    let res = svm.send_transaction(tx);
    assert!(res.is_ok());

    let counter_account = svm.get_account(&counter).unwrap();
    let mut data: &[u8] = &counter_account.data;
    let counter_state = my_program::state::Counter::try_deserialize(&mut data).unwrap();
    assert_eq!(counter_state.count, 1);
    assert_eq!(counter_state.authority, payer.pubkey());
}
```

<Note>
  **`litesvm::LiteSVM`**

  `LiteSVM` is an in-process Solana VM for tests. It lets the test register
  the compiled program, create accounts, send transactions, and inspect account
  state without starting a validator process.

  **`let program_id`**

  The test gets the program address from the `declare_id!` value through
  `my_program::id()` and creates a new payer keypair for the test transaction.

  **`Pubkey::find_program_address`**

  The counter address is derived from the same `COUNTER_SEED` used by the
  program. This makes the test target the PDA that `initialize.rs` expects.

  **`include_bytes!`**

  `include_bytes!` reads the compiled `my_program.so` file produced by the
  build. Those bytes are the executable program code that LiteSVM will run in the
  test.

  **`svm.add_program`**

  `svm.add_program` registers the compiled program bytes at the program
  address in LiteSVM. The airdrop gives the payer enough local SOL to pay for the
  transaction and account creation.

  **`let instruction`**

  `Instruction::new_with_bytes` creates an instruction to invoke the program.
  It includes the program ID, instruction data, and instruction accounts.

  **`svm.latest_blockhash`**

  Every Solana transaction needs a recent blockhash. In this test, LiteSVM
  provides a blockhash to use for the transaction.

  **`Message::new_with_blockhash`**

  The message contains the instruction, fee payer, and blockhash. This is the
  transaction data that will be signed.

  **`VersionedTransaction::try_new`**

  `VersionedTransaction::try_new` signs the message with the payer keypair.
  The payer signs because it pays the transaction fee and funds the new counter
  account.

  **`svm.send_transaction`**

  `svm.send_transaction` executes the transaction in LiteSVM.

  **`svm.get_account`**

  After the transaction runs, the test reads the counter account directly from
  LiteSVM so it can inspect the account data.

  **`Counter::try_deserialize`**

  The counter account stores serialized data. `Counter::try_deserialize`
  checks Anchor's account discriminator and turns the account data back into the
  `Counter` type from `state.rs`.

  **`assert_eq!(counter_state.count, 0)`**

  After `initialize` succeeds, the test deserializes the counter account and
  checks that the starting state matches what `handle_initialize` wrote.

  **`assert_eq!(counter_state.count, 1)`**

  After `increment` succeeds, the same counter account should have `count`
  set to `1` while keeping the same authority.
</Note>

## Project configuration

The root project files tell Anchor and Cargo how to build, test, and deploy the
program. For a full reference, see the Anchor docs for
[Anchor.toml configuration](https://www.anchor-lang.com/docs/references/anchor-toml)
and the [Anchor CLI](https://www.anchor-lang.com/docs/references/cli).

```toml Anchor.toml
skip_local_validator = true

[toolchain]

[features]
resolution = true
skip-lint = false

[programs.localnet]
my_program = "82sFkffP9wxwpyfZyeaKHH2chQoJPUGsJZSPi9mrUuXd"

[provider]
cluster = "localnet"
wallet = "~/.config/solana/id.json"

[scripts]
test = "cargo test"

[hooks]
```

<Note>
  **`skip_local_validator`**

  `skip_local_validator = true` tells Anchor not to start a validator for
  `anchor test`. The Rust test uses LiteSVM instead.

  **`programs.localnet`**

  `[programs.localnet]` maps the Rust crate name to the program address used for
  local builds and tests.

  **`provider`**

  `[provider]` sets the default cluster and wallet for commands such as
  `anchor program deploy`.

  **`scripts`**

  `[scripts]` changes what `anchor test` runs. In this template, `anchor test`
  runs `cargo test`.
</Note>
