Solana Anchor Tutorial: Deploy Your First On-Chain Program Step by Step

10 min read

Solana Anchor Tutorial — A metallic ship anchor rests on a glowing purple and teal circuit board, surrounded by floating holographic code in a dark, cinematic setting.
  • Anchor is the most popular framework for writing Solana programs — it handles the repetitive setup so you can focus on building.
  • You can follow this solana anchor tutorial with a full local install or entirely inside your browser using Solana Playground — no Rust install required to start.
  • A simple counter program (initialize + increment) is the best first project — it teaches accounts, instructions, and testing without overcomplicating things.
  • Anchor generates an IDL file automatically, which acts as a bridge between your on-chain program and any TypeScript frontend or test suite.
  • Deploying to devnet first is free — you airdrop test SOL, confirm everything works, then move to mainnet when you’re ready.
  • Miners already understand hardware, uptime, and reward structures — those instincts translate well to thinking about on-chain compute costs and program efficiency.

Anchor is an open-source framework that makes writing Solana smart contracts dramatically easier by eliminating boilerplate code, handling account validation automatically, and generating a TypeScript client from your program. If you follow this solana anchor tutorial from start to finish, you’ll have a working counter program deployed to Solana’s devnet in under a couple of hours — even if you’ve never written a line of Rust in your life.

What Is Anchor and Why Should Miners Care About It?

Solana calls its smart contracts programs. Before Anchor existed, writing one of these programs meant dealing with a lot of raw, low-level Rust code. Developers had to manually serialize data, validate every account, and wire up instruction handlers by hand. It was slow, error-prone, and a real barrier for anyone new to on-chain development.

Anchor changed that. It wraps all the painful boilerplate inside Rust macros and a clean framework structure, letting you focus on what your program actually does instead of how Solana handles memory. The Anchor GitHub repo now shows over 5,000 stars and nearly 2,000 forks — a strong signal that the whole Solana community has converged on it as the default way to build.

The Problem Anchor Solves for New Developers

When you write a native Solana program without Anchor, every instruction handler requires you to manually unpack accounts, check signers, verify ownership, and handle deserialization. Mess up any one of those checks and you’ve got a security vulnerability. Anchor automates all of that through its #[derive(Accounts)] macro, which validates every account constraint at runtime before your instruction logic ever runs. This makes programs both faster to write and harder to exploit.

Armani Ferrante, the developer who created Anchor, put it plainly: “My thinking behind Anchor was really how do we 10x the number of developers on the network. And let’s do that as fast as possible.” That mission worked. By 2024, Solana attracted more new developers than any other blockchain — a growth rate of 83% year over year — and Anchor was at the center of that expansion.

Why Miners Are Well-Positioned to Learn This

If you’ve been running Chia, Ethereum, or any Proof-of-Work mining operation, you already think in terms of hardware efficiency, throughput, and cost per unit of output. Those instincts map well to on-chain development. Solana programs consume compute units the way a miner consumes electricity. Optimizing a program’s compute usage is the same mental discipline as squeezing more plots per watt out of a farming rig. You’re already trained to think this way — you just need to apply it to code.

Anchor is the de facto standard for Solana smart contract development in 2025. Every serious on-chain program — from DEXs to DAOs — is built with it.

Setting Up Your Solana Anchor Tutorial Environment

Before you write a single line of program code, you need to pick a development path. There are two options: a full local install, or a browser-based environment. Both work for this tutorial. The local install gives you more control and is better for long-term development. The browser option lets you skip the setup entirely and start coding in five minutes.

Option A: Local Install (Rust + Solana CLI + Anchor AVM)

The local path requires three tools installed in order. First, install Rust using the official rustup installer at rustup.rs. Rust is the language Anchor programs are written in. Next, install the Solana CLI — this lets you create wallets, check balances, and interact with the blockchain from your terminal. The official one-command installer is found at docs.solanalabs.com.

