AddressBook

Struct AddressBook 

Source
pub struct AddressBook { /* private fields */ }
Expand description

Address book for mapping public keys to registered addresses with labels.

This structure maintains multiple mappings to efficiently track and query Solana addresses by their public keys, labels, and roles. It’s designed to help with debugging and transaction analysis by providing meaningful context for addresses.

Implementations§

Source§

impl AddressBook

Source

pub fn new() -> AddressBook

Creates a new empty address book.

§Example
use solana_address_book::AddressBook;

let book = AddressBook::new();
assert!(book.is_empty());
Source

pub fn add_default_accounts(&mut self) -> Result<(), Error>

Adds default Solana system programs to the address book.

This includes:

  • System Program
  • Token Program
  • Associated Token Program
§Errors

Returns an error if any of the default programs fail to be added (e.g., due to duplicate labels).

§Example
use solana_address_book::AddressBook;

let mut book = AddressBook::new();
book.add_default_accounts().unwrap();

// The system program is now registered
assert!(book.contains(&anchor_lang::solana_program::system_program::ID));
Source

pub fn get_label(&self, pubkey: &Pubkey) -> String

Gets the label for a given public key.

If the address is registered, returns its label. Otherwise, returns the string representation of the public key.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

// Before registration, returns the pubkey string
assert_eq!(book.get_label(&wallet), wallet.to_string());

// After registration, returns the label
book.add_wallet(wallet, "alice".to_string()).unwrap();
assert_eq!(book.get_label(&wallet), "alice");
Source

pub fn add( &mut self, pubkey: Pubkey, label: String, registered_address: RegisteredAddress, ) -> Result<(), Error>

Adds an address with a registered address and label to the address book.

This is the core method for adding addresses. All other add methods (add_wallet, add_mint, etc.) internally use this method.

§Errors

Returns an error if the label already exists with a different address or role.

§Example
use solana_address_book::{AddressBook, RegisteredAddress};
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();
let registered = RegisteredAddress::wallet(wallet);

book.add(wallet, "my_wallet".to_string(), registered).unwrap();
assert_eq!(book.get_label(&wallet), "my_wallet");
Source

pub fn add_wallet(&mut self, pubkey: Pubkey, label: String) -> Result<(), Error>

Adds a wallet address to the address book.

§Errors

Returns an error if the label already exists with a different address.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

book.add_wallet(wallet, "alice".to_string()).unwrap();

// The wallet is now registered
assert!(book.contains(&wallet));
assert_eq!(book.get_label(&wallet), "alice");
Source

pub fn add_custom( &mut self, pubkey: Pubkey, label: String, custom_role: String, ) -> Result<(), Error>

Adds a custom role address to the address book.

Use this for addresses that don’t fit into the standard categories.

§Errors

Returns an error if the label already exists with a different address.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let address = Pubkey::new_unique();

book.add_custom(
    address,
    "dao_treasury".to_string(),
    "governance".to_string()
).unwrap();

assert_eq!(book.get_label(&address), "dao_treasury");
Source

pub fn add_pda( &mut self, pubkey: Pubkey, label: String, seeds: Vec<String>, program_id: Pubkey, bump: u8, ) -> Result<(), Error>

Adds a Program Derived Address (PDA) to the address book.

§Arguments
  • pubkey - The PDA’s public key
  • label - Human-readable label for the PDA
  • seeds - The string representations of seeds used to derive the PDA
  • program_id - The program that owns the PDA
  • bump - The bump seed used to derive the PDA
§Errors

Returns an error if the label already exists with a different address.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let pda = Pubkey::new_unique();
let program = Pubkey::new_unique();

book.add_pda(
    pda,
    "vault".to_string(),
    vec!["vault".to_string(), "v1".to_string()],
    program,
    255
).unwrap();

assert_eq!(book.get_label(&pda), "vault");
Source

pub fn add_program(&mut self, pubkey: Pubkey, label: &str) -> Result<(), Error>

Adds a program address to the address book.

§Errors

Returns an error if the label already exists with a different address.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let program = Pubkey::new_unique();

book.add_program(program, "my_program").unwrap();
assert_eq!(book.get_label(&program), "my_program");
Source

pub fn find_pda_with_bump( &mut self, label: &str, seeds: &[&[u8]], program_id: Pubkey, ) -> Result<(Pubkey, u8), Error>

Finds a PDA with bump and adds it to the address book.

This method derives the PDA from the provided seeds and program ID, then automatically registers it in the address book.

§Returns

A tuple containing the derived PDA public key and bump seed.

§Errors

Returns an error if the label already exists with a different address.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let program = Pubkey::new_unique();
let user = Pubkey::new_unique();

let (pda, bump) = book.find_pda_with_bump(
    "user_vault",
    &[b"vault", user.as_ref()],
    program
).unwrap();

