1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
use solana_account_decoder::parse_token::real_number_string_trimmed; use solana_sdk::native_token::lamports_to_sol; use std::{ fmt::{Debug, Display, Formatter, Result}, ops::Add, }; const VLX_SYMBOL: &str = "◎"; #[derive(PartialEq)] pub enum TokenType { Sol, SplToken, } pub struct Token { amount: u64, decimals: u8, token_type: TokenType, } impl Token { fn write_with_symbol(&self, f: &mut Formatter) -> Result { match &self.token_type { TokenType::Sol => { let amount = lamports_to_sol(self.amount); write!(f, "{}{}", VLX_SYMBOL, amount) } TokenType::SplToken => { let amount = real_number_string_trimmed(self.amount, self.decimals); write!(f, "{} tokens", amount) } } } pub fn sol(amount: u64) -> Self { Self { amount, decimals: 9, token_type: TokenType::Sol, } } pub fn spl_token(amount: u64, decimals: u8) -> Self { Self { amount, decimals, token_type: TokenType::SplToken, } } } impl Display for Token { fn fmt(&self, f: &mut Formatter) -> Result { self.write_with_symbol(f) } } impl Debug for Token { fn fmt(&self, f: &mut Formatter) -> Result { self.write_with_symbol(f) } } impl Add for Token { type Output = Token; fn add(self, other: Self) -> Self { if self.token_type == other.token_type { Self { amount: self.amount + other.amount, decimals: self.decimals, token_type: self.token_type, } } else { self } } }