use crate::{Result, ToolkitError};
use solana_client::rpc_client::RpcClient;
use solana_sdk::pubkey::Pubkey;
use spl_token::{solana_program::program_pack::Pack, state::Mint};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TokenRiskLevel {
Safe,
Caution,
Warning,
Critical,
}
impl std::fmt::Display for TokenRiskLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenRiskLevel::Safe => write!(f, "SAFE"),
TokenRiskLevel::Caution => write!(f, "CAUTION"),
TokenRiskLevel::Warning => write!(f, "WARNING"),
TokenRiskLevel::Critical => write!(f, "CRITICAL"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum RiskIndicator {
ActiveMintAuthority,
ActiveFreezeAuthority,
HighHolderConcentration { top_10_percent: f64 },
LowHolderCount { count: usize },
LowSupply { supply: u64 },
NotInitialized,
SuspiciousMetadata { reason: String },
}
impl RiskIndicator {
pub fn weight(&self) -> u8 {
match self {
RiskIndicator::ActiveMintAuthority => 20,
RiskIndicator::ActiveFreezeAuthority => 25,
RiskIndicator::HighHolderConcentration { top_10_percent } => {
if *top_10_percent > 90.0 {
25
} else if *top_10_percent > 70.0 {
15
} else {
10
}
}
RiskIndicator::LowHolderCount { count } => {
if *count < 10 {
20
} else if *count < 50 {
15
} else {
10
}
}
RiskIndicator::LowSupply { .. } => 10,
RiskIndicator::NotInitialized => 25,
RiskIndicator::SuspiciousMetadata { .. } => 15,
}
}
pub fn description(&self) -> String {
match self {
RiskIndicator::ActiveMintAuthority => {
"Mint authority active: token creator can print unlimited tokens".to_string()
}
RiskIndicator::ActiveFreezeAuthority => {
"Freeze authority active: token creator can freeze any wallet".to_string()
}
RiskIndicator::HighHolderConcentration { top_10_percent } => {
format!(
"High concentration: top 10 holders own {:.1}% of supply",
top_10_percent
)
}
RiskIndicator::LowHolderCount { count } => {
format!("Low holder count: only {} unique holders", count)
}
RiskIndicator::LowSupply { supply } => {
format!("Low token supply: {}", supply)
}
RiskIndicator::NotInitialized => "Token mint not properly initialized".to_string(),
RiskIndicator::SuspiciousMetadata { reason } => {
format!("Suspicious metadata: {}", reason)
}
}
}
}
#[derive(Debug, Clone)]
pub struct HolderDistribution {
pub holder_count: usize,
pub top_1_percent: f64,
pub top_5_percent: f64,
pub top_10_percent: f64,
pub top_holders: Vec<(Pubkey, u64, f64)>,
}
impl Default for HolderDistribution {
fn default() -> Self {
Self {
holder_count: 0,
top_1_percent: 0.0,
top_5_percent: 0.0,
top_10_percent: 0.0,
top_holders: Vec::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct TokenSafetyReport {
pub mint: Pubkey,
pub risk_level: TokenRiskLevel,
pub risk_score: u8,
pub indicators: Vec<RiskIndicator>,
pub supply: u64,
pub decimals: u8,
pub mint_authority_active: bool,
pub freeze_authority_active: bool,
pub holder_distribution: Option<HolderDistribution>,
pub summary: String,
}
impl TokenSafetyReport {
pub fn is_safe(&self) -> bool {
self.risk_level == TokenRiskLevel::Safe
}
pub fn should_avoid(&self) -> bool {
matches!(
self.risk_level,
TokenRiskLevel::Warning | TokenRiskLevel::Critical
)
}
pub fn get_warnings(&self) -> Vec<String> {
self.indicators.iter().map(|i| i.description()).collect()
}
}
pub struct TokenSafetyChecker {
min_holder_count: usize,
max_top_10_concentration: f64,
}
impl Default for TokenSafetyChecker {
fn default() -> Self {
Self::new()
}
}
impl TokenSafetyChecker {
pub fn new() -> Self {
Self {
min_holder_count: 100,
max_top_10_concentration: 50.0,
}
}
pub fn min_holders(mut self, count: usize) -> Self {
self.min_holder_count = count;
self
}
pub fn max_concentration(mut self, percent: f64) -> Self {
self.max_top_10_concentration = percent;
self
}
pub fn analyze_token(&self, client: &RpcClient, mint: &Pubkey) -> Result<TokenSafetyReport> {
let account = client.get_account(mint).map_err(|e| {
ToolkitError::AccountNotFound(format!("Mint account not found: {}", e))
})?;
let mint_data = Mint::unpack(&account.data)
.map_err(|e| ToolkitError::InvalidAccountData(format!("Invalid mint data: {}", e)))?;
let mut indicators = Vec::new();
if !mint_data.is_initialized {
indicators.push(RiskIndicator::NotInitialized);
}
let mint_authority_active = mint_data.mint_authority.is_some();
if mint_authority_active {
indicators.push(RiskIndicator::ActiveMintAuthority);
}
let freeze_authority_active = mint_data.freeze_authority.is_some();
if freeze_authority_active {
indicators.push(RiskIndicator::ActiveFreezeAuthority);
}
let holder_distribution = self.get_holder_distribution(client, mint, mint_data.supply)?;
if let Some(ref dist) = holder_distribution {
if dist.top_10_percent > self.max_top_10_concentration {
indicators.push(RiskIndicator::HighHolderConcentration {
top_10_percent: dist.top_10_percent,
});
}
if dist.holder_count < self.min_holder_count {
indicators.push(RiskIndicator::LowHolderCount {
count: dist.holder_count,
});
}
}
if mint_data.supply == 0 {
indicators.push(RiskIndicator::LowSupply {
supply: mint_data.supply,
});
}
let risk_score = self.calculate_risk_score(&indicators);
let risk_level = self.score_to_level(risk_score);
let summary = self.generate_summary(&indicators, risk_level, risk_score);
Ok(TokenSafetyReport {
mint: *mint,
risk_level,
risk_score,
indicators,
supply: mint_data.supply,
decimals: mint_data.decimals,
mint_authority_active,
freeze_authority_active,
holder_distribution,
summary,
})
}
pub fn check_rug_pull_indicators(
&self,
client: &RpcClient,
mint: &Pubkey,
) -> Result<Vec<RiskIndicator>> {
let account = client.get_account(mint).map_err(|e| {
ToolkitError::AccountNotFound(format!("Mint account not found: {}", e))
})?;
let mint_data = Mint::unpack(&account.data)
.map_err(|e| ToolkitError::InvalidAccountData(format!("Invalid mint data: {}", e)))?;
let mut indicators = Vec::new();
if !mint_data.is_initialized {
indicators.push(RiskIndicator::NotInitialized);
}
if mint_data.mint_authority.is_some() {
indicators.push(RiskIndicator::ActiveMintAuthority);
}
if mint_data.freeze_authority.is_some() {
indicators.push(RiskIndicator::ActiveFreezeAuthority);
}
if mint_data.supply == 0 {
indicators.push(RiskIndicator::LowSupply {
supply: mint_data.supply,
});
}
Ok(indicators)
}
pub fn get_holder_distribution(
&self,
client: &RpcClient,
mint: &Pubkey,
total_supply: u64,
) -> Result<Option<HolderDistribution>> {
if total_supply == 0 {
return Ok(None);
}
let largest_accounts = client
.get_token_largest_accounts(mint)
.map_err(|e| ToolkitError::NetworkError(format!("Failed to get holders: {}", e)))?;
if largest_accounts.is_empty() {
return Ok(Some(HolderDistribution::default()));
}
let mut top_holders = Vec::new();
for account_balance in &largest_accounts {
let amount = account_balance
.amount
.amount
.parse::<u64>()
.unwrap_or(0);
let address = account_balance.address.parse::<Pubkey>().unwrap_or_default();
let percentage = (amount as f64 / total_supply as f64) * 100.0;
top_holders.push((address, amount, percentage));
}
let holder_count = largest_accounts.len();
let top_1_percent = top_holders.first().map(|(_, _, p)| *p).unwrap_or(0.0);
let top_5_percent: f64 = top_holders.iter().take(5).map(|(_, _, p)| p).sum();
let top_10_percent: f64 = top_holders.iter().take(10).map(|(_, _, p)| p).sum();
Ok(Some(HolderDistribution {
holder_count,
top_1_percent,
top_5_percent,
top_10_percent,
top_holders,
}))
}
pub fn calculate_risk_score(&self, indicators: &[RiskIndicator]) -> u8 {
let total_weight: u16 = indicators.iter().map(|i| i.weight() as u16).sum();
total_weight.min(100) as u8
}
fn score_to_level(&self, score: u8) -> TokenRiskLevel {
match score {
0..=20 => TokenRiskLevel::Safe,
21..=40 => TokenRiskLevel::Caution,
41..=70 => TokenRiskLevel::Warning,
_ => TokenRiskLevel::Critical,
}
}
fn generate_summary(
&self,
indicators: &[RiskIndicator],
level: TokenRiskLevel,
score: u8,
) -> String {
if indicators.is_empty() {
return format!("Token appears safe. Risk score: {}/100", score);
}
let issues: Vec<String> = indicators.iter().map(|i| i.description()).collect();
format!(
"Risk Level: {} (Score: {}/100)\nIssues found:\n- {}",
level,
score,
issues.join("\n- ")
)
}
pub fn analyze_from_data(
&self,
mint: Pubkey,
supply: u64,
decimals: u8,
mint_authority: Option<Pubkey>,
freeze_authority: Option<Pubkey>,
holder_distribution: Option<HolderDistribution>,
) -> TokenSafetyReport {
let mut indicators = Vec::new();
let mint_authority_active = mint_authority.is_some();
if mint_authority_active {
indicators.push(RiskIndicator::ActiveMintAuthority);
}
let freeze_authority_active = freeze_authority.is_some();
if freeze_authority_active {
indicators.push(RiskIndicator::ActiveFreezeAuthority);
}
if let Some(ref dist) = holder_distribution {
if dist.top_10_percent > self.max_top_10_concentration {
indicators.push(RiskIndicator::HighHolderConcentration {
top_10_percent: dist.top_10_percent,
});
}
if dist.holder_count < self.min_holder_count {
indicators.push(RiskIndicator::LowHolderCount {
count: dist.holder_count,
});
}
}
if supply == 0 {
indicators.push(RiskIndicator::LowSupply { supply });
}
let risk_score = self.calculate_risk_score(&indicators);
let risk_level = self.score_to_level(risk_score);
let summary = self.generate_summary(&indicators, risk_level, risk_score);
TokenSafetyReport {
mint,
risk_level,
risk_score,
indicators,
supply,
decimals,
mint_authority_active,
freeze_authority_active,
holder_distribution,
summary,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mock_mint() -> Pubkey {
Pubkey::new_unique()
}
#[test]
fn test_safe_token_passes() {
let checker = TokenSafetyChecker::new();
let distribution = HolderDistribution {
holder_count: 1000,
top_1_percent: 5.0,
top_5_percent: 15.0,
top_10_percent: 25.0,
top_holders: vec![],
};
let report = checker.analyze_from_data(
mock_mint(),
1_000_000_000_000, 6, None, None, Some(distribution),
);
assert!(report.is_safe());
assert_eq!(report.risk_level, TokenRiskLevel::Safe);
assert_eq!(report.risk_score, 0);
assert!(report.indicators.is_empty());
}
#[test]
fn test_active_mint_authority_flagged() {
let checker = TokenSafetyChecker::new();
let authority = Pubkey::new_unique();
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
Some(authority), None,
None,
);
assert!(report.mint_authority_active);
assert!(report
.indicators
.contains(&RiskIndicator::ActiveMintAuthority));
assert!(report.risk_score >= 20); }
#[test]
fn test_active_freeze_authority_flagged() {
let checker = TokenSafetyChecker::new();
let authority = Pubkey::new_unique();
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
None,
Some(authority), None,
);
assert!(report.freeze_authority_active);
assert!(report
.indicators
.contains(&RiskIndicator::ActiveFreezeAuthority));
assert!(report.risk_score >= 25); }
#[test]
fn test_high_holder_concentration_warning() {
let checker = TokenSafetyChecker::new();
let distribution = HolderDistribution {
holder_count: 500,
top_1_percent: 30.0,
top_5_percent: 55.0,
top_10_percent: 75.0, top_holders: vec![],
};
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
None,
None,
Some(distribution),
);
let has_concentration_warning = report.indicators.iter().any(|i| {
matches!(i, RiskIndicator::HighHolderConcentration { .. })
});
assert!(has_concentration_warning);
assert!(report.risk_score > 0);
}
#[test]
fn test_low_holder_count_warning() {
let checker = TokenSafetyChecker::new();
let distribution = HolderDistribution {
holder_count: 50,
top_1_percent: 10.0,
top_5_percent: 30.0,
top_10_percent: 45.0,
top_holders: vec![],
};
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
None,
None,
Some(distribution),
);
let has_holder_warning = report.indicators.iter().any(|i| {
matches!(i, RiskIndicator::LowHolderCount { count } if *count == 50)
});
assert!(has_holder_warning);
}
#[test]
fn test_calculate_risk_score() {
let checker = TokenSafetyChecker::new();
let score = checker.calculate_risk_score(&[]);
assert_eq!(score, 0);
let score = checker.calculate_risk_score(&[RiskIndicator::ActiveMintAuthority]);
assert_eq!(score, 20);
let score = checker.calculate_risk_score(&[
RiskIndicator::ActiveMintAuthority,
RiskIndicator::ActiveFreezeAuthority,
]);
assert_eq!(score, 45);
let score = checker.calculate_risk_score(&[
RiskIndicator::ActiveMintAuthority,
RiskIndicator::ActiveFreezeAuthority,
RiskIndicator::HighHolderConcentration { top_10_percent: 95.0 },
RiskIndicator::LowHolderCount { count: 5 },
RiskIndicator::NotInitialized,
]);
assert_eq!(score, 100);
}
#[test]
fn test_multiple_red_flags_critical() {
let checker = TokenSafetyChecker::new();
let authority = Pubkey::new_unique();
let distribution = HolderDistribution {
holder_count: 20, top_1_percent: 60.0,
top_5_percent: 85.0,
top_10_percent: 95.0, top_holders: vec![],
};
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
Some(authority), Some(authority), Some(distribution),
);
assert_eq!(report.risk_level, TokenRiskLevel::Critical);
assert!(report.risk_score >= 70);
assert!(report.should_avoid());
assert!(report.indicators.len() >= 3);
}
#[test]
fn test_risk_level_thresholds() {
let checker = TokenSafetyChecker::new();
assert_eq!(checker.score_to_level(0), TokenRiskLevel::Safe);
assert_eq!(checker.score_to_level(20), TokenRiskLevel::Safe);
assert_eq!(checker.score_to_level(21), TokenRiskLevel::Caution);
assert_eq!(checker.score_to_level(40), TokenRiskLevel::Caution);
assert_eq!(checker.score_to_level(41), TokenRiskLevel::Warning);
assert_eq!(checker.score_to_level(70), TokenRiskLevel::Warning);
assert_eq!(checker.score_to_level(71), TokenRiskLevel::Critical);
assert_eq!(checker.score_to_level(100), TokenRiskLevel::Critical);
}
#[test]
fn test_indicator_descriptions() {
let mint_auth = RiskIndicator::ActiveMintAuthority;
assert!(mint_auth.description().contains("print"));
let freeze = RiskIndicator::ActiveFreezeAuthority;
assert!(freeze.description().contains("freeze"));
let concentration = RiskIndicator::HighHolderConcentration { top_10_percent: 80.0 };
assert!(concentration.description().contains("80.0%"));
let holders = RiskIndicator::LowHolderCount { count: 50 };
assert!(holders.description().contains("50"));
}
#[test]
fn test_report_summary() {
let checker = TokenSafetyChecker::new();
let authority = Pubkey::new_unique();
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
Some(authority),
None,
None,
);
assert!(report.summary.contains("Risk Level"));
assert!(report.summary.contains("Mint authority"));
}
#[test]
fn test_custom_thresholds() {
let checker = TokenSafetyChecker::new()
.min_holders(500) .max_concentration(30.0);
let distribution = HolderDistribution {
holder_count: 200, top_1_percent: 10.0,
top_5_percent: 25.0,
top_10_percent: 35.0, top_holders: vec![],
};
let report = checker.analyze_from_data(
mock_mint(),
1_000_000,
9,
None,
None,
Some(distribution),
);
assert!(report.indicators.len() >= 2);
}
}