assert_eq!(book.get_label(&pda), "user_vault");
Source

pub fn get(&self, pubkey: &Pubkey) -> Option<&Vec<(String, RegisteredAddress)>>

Gets all registered addresses for a public key.

A single public key can have multiple registrations with different labels.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

book.add_wallet(wallet, "alice".to_string()).unwrap();

let registrations = book.get(&wallet);
assert!(registrations.is_some());
assert_eq!(registrations.unwrap().len(), 1);
Source

pub fn get_first( &self, pubkey: &Pubkey, ) -> Option<(&String, &RegisteredAddress)>

Gets the first registered address for a public key.

Returns the first label and registered address pair if the pubkey exists.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

book.add_wallet(wallet, "alice".to_string()).unwrap();

let (label, reg) = book.get_first(&wallet).unwrap();
assert_eq!(*label, "alice");
Source

pub fn get_by_role(&self, role: &AddressRole) -> Option<Pubkey>

Finds an address by its role.

Returns the first address that matches the specified role.

§Example
use solana_address_book::{AddressBook, AddressRole};
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

book.add_wallet(wallet, "alice".to_string()).unwrap();

let found = book.get_by_role(&AddressRole::Wallet);
assert_eq!(found, Some(wallet));
Source

pub fn get_all_by_role_type(&self, role_type: &str) -> Vec<Pubkey>

Gets all addresses with a specific role type.

Role types are: “wallet”, “mint”, “ata”, “pda”, “program”, “custom”

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet1 = Pubkey::new_unique();
let wallet2 = Pubkey::new_unique();

book.add_wallet(wallet1, "alice".to_string()).unwrap();
book.add_wallet(wallet2, "bob".to_string()).unwrap();

let wallets = book.get_all_by_role_type("wallet");
assert_eq!(wallets.len(), 2);
assert!(wallets.contains(&wallet1));
assert!(wallets.contains(&wallet2));
Source

pub fn format_address(&self, pubkey: &Pubkey) -> String

Gets a formatted string representation of an address with colors.

If the address is registered, returns a colored label with its role. Otherwise, returns the address string in red.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

book.add_wallet(wallet, "alice".to_string()).unwrap();

let formatted = book.format_address(&wallet);
assert!(formatted.contains("alice"));
assert!(formatted.contains("[wallet]"));
Source

pub fn replace_addresses_in_text(&self, text: &str) -> String

Replaces all public key addresses in text with their labels.

Scans the provided text for any registered public keys and replaces them with their colored labels.

§Example
use solana_address_book::{AddressBook, RegisteredAddress};
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let token = Pubkey::new_unique();

book.add(token, "my_token".to_string(), RegisteredAddress::mint(token)).unwrap();

let text = format!("Transfer to {}", token);
let formatted = book.replace_addresses_in_text(&text);

// The pubkey is replaced with the colored label
assert!(formatted.contains("my_token"));
assert!(!formatted.contains(&token.to_string()));
Source

pub fn print_all(&self)

Prints all addresses in the address book with colored formatting.

Addresses are grouped by role type and displayed with appropriate colors. This is useful for debugging and getting an overview of all registered addresses.

§Example
use solana_address_book::{AddressBook, RegisteredAddress};
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
book.add_wallet(Pubkey::new_unique(), "alice".to_string()).unwrap();
let mint = Pubkey::new_unique();
book.add(mint, "usdc".to_string(), RegisteredAddress::mint(mint)).unwrap();

// Prints a formatted table of all addresses
book.print_all();
Source

pub fn contains(&self, pubkey: &Pubkey) -> bool

Checks if an address exists in the book.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
let wallet = Pubkey::new_unique();

assert!(!book.contains(&wallet));

book.add_wallet(wallet, "alice".to_string()).unwrap();
assert!(book.contains(&wallet));
Source

pub fn len(&self) -> usize

Returns the number of unique public keys in the address book.

Note: This counts unique public keys, not total registrations. A single pubkey can have multiple registrations with different labels.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
assert_eq!(book.len(), 0);

book.add_wallet(Pubkey::new_unique(), "alice".to_string()).unwrap();
assert_eq!(book.len(), 1);
Source

pub fn is_empty(&self) -> bool

Checks if the address book is empty.

§Example
use solana_address_book::AddressBook;
use anchor_lang::prelude::*;

let mut book = AddressBook::new();
assert!(book.is_empty());

book.add_wallet(Pubkey::new_unique(), "alice".to_string()).unwrap();
assert!(!book.is_empty());

Trait Implementations§

Source§

impl Clone for AddressBook

Source§

fn clone(&self) -> AddressBook

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AddressBook

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for AddressBook

Source§

fn default() -> AddressBook

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,