Session 03
Anchor · Solana

Solana Smart Contracts
WITH ANCHOR

Two-branch walkthrough for building, testing, and deploying a Solana program with Anchor. Focused on programs, accounts, and safe iteration—not on wallet UI complexity.

01

Repository & Branch Map

main branch

First stable edit of the Anchor template: simple counter program, initialize + increment, no frontend coupling. Perfect for absolute beginners.

git checkout main
final branch

Polished version with refined lib.rs, testp.ts, and the extra app.html. Pull the full branch—files differ from main.

git checkout final && git pull
02

Prerequisites & Checks

Toolchain
  • Rust
  • Solana CLI
  • Anchor CLI
JS Stack
  • Node.js 18+
  • npm
Environment
  • Linux / WSL preferred
  • Consistent PATH
rustc --version
solana --version
anchor --version
node --version
npm --version
03

Solana CLI Wallet & Network

Wallet

Create or reuse CLI wallet for fees, deploys, and tests.

solana-keygen new
solana address

Default path: ~/.config/solana/id.json

Localnet

Anchor manages the local validator. Configure once:

solana config set --url http://127.0.0.1:8899
solana config get
04

Project Setup

Initialize
anchor init trial
cd trial

Generates Anchor.toml, programs/, tests/, package.json scaffolding.

Files of interest
  • programs/trial/src/lib.rs (program)
  • tests/testp.ts (client tests)
  • Anchor.toml (program IDs, provider)
05

Program Versions

Version 1 — main
  • Counter account
  • initialize + increment
  • Great for first exposure
Version 2 — final
  • Refined lib.rs + testp.ts
  • Multiple increments, cleaner flow
  • Includes app.html for context
06

Program ID Discipline

Critical

After every deploy, update both:

  • declare_id!("NEW_PROGRAM_ID") in lib.rs
  • Anchor.toml [programs.localnet].trial

Missing this causes DeclaredProgramIdMismatch.

07

Run & Test

Clean state

Reset ledger and stray validators before tests:

pkill solana-test-validator
rm -rf .anchor/test-ledger
Anchor test
anchor test

Expect: Counter init to 0, then increments to 2, all tests passing.

08

Deploy (optional)

anchor deploy

After deployment, copy the new Program ID, update declare_id! and Anchor.toml, then rerun tests if needed.

09

Common Issues

Account already exists

Use a fresh keypair; clear .anchor/test-ledger.

Blockhash expired

Avoid --skip-local-validator; let anchor manage it.

Program ID mismatch

Update declare_id! and Anchor.toml after deploy.

10

Learning Outcomes

You will be able to
  • Explain Solana programs vs. accounts and why programs are stateless.
  • Use Anchor to scaffold, write, and test on-chain logic safely.
  • Manage Program IDs, deployments, and local validators confidently.
  • Describe how a frontend could interact without diving into wallet UX yet.