Anchor Framework
repository·master·Indexed 26 days ago
https://github.com/otter-sec/anchorA framework for Solana program development featuring a Rust eDSL, IDL specification, TypeScript client generation, and a CLI for workspace management. It includes the Anchor Version Manager (AVM) for managing Anchor, Solana CLI, and platform-tools versions, as well as integration with Crucible for coverage-guided program fuzzing via `anchor fuzz`.
What's inside Anchor
- Anchor v1 is the stable, published development framework for building secure Solana programs (smart contracts) and clients. It is designed to simplify writing, testing, deploying, and interacting with Solana programs while providing built-in security features to reduce vulnerabilities.
Understand Token 2022 Extensions
masterThe Token Extensions Program (Token 2022) allows adding optional features to token mints and accounts via extensions.
Key Implementation Rules:
- Initialization: Most extensions add state that must be initialized during the initial creation of the mint or token account.
- Exceptions: The following extensions can be added to an account after it has been initialized:
cpi-guardmemo-transfertoken-grouptoken-membertoken-metadata
- Incompatibility: Some extensions cannot be used together. For example,
NonTransferableis incompatible withTransferFeeConfigdue to conflicting behaviors. - Data Storage: Extension-specific state is stored in the
tlv_datafield, which follows the base account data. To access this data, you must deserialize thetlv_dataaccording to the specificExtensionTypes enabled for that account.
Choose the correct Account wrapper
masterAnchor provides several account wrappers that determine ownership checks, data layout, borrow behavior, and exit behavior. Choose based on your data requirements:
Type Use for Account<T>Program-owned fixed-size data. Zero-copy, Pod-backed. BorshAccount<T>Variable-length data with Vec,String, or payload enums.Slab<H, Item>Header plus dynamic Pod item tail (e.g., ledgers, order books). Option<A>Optional account slot (uses program ID as absent sentinel). Nested<T>Inline composition of another #[derive(Accounts)]struct.Box<A>Heap-boxed wrapper for large account structs. SignerAn account that must have signed the transaction. Program<T: Id>A CPI target or well-known executable program. SystemAccountSystem-owned account with no typed payload. UncheckedAccountEscape hatch with no validation. Sysvar<T>Account-form sysvar access. Understand the Anchor v2 Design and Account Model
masterAnchor v2 is a pinocchio-based,
#![no_std]runtime. It is designed to be zero-copy by default for fixed-size accounts and is organized around traits to allow for extensibility of account wrappers, constraints, CPI helpers, and IDL metadata.Account Types
Account<T>: Use this for Pod-backed account state. It is zero-copy by default.BorshAccount<T>: Use this when an account requires variable-length fields, such asVecorString.
CPI and Safety
Cross-program calls (CPI) use borrow-tracked
CpiHandle<'a>values, ensuring that typed account access and CPI share the same safety model.Understand Token Extensions (Token 2022)
masterToken Extensions (part of the Token 2022 program) allow you to add optional functionality to token mints and token accounts.
Key Implementation Rules
- Initialization: Most extensions must be enabled during the initial creation of the mint or token account. They cannot be added to an existing account.
- Exceptions: The following extensions can be added after the account has been initialized:
cpi-guardmemo-transfertoken-grouptoken-membertoken-metadata
- Incompatibility: Some extensions are mutually exclusive. For example, you cannot combine the
NonTransferableextension with theTransferFeeConfigextension. - Data Storage: Extension-specific state is stored in the
tlv_datafield, which follows the base account data. This data must be deserialized according to the specific enabledExtensionTypes.
Use @anchor-lang/core TypeScript client
master@anchor-lang/core is a TypeScript client designed for interacting with Anchor programs. You can find the full API documentation via TypeDoc at https://otter-sec.github.io/anchor/ts/index.html.Check Platform Support for @anchor-lang/cli
masterThe
@anchor-lang/clinpm package bundles theanchorbinary specifically forx86_64Linux.On other platforms, the npm wrapper will attempt to use a globally installed
anchorbinary of the same version. If you require a native installation flow for non-Linux platforms, use the official installation guide.Understand Anchor Discriminators
masterAnchor uses unique 8-byte discriminators to identify specific instructions and account types within a program. These discriminators are automatically handled by the Anchor client, so direct interaction is typically unnecessary. As of Anchor v0.30, these discriminators are included in the IDL file.
Discriminators are generated by taking the first 8 bytes of the Sha256 hash of a specific prefix combined with the name of the instruction or account.
Understand SPL token account models in Anchor
masterWhen working with the legacy SPL Token Program in Anchor, the SPL surface uses specific account wrappers and constraints to mirror Anchor's account model:
Account<Mint>: Used to zero-copy SPL mint data.Account<TokenAccount>: Used to zero-copy SPL token account data.mint::*andtoken::*constraints: These act as downstreamAccountConstraintmarkers.- CPI helpers: Available via
anchor_spl_v2::token::cpi. - CPI account structs: Constructed using
cpi_handle()andcpi_handle_mut().
Use anchor-spl-v2 for SPL Token and Token-2022 support
masterThe
anchor-spl-v2crate provides tools for interacting with SPL token programs via Cross-Program Invocations (CPI). It includes zero-copy account types, namespaced constraints, CPI helpers, and support for the Token-2022 interface.Key features include:
- Account Wrappers: Implement shared traits for easy handling.
- Constraints: Downstream
AccountConstraintmarkers for validation. - CPI Helpers: Use
CpiHandleto execute token instructions through a cost-optimized CPI path. - Token-2022 Support: Use
InterfaceAccount<T>to accept accounts owned by either the legacy Token Program or the new Token-2022 program.
Understand Anchor Program Fundamentals
masterAnchor programs are built around several core concepts that manage how instructions are processed and how data is validated on Solana. To build a program, you must understand:
- Program Structure: How handlers, discriminators, and generated modules are organized.
- Accounts and Context: Using
Context<T>to manage instruction data, typed bumps, and remaining accounts. - Account Validation: Using the
#[derive(Accounts)]macro to perform validation passes and apply constraints. - PDAs (Program Derived Addresses): Using seeds and bumps to derive addresses and utilizing generated
Resolvedstructs. - IDL (Interface Definition Language): The schema emitted by Anchor that describes accounts, types, instructions, constants, and events for client-side consumption.
- CPI (Cross-Program Invocation): How one program calls another using
CpiContext,CpiHandle, and generated CPI wrappers.
SPL Token Basics Overview
masterThis guide provides an overview of common instructions for interacting with SPL tokens (both the original Token Program and the Token 2022 Token Extension Program) within Anchor programs. The following operations are supported:
- Create a mint account: Initializes a mint that defines a new token.
- Create a token account: Initializes an account to hold a balance of a specific mint.
- Mint tokens: Increases the supply of a mint and credits a token account.
- Transfer tokens: Moves tokens between two token accounts of the same mint.