Building with Anchor
A comprehensive developer's guide to the Solana smart contract framework
Learn how to use Anchor, Solana's leading development framework, to build secure, efficient, and maintainable smart contracts for the high-performance Solana blockchain.
In This Guide
What is Anchor?
A framework for efficient Solana program development
Framework Overview
Anchor is a development framework for building secure Solana programs (smart contracts). It streamlines the development process by eliminating boilerplate code, standardizing program architecture, and providing developer-friendly abstractions. Anchor isn't a blockchain itself, but a toolset designed to make Solana development more productive, secure, and maintainable while reducing the typical sources of vulnerabilities.
Why Use Anchor?
Developers choose Anchor to boost productivity with Rust macros that automate account validation, instruction encoding/decoding, error handling, and testing. Anchor reduces Solana program code by up to 80% compared to raw implementation, standardizes security practices, simplifies state management, and provides automatic client generation for multiple programming languages. It has become the de-facto standard for Solana program development.
Core Components
Anchor comprises several components: 1) Rust macros for code generation, 2) Command-line interface (anchor CLI) for project management, 3) TypeScript client library for frontend integration, 4) Testing framework for program validation, 5) IDL (Interface Definition Language) system for cross-language compatibility. Together, these components create a more developer-friendly experience while maintaining Solana's performance advantages.
Integration with Solana
Anchor seamlessly integrates with the Solana ecosystem while providing higher-level abstractions. It compiles down to standard Solana programs with no runtime overhead, works with all Solana tools and wallets, and can interact with any Solana program (Anchor or non-Anchor). This allows developers to leverage Solana's performance while benefiting from improved development ergonomics and standardized patterns.
Understanding Anchor's Architecture
The technical components that make up the Anchor framework
Anchor Project Structure
Key components and organization of Anchor projects
Project Setup
Anchor projects are initialized with the 'anchor init' command, which creates a standardized directory structure. The project includes a cargo.toml file with Anchor dependencies, an Anchor.toml configuration file with project settings and deployment parameters, and a set of directories for programs, tests, and application code. This consistent structure enables developers to quickly navigate any Anchor project.
Programs Directory
The 'programs/' directory contains all on-chain Solana program code written in Rust. Each program has its own subdirectory with a lib.rs file containing the program module, instruction handlers, account structures, and error definitions. Additional modules can be organized in separate files. Anchor automatically sets up the proper entrypoint, serialization/deserialization, and dispatch logic for all programs in this directory.
Tests Directory
The 'tests/' directory houses TypeScript/JavaScript tests that verify program functionality. These tests use the Anchor testing framework to deploy programs to a local validator, send transactions, and verify state changes. Test files typically follow a structure of describing features and asserting expected behavior. The testing environment automatically manages validator startup, program deployment, and account creation.
Application Code
The 'app/' directory is intended for frontend application code that interacts with deployed Anchor programs. This is where you would build your web interface using JavaScript/TypeScript frameworks like React, Vue, or Svelte. Client integration is simplified through Anchor-generated TypeScript types derived from your program's interface definition language (IDL) file.
Anchor.toml Configuration
The Anchor.toml file is the central configuration for the project. It defines program IDs, provider settings (like cluster URLs and wallet paths), test configurations, and deployment parameters. The file uses TOML format with clearly documented sections for different aspects of the project. This configuration controls how the anchor CLI interacts with your project when building, testing, and deploying.
Migrations Directory
The 'migrations/' directory contains deployment scripts for initializing program state after deployment. These scripts, written in JavaScript/TypeScript, run during 'anchor migrate' and can create initial accounts, set up program configurations, and establish starting state. Migrations enable reproducible deployments across different environments from development to production.
Target Directory
After building, Anchor generates compiled program binaries, IDL files, and other artifacts in the 'target/' directory. The 'target/deploy/' folder contains the BPF executable .so files ready for deployment to Solana, along with keypairs for program addresses and JSON IDL files describing the program interface. These artifacts are used during deployment and client generation.
Client Generation
Anchor can automatically generate type-safe client libraries for your programs. Running 'anchor client-gen' creates TypeScript interfaces derived from your program's IDL, providing method builders, account fetchers, and event parsers. These clients ensure type safety between your frontend and on-chain code, catching integration errors at compile time rather than runtime.
Workspaces
Anchor supports multi-program workspaces where multiple related programs can be developed together. Each program maintains its own code in the programs/ directory but shares testing and deployment configuration. This approach is ideal for complex protocols where multiple programs need to interact, enabling integrated testing and coordinated deployment.
Project Examples
Anchor provides a variety of example projects demonstrating best practices for different use cases. These include basic program structures, token handling examples, cross-program invocation patterns, and complex protocol implementations. Exploring these examples is an excellent way to understand how to structure different types of Anchor applications effectively.
Program Development with Anchor
Building efficient and secure Solana programs using Anchor
The Anchor Development Framework
Technical components of the development framework powering Solana programs
Program Architecture
Anchor programs follow a modular architecture with clear separation of concerns. The core entrypoint is defined by the #[program] macro, which generates the Solana program interface and dispatches instructions to appropriate handlers. Program state is managed through typed Account structures, ensuring memory safety and preventing data corruption. Instructions use Context structs to validate and access accounts. This architecture reduces common attack vectors by enforcing systematic validation and standardized execution flows.
Account System
Anchor's account system abstracts Solana's raw account model through typed structures and validation. The #[account] macro creates account types with automatic 8-byte discriminators that prevent account type confusion. Account constraints declared through #[derive(Accounts)] enforce security invariants such as ownership checks, signature requirements, and address derivation. Advanced patterns include zero-copy accounts for high-performance handling of large data structures, and account reallocation for dynamically resizing accounts as needed.
Instruction Processing
Anchor's instruction handler system automates serialization and validation workflows. Function arguments are automatically serialized/deserialized using Borsh encoding, with type checking to prevent data corruption. The Context<T> pattern provides compile-time verification of account validation logic. Error handling uses the #[error_code] macro to define structured errors with descriptive messages, enabling clearer client feedback. Instruction handlers support concurrent processing through Solana's parallel execution engine.
Program Derived Addresses
Anchor simplifies Solana's Program Derived Address (PDA) system with declarative seeds and bump finding. The seeds and bump constraint automatically derives and validates PDAs, ensuring accounts are owned by the correct program. PDAs enable programs to sign for operations without private keys, using find_program_address and seeds for deterministic derivation. This pattern powers capability-based security models where address derivation encodes permissions, and enables cross-program authority delegation.
Cross-Program Invocation
Anchor enables type-safe cross-program invocation (CPI) through its CpiContext abstraction. Programs can securely call other Solana programs with validated accounts and proper signatures. For Anchor-to-Anchor calls, the cpi feature generates client wrappers matching the target program's API signature. Accounts are passed through accurately with remaining_accounts support for dynamic account lists. The system handles signature propagation for PDA-based authorities, enabling complex multi-program transactions while maintaining security invariants.
Event System
Anchor's event system provides structured logging through the #[event] macro and emit! function. Events define structured data that's serialized and included in transaction logs, enabling rich off-chain indexing and notifications. Each event contains typed fields with proper serialization, allowing clients to parse event data reliably. This system enables efficient data indexing without requiring on-chain storage, supports client subscriptions for real-time updates, and maintains an audit trail of program actions separate from state changes.
Interface Definition Language
Anchor's IDL (Interface Definition Language) system automatically generates JSON descriptions of program interfaces. The IDL contains all instructions, accounts, types, errors, and events defined in the program, enabling type-safe client generation. The anchor build process extracts this IDL directly from the Rust code, ensuring it always matches implementation. The IDL can be published on-chain for discovery via the anchor idl init command, supporting client verification of program interfaces and enabling dynamic client generation across multiple languages.
Testing Framework
Anchor includes a comprehensive testing framework built around TypeScript and Mocha. The BanksClient enables in-memory transaction testing without full validator deployment, while LocalValidator provides complete on-chain validation. ProgramTest simplifies program deployment and initialization for tests. The Provider abstraction manages connections, wallets, and confirmations. Account fetching utilities enable state validation after transactions. Transaction simulation allows previewing execution results before submission. Multiple testing approaches including unit, integration, and property-based tests ensure robust program behavior.
Client Libraries
Anchor provides client libraries in TypeScript and JavaScript for frontend development. The Program object offers typed interfaces to interact with deployed Anchor programs, with methods mapped directly to on-chain instructions. AccountClient enables fetching and subscribing to on-chain account state with automatic deserialization. The MethodsBuilder interface creates fluent transaction builders with proper account and argument handling. EventParser classes process program logs to extract typed event data. The Provider abstraction manages connection, wallet, and confirmation logic across different environments.
Workspace Management
Anchor's workspace system manages multi-program projects through the Anchor.toml configuration. Workspaces can contain multiple interrelated programs with shared dependencies and testing. The CLI provides commands for managing program builds, tests, and deployments across the workspace. Dependencies between programs are managed through local crates with feature flags. The anchor init and anchor new commands scaffold projects with correct directory structure and configuration. This approach enables development of complex protocol systems with multiple interacting programs.
Development Tools
Essential tools and frameworks for building with Anchor
Testing & Deployment
Best practices for validating and launching Anchor applications
Program Interaction and Composability
Building interoperable applications in the Solana ecosystem
Cross-Program Invocation
Solana's Cross-Program Invocation (CPI) allows programs to call other programs directly. Anchor simplifies this with CpiContext, providing type safety and automatic account passing. Programs can invoke methods on other programs with proper permissioning, enabling a composable ecosystem where programs build on each other's functionality while maintaining security boundaries.
Program Derived Addresses
PDAs enable programs to control addresses derived deterministically from seeds. The 'seeds' and 'bump' constraints in Anchor handle PDA derivation and validation automatically. PDAs serve multiple purposes: they act as deterministic addresses for storing program data, enable programs to sign for operations (sign_for pattern), and create capability-based security models where address derivation encodes permissions.
Anchor-to-Anchor Integration
When two Anchor programs need to interact, the cpi Cargo feature generates client modules that mirror the target program's API. This enables strongly-typed, compile-time verified program interactions. The integration pattern includes importing the target program's crate with the cpi feature enabled, defining account contexts matching the target program's requirements, and using the generated client to make type-safe calls.
Non-Anchor Program Integration
Interacting with non-Anchor Solana programs requires more manual work, but Anchor provides helper utilities. The 'interface' attribute macro enables creation of type-safe wrappers around non-Anchor programs. For native programs like System, Token, and Associated Token programs, Anchor provides pre-built integrations that handle the low-level details of instruction creation and account management.
Instruction Parsing
Anchor programs can parse and validate incoming instructions to ensure they match expected formats. This is useful when a program needs to analyze or modify instructions it received. The anchor_lang::solana_program::instruction module provides utilities for instruction parsing, while Anchor's deserialization helps interpret data from other programs. This enables complex protocol interactions where programs can inspect and augment instructions.
Token Program Integration
Anchor provides first-class integration with the Solana SPL Token program for handling fungible tokens. The 'anchor-spl' crate includes type-safe wrappers for token operations like transfers, mints, and burns. Associated token accounts can be created, managed, and validated through Anchor constraints, simplifying token handling. This integration enables development of DeFi protocols, marketplaces, and other token-based applications with minimal boilerplate.
Metaplex Integration
For NFT applications, Anchor can integrate with Metaplex's Token Metadata program. While not built into Anchor core, community-created crates provide type-safe interfaces to the Metaplex ecosystem. These integrations handle the complexity of NFT metadata creation, verification, and management, enabling developers to build NFT marketplaces, collectibles platforms, and on-chain games that leverage metadata-enriched tokens.
Composable Applications
The ultimate goal of program interaction is building composable applications where multiple specialized programs work together. Common patterns include liquidity protocols that can be integrated into multiple frontends, governance systems that manage multiple community-owned programs, yield aggregators that coordinate across lending and trading protocols, and multi-protocol positions that leverage multiple DeFi primitives to create complex financial instruments.
Governance & Program Administration
Managing updates and community control of Anchor programs
Security Best Practices
Protecting your Anchor programs on Solana
Account Validation
Thoroughly validate all accounts using Anchor's constraint system. Use ownership constraints to verify account ownership, has_one constraints to validate relationships between accounts, seeds constraints to verify PDAs, and custom constraints for complex validations. Never trust client-provided accounts without proper validation, as improper account validation is the most common source of vulnerabilities in Solana programs.
Safe Arithmetic
Prevent overflow/underflow vulnerabilities by using Rust's checked arithmetic operations (checked_add, checked_sub, checked_mul, checked_div) for all financial calculations. Alternatively, use the safeMath library for wrapping operations or standard library functions like saturating_add for operations that should never fail. Validate that numeric inputs are within expected ranges to prevent manipulation attacks.
Proper Authority Checking
Implement rigorous authority checking for all privileged operations. Use the #[account(signer)] constraint to verify transaction signatures, verify authorities stored in accounts match the signer, implement tiered authority systems for critical operations, and consider requiring multiple signers for high-value transactions. Authority validation failures account for many security incidents.
Cross-Program Invocation Safety
Handle CPIs (Cross-Program Invocations) safely by validating target program IDs, verifying returned values, implementing proper error handling for failed invocations, and being cautious with the remaining_accounts pattern. When accepting CPIs from other programs, validate the caller's permissions and implement rate limiting for resource-intensive operations to prevent denial of service attacks.
Reentrancy Protection
Prevent reentrancy attacks by implementing state checks before CPIs, using execution flags to track program state during execution, completing all state changes before calling external programs, and considering the potential for nested CPIs that could manipulate program state. Solana's account model makes reentrancy less common than in Ethereum, but it's still possible through complex CPI chains.
Program Upgrade Security
Secure program upgrades by implementing proper upgrade authority controls, testing upgrades extensively on testnet before mainnet deployment, validating state compatibility between versions, considering timelock mechanisms for critical upgrades, and maintaining the ability to rollback if necessary. As your protocol matures, consider transitioning upgrade authority to decentralized governance.
Comprehensive Testing
Implement thorough testing at multiple levels: unit tests for individual functions, integration tests with Anchor's testing framework, fuzz testing to identify edge cases, property-based testing for invariant validation, and security-focused testing that deliberately attempts to break security assumptions. Test negative scenarios (expected failures) as well as positive paths to ensure proper error handling.
Professional Auditing
For production-ready code, obtain security audits from professional firms with Solana/Anchor expertise. Prepare for audits by documenting security assumptions, providing comprehensive tests, and implementing monitoring for post-audit security. Consider continuous security reviews as your protocol evolves rather than one-time audits. Implement a responsible disclosure policy for vulnerability reporting.
Real-World Examples
Success stories and use cases built with Anchor on Solana
Marinade Finance
Marinade is a liquid staking protocol built with Anchor that allows SOL holders to stake while maintaining liquidity. The protocol uses multiple Anchor programs to handle staking delegation across validators, minting of mSOL tokens, and fee distribution. Marinade leverages Anchor's security features to protect over $100M in TVL, showcasing how Anchor can be used to build highly secure financial infrastructure with minimal code.
Solend
Solend is a decentralized lending protocol that enables users to earn interest on deposits and borrow assets. Built with Anchor, it features a complex system of risk parameters, isolated lending pools, and oracle integration. The protocol demonstrates Anchor's capability for building sophisticated financial applications with multiple interacting components. Solend's code serves as an excellent reference for handling complex state management in Anchor.
Jupiter Aggregator
Jupiter is the leading liquidity aggregator on Solana, routing trades across all major DEXes to find the best prices. Its Anchor programs implement complex routing algorithms while maintaining high performance. Jupiter demonstrates how Anchor can be used to build high-throughput infrastructure serving millions of users. The project features advanced CPI patterns to interact with multiple external programs within a single transaction.
Metaplex
Metaplex's NFT standard is implemented with Anchor and powers most NFTs on Solana. The protocol includes Token Metadata, Candy Machine (for minting), and Auction House (for marketplaces) programs. Metaplex showcases how Anchor enables building standardized protocols that the entire ecosystem can build upon. Their modular approach demonstrates effective program composition patterns in the Anchor framework.
Squads
Squads is a multisig and DAO tooling platform that enables secure treasury management and governance. Built entirely with Anchor, it implements a sophisticated transaction creation, proposal, and execution system with fine-grained permissions. Squads demonstrates Anchor's suitability for governance applications that require high security and complex role-based access control systems.
Clockwork
Clockwork provides automation infrastructure for Solana, allowing developers to schedule transactions and create automated workflows. Implemented with Anchor, it demonstrates how the framework can be used to build core infrastructure services. Clockwork showcases advanced Anchor patterns including thread management, secure delegation of transaction execution, and persistent state handling for long-running processes.
Future of Anchor
Upcoming developments and the roadmap for the framework
Frequently Asked Questions
Common questions about developing with Anchor
Additional Resources
Essential links and tools for Anchor developers
Anchor Documentation
Official documentation for the Anchor framework, including API references, guides, and examples.
Anchor GitHub Repository
Source code, issue tracking, and community discussions for the Anchor framework.
Solana Cookbook Anchor Sections
Practical recipes and patterns for Anchor development in the Solana Cookbook.
Solana Developer Documentation
Official Solana documentation for understanding the underlying blockchain that Anchor builds on.
Anchor Project Templates
Starter templates and examples for different types of Anchor projects.
Anchor TypeScript Package
NPM package for interacting with Anchor programs from JavaScript/TypeScript clients.
Anchor Discord Channel
Community support and discussions in the Anchor channel of the Solana Discord.
Solana Stack Exchange
Q&A site for Solana and Anchor development questions.
Anchor Tutorial Series
Comprehensive step-by-step tutorial for learning Anchor development from Buildspace.
Solana Playground
Browser-based IDE with built-in Anchor support for quick development and testing.
Solana Program Library (SPL)
Collection of on-chain programs commonly used with Anchor development.
Anchor Workshop Videos
Educational videos and workshops showcasing Anchor development techniques.
Ready to Build with Anchor?
Take the next steps in your Solana development journey with Anchor