From e2c8aa084797a61ba36409388d576dd2ed9e6b3b Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Sun, 9 Aug 2020 00:28:24 +0000 Subject: [PATCH] Return delegated amount as UiTokenAmount (#11475) (#11476) * Return delegated amount as UiTokenAmount * Omit delegate and delegatedAmount when none (cherry picked from commit 88d8d3d02a0335c079da2707acbebc273a1a34cb) Co-authored-by: Tyera Eulberg --- account-decoder/src/parse_token.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/account-decoder/src/parse_token.rs b/account-decoder/src/parse_token.rs index 04201c9d9e6e41..92419b155ed268 100644 --- a/account-decoder/src/parse_token.rs +++ b/account-decoder/src/parse_token.rs @@ -35,18 +35,17 @@ pub fn parse_token( "no mint_decimals provided to parse spl-token account".to_string(), ) })?; - let ui_token_amount = token_amount_to_ui_amount(account.amount, decimals); Ok(TokenAccountType::Account(UiTokenAccount { mint: account.mint.to_string(), owner: account.owner.to_string(), - token_amount: ui_token_amount, + token_amount: token_amount_to_ui_amount(account.amount, decimals), delegate: match account.delegate { COption::Some(pubkey) => Some(pubkey.to_string()), COption::None => None, }, is_initialized: account.is_initialized, is_native: account.is_native, - delegated_amount: account.delegated_amount, + delegated_amount: token_amount_to_ui_amount(account.delegated_amount, decimals), })) } else if data.len() == size_of::() { let mint: Mint = *unpack(&mut data) @@ -99,10 +98,12 @@ pub struct UiTokenAccount { pub mint: String, pub owner: String, pub token_amount: UiTokenAmount, + #[serde(skip_serializing_if = "Option::is_none")] pub delegate: Option, pub is_initialized: bool, pub is_native: bool, - pub delegated_amount: u64, + #[serde(skip_serializing_if = "UiTokenAmount::is_zero")] + pub delegated_amount: UiTokenAmount, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] @@ -113,6 +114,16 @@ pub struct UiTokenAmount { pub amount: StringAmount, } +impl UiTokenAmount { + fn is_zero(&self) -> bool { + if let Ok(amount) = self.amount.parse::() { + amount == 0 + } else { + false + } + } +} + pub fn token_amount_to_ui_amount(amount: u64, decimals: u8) -> UiTokenAmount { // Use `amount_to_ui_amount()` once spl_token is bumped to a version that supports it: https://github.com/solana-labs/solana-program-library/pull/211 let amount_decimals = amount as f64 / 10_usize.pow(decimals as u32) as f64; @@ -177,7 +188,11 @@ mod test { delegate: None, is_initialized: true, is_native: false, - delegated_amount: 0, + delegated_amount: UiTokenAmount { + ui_amount: 0.0, + decimals: 2, + amount: "0".to_string() + }, }), );