From 54b87b34c3a12768bac3726757770196f6a3a906 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Sat, 19 Sep 2020 03:53:51 +0000 Subject: [PATCH] Add get_token_account methods (#12346) (#12349) (cherry picked from commit 28f2c155979ae1652ca290b49fedffc49cd225aa) Co-authored-by: Tyera Eulberg --- client/src/rpc_client.rs | 66 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/client/src/rpc_client.rs b/client/src/rpc_client.rs index 8ae46279d5..7677abf30d 100644 --- a/client/src/rpc_client.rs +++ b/client/src/rpc_client.rs @@ -15,7 +15,10 @@ use bincode::serialize; use indicatif::{ProgressBar, ProgressStyle}; use log::*; use serde_json::{json, Value}; -use solana_account_decoder::{parse_token::UiTokenAmount, UiAccount, UiAccountEncoding}; +use solana_account_decoder::{ + parse_token::{TokenAccountType, UiTokenAccount, UiTokenAmount}, + UiAccount, UiAccountData, UiAccountEncoding, +}; use solana_sdk::{ account::Account, clock::{ @@ -722,6 +725,67 @@ impl RpcClient { Ok(hash) } + pub fn get_token_account(&self, pubkey: &Pubkey) -> ClientResult> { + Ok(self + .get_token_account_with_commitment(pubkey, CommitmentConfig::default())? + .value) + } + + pub fn get_token_account_with_commitment( + &self, + pubkey: &Pubkey, + commitment_config: CommitmentConfig, + ) -> RpcResult> { + let config = RpcAccountInfoConfig { + encoding: Some(UiAccountEncoding::JsonParsed), + commitment: Some(commitment_config), + data_slice: None, + }; + let response = self.sender.send( + RpcRequest::GetAccountInfo, + json!([pubkey.to_string(), config]), + ); + + response + .map(|result_json| { + if result_json.is_null() { + return Err( + RpcError::ForUser(format!("AccountNotFound: pubkey={}", pubkey)).into(), + ); + } + let Response { + context, + value: rpc_account, + } = serde_json::from_value::>>(result_json)?; + trace!("Response account {:?} {:?}", pubkey, rpc_account); + let response = { + if let Some(rpc_account) = rpc_account { + if let UiAccountData::Json(account_data) = rpc_account.data { + let token_account_type: TokenAccountType = + serde_json::from_value(account_data.parsed)?; + if let TokenAccountType::Account(token_account) = token_account_type { + return Ok(Response { + context, + value: Some(token_account), + }); + } + } + } + Err(Into::::into(RpcError::ForUser(format!( + "Account could not be parsed as token account: pubkey={}", + pubkey + )))) + }; + response? + }) + .map_err(|err| { + Into::::into(RpcError::ForUser(format!( + "AccountNotFound: pubkey={}: {}", + pubkey, err + ))) + })? + } + pub fn get_token_account_balance(&self, pubkey: &Pubkey) -> ClientResult { Ok(self .get_token_account_balance_with_commitment(pubkey, CommitmentConfig::default())?