Skip to main content

anchor_parser/
client.rs

1//! Async RPC client helpers for fetching and deserializing accounts.
2//!
3//! Requires the `client` feature (adds a `solana-client` dependency).
4//!
5//! ```ignore
6//! use anchor_parser::client;
7//! use my_program::accounts::MyAccount;
8//!
9//! let account = client::fetch_account::<MyAccount>(&rpc_client, &address).await?;
10//! let accounts = client::fetch_accounts::<MyAccount>(&rpc_client, &[addr1, addr2]).await?;
11//! ```
12
13use solana_client::client_error::ClientError;
14use solana_client::nonblocking::rpc_client::RpcClient;
15use solana_sdk::pubkey::Pubkey;
16
17use crate::AccountDeserialize;
18
19/// Fetch and deserialize a single account from an async RPC client.
20pub async fn fetch_account<T: AccountDeserialize>(
21    client: &RpcClient,
22    address: &Pubkey,
23) -> Result<T, ClientError> {
24    let account = client.get_account(address).await?;
25    T::deserialize(&account.data).map_err(|e| e.into())
26}
27
28/// Fetch and deserialize multiple accounts of the same type.
29///
30/// Returns `None` for accounts that don't exist or fail deserialization.
31pub async fn fetch_accounts<T: AccountDeserialize>(
32    client: &RpcClient,
33    addresses: &[Pubkey],
34) -> Result<Vec<Option<T>>, ClientError> {
35    let accounts = client.get_multiple_accounts(addresses).await?;
36    Ok(accounts
37        .into_iter()
38        .map(|maybe_acc| maybe_acc.and_then(|acc| T::deserialize(&acc.data).ok()))
39        .collect())
40}