Finally, install the Anchor Version Manager (AVM), which manages Anchor versions the same way nvm manages Node.js. Run cargo install --git //github.com/coral-xyz/avm avm --locked --force, then avm install latest and avm use latest. Once all three are in place, run anchor --version to confirm everything installed correctly.

Option B: Solana Playground (Zero Install Required)

If you want to skip the local setup entirely, head to beta.solpg.io. Solana Playground is a browser-based IDE that lets you write, build, test, and deploy Anchor programs without installing anything on your machine. It’s the fastest way to run through this solana anchor tutorial for the first time. The trade-off is that it’s less suitable for large projects with multiple files or complex CI pipelines, but for a counter program it’s perfect.

Setup PathBest ForRust Required Locally?Devnet Deploy?Time to Start
Local (Rust + Solana CLI + AVM)Serious long-term development, CI/CD pipelines, team projectsYesYes~30–60 minutes
Solana Playground (browser)First-time learners, quick experiments, hackathonsNoYes~5 minutes
Solana Playground + local tests laterMiners who want to learn fast, then build properlyNo (to start)Yes~5 minutes

Your First Anchor Program: Building the Counter

The classic first Anchor project is a counter — a program that stores a number on-chain and lets you increment it. It sounds simple, but it covers every core concept you’ll use in any real program: creating accounts, defining instructions, validating signers, and persisting state. Once you understand the counter pattern, you can extend it to anything — staking contracts, escrow programs, token vaults.

Step 1 — Scaffold the Workspace

Open your terminal (or Solana Playground) and run:

anchor init my_counter
cd my_counter

This single command creates a full project structure. The important folders are programs/my_counter/src/ where your Rust code lives, and tests/ where your TypeScript tests go. There’s also an Anchor.toml config file at the root that controls which cluster you’re targeting (localnet, devnet, or mainnet). Don’t touch this file yet — we’ll update it when we deploy.

Step 2 — Write the Program Logic in lib.rs

Open programs/my_counter/src/lib.rs and replace the boilerplate with this counter program:

use anchor_lang::prelude::*;

declare_id!("YOUR_PROGRAM_ID");

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

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.counter.count = 0;
        Ok(())
    }

    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        ctx.accounts.counter.count += 1;
        Ok(())
    }
}

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

#[derive(Accounts)]
pub struct Increment<'info> {
    #[account(mut)]
    pub counter: Account<'info, Counter>,
}

#[account]
pub struct Counter {
    pub count: u64,
}

Let’s break down what’s happening. The declare_id! macro sets the unique on-chain address for your program. The #[program] block holds your two instructions: initialize sets the counter to zero and increment adds one. The #[derive(Accounts)] structs define which accounts each instruction needs — Anchor validates all of them automatically before your code runs. The space = 8 + 8 in Initialize tells Solana to allocate 8 bytes for the Anchor discriminator plus 8 bytes for the u64 count.

Step 3 — Build and Sync Keys

Run anchor build to compile your program into a BPF (Berkeley Packet Filter) binary that Solana can execute. After the build completes, run anchor keys sync — this is a step many tutorials skip, but it’s important. It reads the keypair that was generated during the build and updates the declare_id! value in your lib.rs to match, preventing a mismatch error when you deploy. Build one more time after syncing to lock in the correct program ID.

Testing and Deploying Your Anchor Program to Devnet

Writing a program is only half the job. The other half is making sure it actually works before you put it on mainnet. Anchor comes with a built-in testing setup that spins up a local Solana validator, deploys your program to it, and runs your TypeScript tests — all in a single command. This is one of the most useful parts of the entire Anchor workflow.

Running anchor test Locally

Inside your tests/ folder you’ll find a TypeScript file pre-generated by Anchor. Replace its contents with this test to call both instructions and check the result:

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { MyCounter } from "../target/types/my_counter";
import { assert } from "chai";

