|
| 1 | +use crate::{SUI_COIN_TYPE, SUI_COIN_TYPE_FULL}; |
| 2 | +use primitives::hex::decode_hex; |
| 3 | + |
| 4 | +const SUI_ADDRESS_LENGTH: usize = 32; |
| 5 | + |
| 6 | +pub fn full_coin_type(coin_type: &str) -> String { |
| 7 | + let Some((prefix, rest)) = coin_type.split_once("::") else { |
| 8 | + return coin_type.to_string(); |
| 9 | + }; |
| 10 | + match decode_hex(prefix) { |
| 11 | + Ok(bytes) if bytes.len() <= SUI_ADDRESS_LENGTH => { |
| 12 | + let mut padded = [0u8; SUI_ADDRESS_LENGTH]; |
| 13 | + padded[SUI_ADDRESS_LENGTH - bytes.len()..].copy_from_slice(&bytes); |
| 14 | + format!("0x{}::{rest}", hex::encode(padded)) |
| 15 | + } |
| 16 | + _ => coin_type.to_string(), |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +pub fn coin_type_matches(a: &str, b: &str) -> bool { |
| 21 | + full_coin_type(a) == full_coin_type(b) |
| 22 | +} |
| 23 | + |
| 24 | +pub fn is_sui_coin(coin_type: &str) -> bool { |
| 25 | + coin_type == SUI_COIN_TYPE || coin_type == SUI_COIN_TYPE_FULL |
| 26 | +} |
| 27 | + |
| 28 | +#[cfg(test)] |
| 29 | +mod tests { |
| 30 | + use super::*; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn test_full_coin_type() { |
| 34 | + assert_eq!( |
| 35 | + full_coin_type("0x2::sui::SUI"), |
| 36 | + "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI" |
| 37 | + ); |
| 38 | + assert_eq!( |
| 39 | + full_coin_type("2::sui::SUI"), |
| 40 | + "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI" |
| 41 | + ); |
| 42 | + assert_eq!( |
| 43 | + full_coin_type("0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI"), |
| 44 | + "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI" |
| 45 | + ); |
| 46 | + assert_eq!(full_coin_type("0xabc"), "0xabc"); |
| 47 | + assert_eq!(full_coin_type("not-a-type::coin::COIN"), "not-a-type::coin::COIN"); |
| 48 | + } |
| 49 | + |
| 50 | + #[test] |
| 51 | + fn test_coin_type_matches() { |
| 52 | + assert!(coin_type_matches("0x2::sui::SUI", "0x2::sui::SUI")); |
| 53 | + assert!(coin_type_matches("0x2::sui::SUI", "2::sui::SUI")); |
| 54 | + assert!(coin_type_matches("2::sui::SUI", "0x2::sui::SUI")); |
| 55 | + assert!(coin_type_matches( |
| 56 | + "0x2::sui::SUI", |
| 57 | + "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI" |
| 58 | + )); |
| 59 | + assert!(!coin_type_matches("0x2::sui::SUI", "0x3::token::TOKEN")); |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_is_sui_coin() { |
| 64 | + assert!(is_sui_coin(SUI_COIN_TYPE)); |
| 65 | + assert!(is_sui_coin(SUI_COIN_TYPE_FULL)); |
| 66 | + assert!(!is_sui_coin("0x3::token::TOKEN")); |
| 67 | + } |
| 68 | +} |
0 commit comments