Anchor is a Rust framework and development workflow for building Solana programs with account validation, IDL generation, client libraries, testing tools, and CLI support. The official Anchor docs are best used as a progression: install the toolchain, create a workspace, understand accounts and instructions, test locally, then deploy to a selected Solana cluster. This guide explains that progression and shows how to verify both your local program and the RPC connection it uses. It does not prescribe a single endpoint or claim performance results; measure the provider and network configuration you choose.
Anchor documentation scope
The Anchor documentation covers the framework for building Solana programs, sometimes called smart contracts. It brings together the Anchor CLI, Rust crates, program structure, account constraints, IDL generation, client libraries, testing options, deployment configuration, and security guidance.
A useful mental model is to treat Anchor as a layer above Solana's lower-level program APIs. Your program still executes in Solana's Sealevel runtime and still operates on accounts, instructions, program-derived addresses, and cross-program invocations. Anchor reduces repetitive code by deriving account validation, serialisation, error handling, and client-facing metadata from your Rust definitions.
The docs are not a replacement for the Solana developer documentation. Use Solana documentation for runtime rules, transactions, fees, account ownership, cluster behaviour, and protocol-level concepts. Use Anchor docs for the framework conventions that make those concepts easier to implement.
- Start with Installation and Quickstart when setting up a new machine.
- Read Program Structure, Account Types, and Account Constraints before writing production instructions.
- Use IDL, Client Libraries, Testing, and Verifiable Builds when moving beyond a local prototype.
Toolchain prerequisites
Anchor development requires a compatible Rust toolchain, Solana command-line tools, Node.js package tooling for many client workflows, and the Anchor CLI. Exact version compatibility can change, so check the versions stated in the current Anchor installation documentation rather than copying an old version from a blog post.
You also need a Solana keypair for signing local transactions and, for a remote cluster, an RPC URL and sufficient funds for deployment or test transactions. Keep signing material separate from application configuration. A public RPC URL may be stored in a local configuration file, but a private key should never be committed to a repository or placed in frontend code.
For a managed endpoint, review OnFinality RPC services and RPC pricing for the available service model. Select the network and endpoint according to your workload and environment; this guide intentionally does not claim that one endpoint is fastest or most reliable without a measurement run.
- Confirm Rust, Solana CLI, Node.js, and Anchor versions before troubleshooting application code.
- Use a disposable keypair and a test cluster for early experiments.
- Store RPC_URL and signing configuration in environment variables or a secret manager.
solana --version
rustc --version
node --version
anchor --version
solana config get
solana addressWorkspace and program structure
An Anchor workspace normally separates the on-chain program from client code, tests, deployment artifacts, and workspace configuration. The exact generated layout depends on the Anchor version and template, but the important boundaries remain stable: Rust source defines the program, tests exercise its instructions, the IDL describes its public interface, and configuration selects the provider and deployment target.
Create a project with the Anchor CLI, inspect the generated files, and read them before changing the example. The generated program usually includes an instruction module and an accounts context. The context states which accounts the instruction expects and which constraints Anchor should validate. The instruction handler then contains the program's business logic.
A program ID is part of the deployment identity. Keep the declared ID, keypair, workspace configuration, and deployed address consistent. A mismatch can produce confusing deployment or transaction errors even when the Rust code compiles.
- Treat the generated test as an executable specification of the initial workflow.
- Review Anchor.toml before switching from a local validator to a remote cluster.
- Do not assume that a successful build means the program has been deployed.
anchor init counter_app
cd counter_app
anchor build
anchor testAccounts instructions and IDL
Solana programs receive accounts and instruction data explicitly. Anchor expresses the expected accounts with a Rust context structure, often using attributes such as initialization, mutability, signer requirements, ownership checks, seeds, and bump values. These constraints are executable validation rules, not merely documentation.
The instruction handler receives the validated context and any serialised arguments. This separation is central to reviewing an Anchor program: first inspect who can supply or change each account, then inspect what the handler does with the validated inputs. A missing signer, owner, relationship, or seed constraint can become an authorization or account-confusion vulnerability.
Anchor can generate an IDL describing instructions, arguments, accounts, types, and errors. Client libraries use that interface to construct calls and decode responses. Treat the IDL as a generated artifact tied to a specific build; regenerate and review it when public instruction interfaces change.
Program-derived addresses deserve special attention. A PDA is derived from seeds, a program ID, and a bump, but it has no private key. The program must validate the seeds and expected relationship before using it as authority or storage. The Anchor docs' PDA and account-constraint sections should be read alongside the Sealevel attacks guidance before production deployment.
use anchor_lang::prelude::*;
declare_id!("PROGRAM_ID");
#[program]
pub mod counter_app {
use super::*;
pub fn increment(ctx: Context<Increment>) -> Result<()> {
ctx.accounts.counter.value = ctx.accounts.counter.value.checked_add(1).ok_or(ErrorCode::Overflow)?;
Ok(())
}
}
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(mut)]
pub counter: Account<'info, Counter>,
}
#[account]
pub struct Counter {
pub value: u64,
}
#[error_code]
pub enum ErrorCode {
#[msg("Counter value overflowed")]
Overflow,
}Local testing and client execution
Anchor testing can start a local validator, build the program, deploy it to the test environment, and run the workspace tests. This gives you a deterministic place to check account creation, instruction arguments, expected errors, and state changes before involving a public cluster.
Tests should verify more than a transaction signature. Fetch the resulting account, assert the state transition, inspect expected failures, and confirm that unauthorized signers cannot perform privileged actions. For instructions involving multiple accounts, include cases with incorrect owners, wrong PDAs, missing signers, and accounts from an unrelated program.
A JavaScript or TypeScript client commonly loads the generated IDL and program address, creates a provider, derives accounts, sends an instruction, and fetches state. The following minimal pattern uses an environment-provided RPC URL and keypair path. Adapt the imports and API calls to the Anchor client version used by your project.
import fs from "node:fs";
import anchor from "@coral-xyz/anchor";
import { Keypair, PublicKey } from "@solana/web3.js";
const rpcUrl = process.env.RPC_URL;
const keypairPath = process.env.KEYPAIR_PATH;
if (!rpcUrl || !keypairPath) throw new Error("Set RPC_URL and KEYPAIR_PATH");
const walletKeypair = Keypair.fromSecretKey(
Uint8Array.from(JSON.parse(fs.readFileSync(keypairPath, "utf8")))
);
const connection = new anchor.web3.Connection(rpcUrl, "confirmed");
const wallet = new anchor.Wallet(walletKeypair);
const provider = new anchor.AnchorProvider(connection, wallet, { commitment: "confirmed" });
anchor.setProvider(provider);
const programId = new PublicKey(process.env.PROGRAM_ID);
console.log("provider:", provider.connection.rpcEndpoint);
console.log("wallet:", wallet.publicKey.toBase58());
console.log("program:", programId.toBase58());
console.log("slot:", await connection.getSlot("confirmed"));RPC endpoint verification
Anchor depends on an RPC endpoint for reads, transaction submission, blockhash retrieval, simulation, confirmations, and account queries. A healthy endpoint is necessary but not sufficient for a successful deployment: the selected cluster, commitment level, program ID, wallet balance, and transaction status must also agree.
Before running a client, test the endpoint independently. JSON-RPC methods and response timing can vary by provider and network conditions, so record the method, commitment, timestamp, response status, and error body. Do not confuse an HTTP 200 response with a successful JSON-RPC result; inspect the result and error fields.
Use this request with a placeholder endpoint. It tests a basic health method and a slot query without exposing a private key.
- A healthy response should contain a JSON-RPC result rather than an error object.
- A slot result should be numeric; compare repeated samples only after fixing the commitment level.
- Use Solana network information to confirm that your endpoint and wallet target the intended cluster.
curl -sS -X POST "$RPC_URL" \
-H 'Content-Type: application/json' \
--data '{"jsonrpc":"2.0","id":1,"method":"getHealth"}'
echo
curl -sS -X POST "$RPC_URL" \
-H 'Content-Type: application/json' \
--data '{"jsonrpc":"2.0","id":2,"method":"getSlot","params":[{"commitment":"confirmed"}]}'Deployment and verification workflow
Deploy only after the local test suite passes and the program ID is fixed. Configure the intended cluster and RPC URL explicitly, build the program, deploy it, and save the deployment output. Then verify the program account and run a real instruction using the same cluster configuration.
Deployment verification should include both on-chain identity and application behaviour. Check that the deployed address matches the declared program ID, that the program account exists on the intended cluster, and that a test transaction reaches the expected confirmation state. If your application depends on an IDL, ensure the client is using the IDL generated from the same source revision as the deployed binary.
For workloads that need predictable isolation, compare shared RPC access with dedicated node options. That is an architectural choice, not a guaranteed performance improvement; validate it against your traffic pattern.
- Record the program ID, cluster, build revision, IDL revision, and deployment transaction signature.
- Fund the deployment wallet through the appropriate network process before deployment.
- Never use a production authority keypair in an ad hoc shell session without an approved key-management process.
export RPC_URL="RPC_URL"
solana config set --url "$RPC_URL"
solana config get
anchor build
anchor deploy --provider.cluster "$RPC_URL"
solana program show PROGRAM_ID --url "$RPC_URL"
anchor test --skip-local-validator --provider.cluster "$RPC_URL"Measurement and results procedure
When choosing an endpoint for Anchor development or production traffic, measure the operations your application actually performs instead of relying on a generic latency claim. Include cold and warm requests, reads and writes, simulation, blockhash retrieval, and confirmation where relevant. Run the same test from the same region, use the same commitment, and distinguish provider response time from transaction inclusion time.
Capture enough samples to reveal timeouts and outliers. A simple results table can be filled from your own run: | Test | Commitment | Samples | Median | p95 | Errors/timeouts | Notes |; | getHealth | fixed value | record | record | record | record | record |; | getSlot | confirmed | record | record | record | record | record |; | account read | confirmed | record | record | record | record | record |; | send and confirm transaction | confirmed | record | record | record | record | record |. Do not publish empty cells as performance results.
Interpret results in context. A faster read does not necessarily mean faster transaction finality, and a low error rate during an idle test may not represent behaviour under concurrency. Repeat the test during expected traffic, document rate limits and retries, and compare like-for-like endpoint plans.
- Use a monotonic local timer and log HTTP status, JSON-RPC error, and elapsed milliseconds.
- Keep payload size, commitment, encoding, and retry policy constant between candidates.
- Report test date, client version, network, region, sample count, and exclusion rules with any result.
Common failure modes
Version mismatches are a frequent first cause of failure. An incompatible Rust dependency, Solana CLI, Anchor CLI, generated IDL, or client package can produce compile errors or runtime decoding failures. Compare the versions in the project configuration with the current compatibility guidance before changing application logic.
A program ID mismatch often appears during deployment or client calls. Check the declaration in Rust, the keypair used for deployment, workspace configuration, client configuration, and the address queried on-chain. A program deployed to one cluster is not automatically present on another.
Account constraint errors mean Anchor rejected the supplied account set before the handler ran. Read the full error, identify the failing constraint, and inspect the account's owner, signer status, mutability, address, seeds, and discriminator. Do not bypass a constraint simply to make a test pass.
RPC errors require a separate diagnosis. Check the endpoint URL, network, authentication, rate limits, request body, commitment, and retry behaviour. If reads succeed but writes fail, inspect wallet balance, blockhash expiry, simulation logs, transaction size, and confirmation handling. If the endpoint is unavailable, test a known-good endpoint or the network's public development endpoint to isolate application errors from infrastructure errors.
- Build failure: verify toolchain and dependency compatibility.
- Simulation failure: inspect program logs and account constraints.
- Confirmation timeout: check blockhash age, transaction status, commitment, and endpoint consistency.
- Unexpected state: verify the program ID, cluster, account address, and IDL revision.
Security limitations and design tradeoffs
Anchor's generated validation is valuable, but it does not make a program secure automatically. Developers still choose which accounts are mutable, which authorities are trusted, how seeds are constructed, whether arithmetic can overflow, and whether a cross-program invocation is safe. Review the generated constraints and the handler together.
Convenience can also conceal runtime cost or compatibility assumptions. Zero-copy accounts, event emission, account resizing, custom serialization, and cross-program invocations each introduce tradeoffs in compute usage, account space, client decoding, and upgrade procedures. Use the relevant Anchor reference section rather than applying a pattern without checking its constraints.
Local tests do not reproduce every production condition. Public clusters may have congestion, different feature activation, rate limits, forks, delayed indexing, and provider-specific retry behaviour. Maintain an explicit operational plan for key security, upgrades, monitoring, rollback, and endpoint failover.
- Use least-privilege authorities and separate development, staging, and production keys.
- Add negative tests for every authorization and account relationship.
- Review upgrade authority and deployment permissions before publishing a production program.
Next steps for production development
After the quickstart works, move through the Anchor docs in a deliberate order: account types and constraints, program-derived addresses, cross-program invocation, custom errors, events, testing libraries, verifiable builds, and security examples. Each topic should lead to a test or review rule in your own repository.
Connect your client to the selected Solana network only after recording the endpoint, commitment, retry, and confirmation policy. For a broader infrastructure comparison, see the best Solana RPC provider guide and the Solana devnet guide. These resources can help frame endpoint selection, while your own workload measurements should determine the final choice.
Finally, document a reproducible release path: pinned toolchain, clean build, generated IDL review, test results, program ID, deployment authority, transaction signature, endpoint configuration, and post-deployment verification. That record turns Anchor from a local framework into an auditable development and operations workflow.
- Keep source, IDL, binary, and deployment metadata traceable to one revision.
- Automate build and test checks before deployment approval.
- Monitor transaction errors, confirmation delays, RPC failures, and program logs after release.