Skip to content
This quickstart uses the Anchor framework 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. 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:
Terminal
1

Create the project

Run the following commands in your terminal:
Terminal
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 account addresses, making a cross-program invocation (CPI) to transfer SOL, and using custom error checks to stop an instruction when a condition fails.
my-program
Anchor.toml
Cargo.toml
programs
my-program
Cargo.toml
src
lib.rs
constants.rs
error.rs
instructions.rs
instructions
initialize.rs
increment.rs
state.rs
tests
test_initialize.rs
2

Build Program

Run anchor build to compile the starter program:
Terminal
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.
3

Run Test

Run the default test:
Terminal
This template’s Anchor.toml uses the Rust test command:
Anchor.toml
The test loads the compiled program into LiteSVM, 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.
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):
    Terminal
  • 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:
    Terminal
    Anchor 1.2.2 and later pin LiteSVM 0.15, which loads SBPF v3 programs, so anchor test works as shown.
4

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. Print your wallet address to paste into the faucet:
Terminal
The devnet RPC faucet is closed, so solana airdrop works only against a local validator. See Airdrops and faucets for other ways to get test SOL.
Terminal
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.

​Source files

The src directory contains the Solana program. Anchor’s 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.
programs/my-program/src/lib.rs
pub mod constantspub 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 errorpub 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 instructionspub 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 statepub 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::preludeanchor_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 incrementinitialize 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_incrementThe handler function contains the logic for the instruction.
Anchor.toml
lib.rs
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.
programs/my-program/src/constants.rs
#[constant]#[constant] tells Anchor to include the value in the program IDL. That makes important program constants visible to generated clients and tooling.COUNTER_SEEDCOUNTER_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_LAMPORTSHELLO_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_COUNTMAX_COUNT is the upper bound checked by increment. Keeping it here gives the program, tests, and generated IDL one shared name for the rule.
initialize.rs
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.
increment.rs
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.

​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.
programs/my-program/src/state.rs
#[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.InitSpaceInitSpace 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.countcount is the counter value stored inside the account data.authorityauthority stores the address allowed to increment the counter. initialize writes this address, and increment requires that same address to sign.
initialize.rs
increment.rs
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.

​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.
programs/my-program/src/error.rs
#[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.UnauthorizedUnauthorized is returned when the transaction signer is not the authority stored in the counter account.CounterOverflowCounterOverflow is returned when incrementing would break the program’s MAX_COUNT rule.
increment.rs
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.

​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.
programs/my-program/src/instructions.rs
pub mod initializeThe pub mod lines make src/instructions/initialize.rs and src/instructions/increment.rs part of the program crate.pub use initializeThe pub use lines re-export public items from those files. That makes the instruction account structs and handler functions available through the instructions module.

​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 to say which accounts are required and how the new counter account is created.
programs/my-program/src/instructions/initialize.rs
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.initinit 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 = payerpayer = payer specifies the payer account as the payer for creating the new counter account.space = 8 + Counter::INIT_SPACEspace = 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.bumpbump 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_initializeThe handler runs after Anchor validates the accounts and creates the counter account, so it can safely write the account’s initial data.counter.count = 0Sets 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::TransferThese 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::newCpiContext 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::transferThis 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.
1

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.
initialize.rs
2

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.
initialize.rs
3

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.
initialize.rs
4

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.
initialize.rs
5

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.
initialize.rs
6

System Program

The system_program account is required because creating a new account uses the System Program.
initialize.rs
7

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.
initialize.rs
8

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.
initialize.rs
9

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.
initialize.rs
10

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.
initialize.rs
11

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.
initialize.rs
12

Log Message

msg! writes a message to the program logs. Ok(()) indicates the instruction returned successfully.
initialize.rs

​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.
programs/my-program/src/instructions/increment.rs
derive(Accounts)Increment is the account context for the increment instruction. Anchor uses it to validate the mutable counter account and required signer.mutmut 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.bumpbump 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.SignerSigner requires the authority’s signature. The handler then compares this signer’s address to the authority stored in the counter account.handle_incrementThe 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 += 1Only 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.
1

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.
increment.rs
2

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.
increment.rs
3

Authority Signer

The authority account must sign the transaction. The handler later checks that this signer matches the authority stored in the counter account.
increment.rs
4

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.
increment.rs
5

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.
increment.rs
6

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.
increment.rs
7

Update Count

Only after both checks pass does the handler update the account data. This line adds one to the stored counter value.
increment.rs
8

Log Message

msg! writes the updated count to the program logs. Ok(()) indicates the instruction returned successfully.
increment.rs

​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.
initialize.rs
test_initialize.rs
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.
increment.rs
test_initialize.rs
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.
programs/my-program/tests/test_initialize.rs
litesvm::LiteSVMLiteSVM 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_idThe 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_addressThe 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_programsvm.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 instructionInstruction::new_with_bytes creates an instruction to invoke the program. It includes the program ID, instruction data, and instruction accounts.svm.latest_blockhashEvery Solana transaction needs a recent blockhash. In this test, LiteSVM provides a blockhash to use for the transaction.Message::new_with_blockhashThe message contains the instruction, fee payer, and blockhash. This is the transaction data that will be signed.VersionedTransaction::try_newVersionedTransaction::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_transactionsvm.send_transaction executes the transaction in LiteSVM.svm.get_accountAfter the transaction runs, the test reads the counter account directly from LiteSVM so it can inspect the account data.Counter::try_deserializeThe 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.

​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 and the Anchor CLI.
Anchor.toml
skip_local_validatorskip_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.