use {
smbcloud_wallet_constants::constants::SPL_TOKEN_PROGRAM_ID,
smbcloud_wallet_core_http::price_data::{
get_asset_price::get_asset_price, get_sol_price::get_sol_price,
},
smbcloud_wallet_core_network::model::ErrorResponse,
smbcloud_wallet_core_rpc::balance::{
sol_balance::sol_balance as core_sol_balance,
spl_token_accounts_with_balance::spl_token_accounts_with_balance,
},
};
pub async fn wallet_balance(
rpc_url: String,
api_key: &str,
user_agent: &str,
pubkey: String,
) -> Result<String, ErrorResponse> {
let sol_amount = match core_sol_balance(rpc_url.clone(), pubkey.clone()) {
Ok(balance) => balance.1,
Err(_) => 0.0,
};
println!("🦀🦀 Will calculate balance for {:?} SOL", sol_amount);
let sol_price = if sol_amount >= 0.000000001 {
get_sol_price(api_key, user_agent).await?
} else {
0.0
};
let sol_value = sol_amount * sol_price;
println!("🦀🦀 SOL value is {:?} USD", sol_value);
let spl_tokens = match spl_token_accounts_with_balance(
rpc_url.clone(),
pubkey.clone(),
SPL_TOKEN_PROGRAM_ID.to_string(),
) {
Ok(tokens) => tokens,
Err(err) => {
println!("🦀🦀 Failed to get SPL token accounts: {:?}", err);
Vec::new()
}
};
println!("🦀🦀 SPL tokens with balance: {:?}", spl_tokens);
let mut spl_value = 0.0;
for token in spl_tokens {
let token_price = match get_asset_price(&token.mint, api_key, user_agent).await {
Ok(price) => price.data.value,
Err(err) => {
println!(
"🦀🦀 Failed to get price for token {}: {:?}",
token.mint, err
);
0.0
}
};
let token_amount = match token.token_amount.ui_amount {
Some(amount) => amount,
None => {
println!("🦀🦀 Token amount is None for token {}", token.mint);
0.0
}
};
spl_value += token_amount * token_price;
}
println!("🦀🦀 SPL token value is {:?} USD", spl_value);
let total_value = sol_value + spl_value;
println!("🦀🦀 Total value is {:?} USD", total_value);
Ok(format!("{}{:.2}", "$", total_value))
}