describe("my_counter", () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  const program = anchor.workspace.MyCounter as Program<MyCounter>;

  it("Initializes and increments", async () => {
    const counter = anchor.web3.Keypair.generate();

    await program.methods
      .initialize()
      .accounts({ counter: counter.publicKey, user: provider.wallet.publicKey })
      .signers([counter])
      .rpc();

    await program.methods
      .increment()
      .accounts({ counter: counter.publicKey })
      .rpc();

    const account = await program.account.counter.fetch(counter.publicKey);
    assert.equal(account.count.toNumber(), 1);
  });
});

Run anchor test. Anchor will start a local validator, deploy your program, execute the test, and report the result. If you see a green checkmark, your program logic is confirmed working. This is your safety net — always run tests before deploying anywhere.

Deploying to Solana Devnet

Devnet is Solana’s free testing network. Nothing on it has real value, but it behaves exactly like mainnet. To deploy there, first switch your Solana CLI config: solana config set --url devnet. Then open Anchor.toml and set cluster = "devnet" under the [provider] section. You’ll need some test SOL — get a free airdrop by running solana airdrop 2. Confirm your balance with solana balance. Then run anchor deploy. When it completes, Anchor prints your program ID. Copy it and save it — that’s your program’s permanent address on devnet.

Every Solana program deployed on-chain has a unique public key (program ID) — treat it like a miner treats a wallet address. It’s how everyone else finds and calls your program.

Key Anchor Concepts Every New Developer Needs to Understand

Writing your first counter is a great start, but you’ll hit a wall quickly if you don’t understand the concepts underneath. Two of the most important ones for any solana anchor tutorial are the account model and the IDL. These aren’t unique to Anchor — they’re core to how Solana itself works — but Anchor makes them much easier to use.

Accounts, Instructions, and Program Derived Addresses (PDAs)

Solana programs are stateless by design. Unlike Ethereum, where a smart contract can store its own variables, Solana programs cannot store data inside themselves. All data lives in separate account objects. Your counter program stored the count inside a Counter account that lives at a keypair address. As you build more complex programs, you’ll use Program Derived Addresses (PDAs) — special accounts whose address is computed from your program ID and a seed string, rather than a random keypair. PDAs are what make programs like escrows, vaults, and marketplaces work, because the program itself controls those accounts without needing a private key.

The IDL: Your Program’s Public Interface

When you run anchor build, Anchor generates an Interface Description Language (IDL) file in your target/idl/ folder. This JSON file describes every instruction your program has, what accounts each one needs, and what data types it uses. Think of it as your program’s API documentation — except it’s also machine-readable. The Anchor TypeScript client reads this IDL to generate a typed SDK automatically, which is how your test file was able to call program.methods.initialize() without you writing any serialization code. When you’re ready to build a frontend, you’ll pass this same IDL to Anchor’s JavaScript library and get a fully-typed client for free.

FeatureNative Rust (No Anchor)Anchor Framework
Account validationManual — developer writes every checkAutomatic via #[derive(Accounts)] macros
Data serializationManual Borsh encode/decodeAuto-handled by Anchor
TypeScript clientMust write from scratchGenerated from IDL automatically
Error handlingCustom error codes and mappingBuilt-in error macro #[error_code]
Testing setupManual validator + script wiringanchor test handles everything
Code volumeHigh — lots of boilerplateLow — macros eliminate repetition
Learning curveSteep — requires deep Solana internals knowledgeModerate — Rust basics + Anchor patterns

From Miner to Builder: What to Do After This Solana Anchor Tutorial

Completing a counter program is a real milestone — you’ve written Rust, defined on-chain accounts, tested locally, and pushed code to a live blockchain network. But it’s the first step on a longer path. The natural next project after a counter is an escrow program, which teaches you how to hold tokens on behalf of two parties and release them when conditions are met. From there, programs like SPL token mints, staking contracts, and simple DEX vaults all use the same building blocks you just learned.

If you want to go deeper on smart contract languages across different blockchains, Chialisp — Chia Network’s on-chain programming language — takes a very different approach to security and composability. It’s worth understanding how multiple ecosystems solve the same problems. You can explore how Chialisp works in our guide: Chialisp: Transforming Blockchain and Unlocking Next-Gen Smart Contracts.

