Skip to content

Commit

Permalink
Return delegated amount as UiTokenAmount (#11475) (#11476)
Browse files Browse the repository at this point in the history
* Return delegated amount as UiTokenAmount

* Omit delegate and delegatedAmount when none

(cherry picked from commit 88d8d3d)

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>
  • Loading branch information
mergify[bot] and CriesofCarrots authored Aug 9, 2020
1 parent 9b04940 commit e2c8aa0
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions account-decoder/src/parse_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Mint>() {
let mint: Mint = *unpack(&mut data)
Expand Down Expand Up @@ -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<String>,
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)]
Expand All @@ -113,6 +114,16 @@ pub struct UiTokenAmount {
pub amount: StringAmount,
}

impl UiTokenAmount {
fn is_zero(&self) -> bool {
if let Ok(amount) = self.amount.parse::<u64>() {
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;
Expand Down Expand Up @@ -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()
},
}),
);

Expand Down

0 comments on commit e2c8aa0

Please sign in to comment.