light_client/indexer/
base58.rs1use bs58;
2use solana_pubkey::Pubkey;
3
4use crate::indexer::error::IndexerError;
5
6pub trait Base58Conversions {
7 fn to_base58(&self) -> String;
8 fn from_base58(s: &str) -> Result<Self, IndexerError>
9 where
10 Self: Sized;
11 fn to_bytes(&self) -> [u8; 32];
12 fn from_bytes(bytes: &[u8]) -> Result<Self, IndexerError>
13 where
14 Self: Sized;
15}
16
17impl Base58Conversions for [u8; 32] {
18 fn to_base58(&self) -> String {
19 bs58::encode(self).into_string()
20 }
21
22 fn from_base58(s: &str) -> Result<Self, IndexerError> {
23 decode_base58_to_fixed_array(s)
24 }
25
26 fn to_bytes(&self) -> [u8; 32] {
27 *self
28 }
29
30 fn from_bytes(bytes: &[u8]) -> Result<Self, IndexerError> {
31 let mut arr = [0u8; 32];
32 arr.copy_from_slice(bytes);
33 Ok(arr)
34 }
35}
36
37pub fn decode_base58_to_fixed_array<const N: usize>(input: &str) -> Result<[u8; N], IndexerError> {
38 let mut buffer = [0u8; N];
39 let decoded_len = bs58::decode(input)
40 .onto(&mut buffer)
41 .map_err(|_| IndexerError::InvalidResponseData)?;
42
43 if decoded_len != N {
44 return Err(IndexerError::InvalidResponseData);
45 }
46
47 Ok(buffer)
48}
49
50pub fn decode_base58_option_to_pubkey(
51 value: &Option<String>,
52) -> Result<Option<Pubkey>, IndexerError> {
53 value
54 .as_ref()
55 .map(|ctx| decode_base58_to_fixed_array(ctx).map(Pubkey::new_from_array))
56 .transpose()
57}