Skip to main content
The anchor-client crate provides a Rust client library for interacting with Anchor programs. It offers a type-safe, ergonomic API for building transactions, sending them to the cluster, and fetching program accounts.

Installation

Add anchor-client to your Cargo.toml:
The client is blocking by default. Enable the async feature for asynchronous operations.

Core Concepts

The Anchor Rust client is built around these key components:

Client

Configures cluster connection and payer for transactions

Program

Provides methods to interact with a specific on-chain program

RequestBuilder

Builder pattern for constructing and sending transactions

Client Setup

Create a Client to manage your cluster connection and transaction payer.

API Signature

Basic Example

Using Dynamic Signers

If you need to work with Box<dyn Signer>, use the DynSigner wrapper:

Cluster Configuration

The Cluster enum defines which Solana cluster to connect to:

Usage Examples

Program Instance

Create a Program instance to interact with a specific on-chain program.

API

Creating a Program

Using declare_program!

The declare_program! macro generates type-safe client code from your program’s IDL.
1

Place IDL in idls/ directory

Create an idls/ folder in your client project root and place your program’s IDL JSON file there:
2

Declare the program

Use the macro in your code:
3

Import generated modules

The macro generates client::accounts and client::args modules:

Generated Modules

The declare_program! macro generates:
  • client::accounts - Structs matching instruction account requirements
  • client::args - Structs for instruction arguments
  • Account types - Deserializable account data structures
  • ID - The program’s public key constant

Building Transactions

Use the RequestBuilder to construct transactions with the builder pattern.

RequestBuilder API

Single Instruction

Multiple Instructions

Combine multiple instructions into a single transaction:

Remaining Accounts

For instructions that accept remaining accounts:

Fetching Accounts

Fetch and deserialize program accounts using type-safe methods.

Single Account

Multiple Accounts with Filters

Event Listeners

Subscribe to program events emitted via logs:

Complete Example

Here’s a full example demonstrating the Rust client in action:

Error Handling

The client uses the ClientError enum for error handling:

Features

The anchor-client crate supports optional features:

async

Enables asynchronous client operations:
With async enabled, all I/O operations return Futures and require an async runtime like Tokio.

mock

Allows passing custom RPC clients for testing:
Useful for mocking RPC responses in tests using RpcClient::new_mock.

API Reference

Client

Program

RequestBuilder

Next Steps

TypeScript Client

Learn about the TypeScript client library

Testing Programs

Write tests for your Anchor programs