Jacky Gu

Solana开发笔记: 如何在anchor程序中验证metadata数据

01 Jan 2025 Share to

如何在anchor程序中验证metadata数据

验证token name

要求字符数不超过MAX_NAME_LENGTH,只允许子母、数字、常用特殊字符(punctuation)和空格,以及emoji。

pub fn is_valid_token_name(name: &str) -> bool {
  // Check basic constraints
  !name.is_empty() && 
  name.chars().count() <= MAX_NAME_LENGTH && 
  name.chars().all(|c| 
      c.is_ascii_alphanumeric() || 
      c.is_ascii_punctuation() || 
      c.is_whitespace() || 
      is_emoji(c)
  ) &&
  name.trim().len() > 0 && // Prevent names with only whitespace
  !name.contains("  ") // Prevent multiple consecutive spaces
}

验证symbol

要求字符数不超过MAX_SYMBOL_LENGTH,只允许子母、数字以及emoji,不允许空格。

pub fn is_valid_token_symbol(symbol: &str) -> bool {
  !symbol.is_empty() && 
  symbol.chars().count() <= MAX_SYMBOL_LENGTH && 
  symbol.chars().all(|c| 
      c.is_ascii_alphanumeric() || 
      is_emoji(c) // Only one emoji allowed, otherwise, the mint account can not be created
  ) &&
  symbol.trim().len() > 0 && // Prevent symbols with only whitespace
  !symbol.contains(' ') // Prevent multiple consecutive spaces
}

验证uri

要求uri长度不能超过MAX_URI_LENGTH,并且需要是https://http://开头

pub fn is_valid_token_uri(uri: &str) -> bool {
  !uri.is_empty() && 
  uri.chars().count() <= MAX_URI_LENGTH && 
  (uri.starts_with("https://") || uri.starts_with("http://"))
}

关于验证是否是emoji的方法

// Helper function to check if a character is an emoji
fn is_emoji(c: char) -> bool {
  // Unicode ranges for common emoji
  let emoji_ranges = [
      0x1F600..=0x1F64F,  // Emoticons
      0x1F300..=0x1F5FF,  // Misc Symbols and Pictographs
      0x1F680..=0x1F6FF,  // Transport and Map Symbols
      0x2600..=0x26FF,    // Misc symbols
      0x2700..=0x27BF,    // Dingbats
      0xFE00..=0xFE0F,    // Variation Selectors
      0x1F900..=0x1F9FF,  // Supplemental Symbols and Pictographs
      0x1F1E6..=0x1F1FF,  // Regional indicator symbols
  ];
  emoji_ranges.iter().any(|range| range.contains(&(c as u32)))
}