Case study: Orca, one of Solana’s largest decentralized exchanges, uses Anchor throughout its on-chain program architecture. Its concentrated liquidity pools process hundreds of millions in daily volume — all validated by the same account constraint system you used in this tutorial’s counter program.

The single biggest mistake new Solana developers make is skipping the test suite. Running anchor test before every deploy catches most bugs before they reach a live network where fixing them costs SOL and time.

Conclusion

This solana anchor tutorial walked you through the full lifecycle of a Solana program — from picking a dev environment to writing a counter in Rust, running a TypeScript test suite, and deploying to devnet. Anchor handles the hard parts of Solana development automatically, so you can focus on the logic that makes your program useful rather than fighting with account serialization and validation boilerplate. Miners already think in systems — hardware, throughput, cost, uptime. That same thinking maps directly to writing efficient on-chain programs. Your next step is to build something slightly harder: an escrow, a simple vault, or an SPL token program. Each one builds on exactly what you learned here. Head to the official Anchor documentation or the Solana developer course and keep building.

Solana Anchor Tutorial FAQs

What is a solana anchor tutorial and what will I learn from it?

A solana anchor tutorial teaches you how to use the Anchor framework to write, test, and deploy smart contract programs on the Solana blockchain. By the end of a typical tutorial, you’ll understand Anchor’s account model, instruction structure, and IDL — and you’ll have a working program running on Solana’s devnet.

Do I need to know Rust to follow a solana anchor tutorial?

Basic Rust familiarity helps, but it isn’t required to complete a first solana anchor tutorial. Using Solana Playground lets you start building without any local Rust installation, and Anchor’s macros hide much of Rust’s lower-level complexity until you’re ready to dig deeper.

What is the difference between a Solana program and a smart contract?

Solana calls its smart contracts “programs” — they’re the same concept but use Solana’s own runtime model called Sealevel, which processes transactions in parallel rather than sequentially. Anchor makes writing these programs easier by abstracting account validation and data serialization.

What is an IDL in Anchor and why does it matter?

An IDL (Interface Description Language) is a JSON file Anchor generates automatically when you build your program. It describes every instruction and account type your program uses, and Anchor’s TypeScript client reads it to create a typed SDK — saving you from writing any frontend integration code by hand.

How much does it cost to deploy an Anchor program to Solana devnet?

Deploying to Solana’s devnet is completely free — you use test SOL obtained via the solana airdrop command, which has no real-world value. The cost to deploy a small program to mainnet-beta is typically a few hundredths of a SOL, depending on program size.

Solana Anchor Tutorial Citations

  1. Anchor Framework Official Documentation — https://www.anchor-lang.com/docs
  2. Solana Foundation — Intro to Anchor Course — https://solana.com/developers/courses/onchain-development/intro-to-anchor
  3. Helius — A Beginner’s Guide to Building Solana Programs with Anchor — https://www.helius.dev/blog/an-introduction-to-anchor-a-beginners-guide-to-building-solana-programs
  4. QuickNode — Write Your First Anchor Program — https://www.quicknode.com/guides/solana-development/anchor/how-to-write-your-first-anchor-program-in-solana-part-1
  5. GitHub — solana-foundation/anchor — https://github.com/solana-foundation/anchor
  6. Solana Compass — Armani Ferrante on Anchor and the Solana Ecosystem — https://solanacompass.com/learn/Validated/validated-from-anchor-to-mad-lads-and-beyond-with-armani-ferrante
  7. Electric Capital — 2024 Developer Report (via 24/7 Wall St.) — https:/뢏wallst.com/investing/2025/11/18/solana-developer-growth-hits-record-highs-why-it-matters/
  8. Solana Playground — Browser-Based IDE — https://beta.solpg.io
  9. Solana CLI Installation Docs — https://docs.solanalabs.com/cli/install
  10. Superteam — Deep Dive: State of Developer Tooling on Solana 2025 — https://blog.superteam.fun/p/deep-dive-of-the-state-of-developer