Skip to content

Commit

Permalink
chore: impl decode for UiAccountData (solana-labs#33632)
Browse files Browse the repository at this point in the history
  • Loading branch information
xoac authored Nov 6, 2023
1 parent e840b97 commit 63fd5cf
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions account-decoder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,30 @@ pub enum UiAccountData {
Binary(String, UiAccountEncoding),
}

impl UiAccountData {
/// Returns decoded account data in binary format if possible
pub fn decode(&self) -> Option<Vec<u8>> {
match self {
UiAccountData::Json(_) => None,
UiAccountData::LegacyBinary(blob) => bs58::decode(blob).into_vec().ok(),
UiAccountData::Binary(blob, encoding) => match encoding {
UiAccountEncoding::Base58 => bs58::decode(blob).into_vec().ok(),
UiAccountEncoding::Base64 => BASE64_STANDARD.decode(blob).ok(),
UiAccountEncoding::Base64Zstd => {
BASE64_STANDARD.decode(blob).ok().and_then(|zstd_data| {
let mut data = vec![];
zstd::stream::read::Decoder::new(zstd_data.as_slice())
.and_then(|mut reader| reader.read_to_end(&mut data))
.map(|_| data)
.ok()
})
}
UiAccountEncoding::Binary | UiAccountEncoding::JsonParsed => None,
},
}
}
}

#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub enum UiAccountEncoding {
Expand Down Expand Up @@ -139,24 +163,7 @@ impl UiAccount {
}

pub fn decode<T: WritableAccount>(&self) -> Option<T> {
let data = match &self.data {
UiAccountData::Json(_) => None,
UiAccountData::LegacyBinary(blob) => bs58::decode(blob).into_vec().ok(),
UiAccountData::Binary(blob, encoding) => match encoding {
UiAccountEncoding::Base58 => bs58::decode(blob).into_vec().ok(),
UiAccountEncoding::Base64 => BASE64_STANDARD.decode(blob).ok(),
UiAccountEncoding::Base64Zstd => {
BASE64_STANDARD.decode(blob).ok().and_then(|zstd_data| {
let mut data = vec![];
zstd::stream::read::Decoder::new(zstd_data.as_slice())
.and_then(|mut reader| reader.read_to_end(&mut data))
.map(|_| data)
.ok()
})
}
UiAccountEncoding::Binary | UiAccountEncoding::JsonParsed => None,
},
}?;
let data = self.data.decode()?;
Some(T::create(
self.lamports,
data,
Expand Down

0 comments on commit 63fd5cf

Please sign in to comment.