parse.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. use std::iter::FromIterator;
  2. use std::str::FromStr;
  3. use sha2::{Digest, Sha256};
  4. use crate::{
  5. serial::{deserialize, serialize},
  6. util::{NetworkName, SolTokenList},
  7. Error, Result,
  8. };
  9. // hash the external token ID and NetworkName param.
  10. // if fails, change the last 4 bytes and hash it again. keep repeating until it works.
  11. pub fn generate_id(tkn_str: &str, network: &NetworkName) -> Result<jubjub::Fr> {
  12. let mut id_string = network.to_string();
  13. id_string.push_str(tkn_str);
  14. let mut data: Vec<u8> = serialize(&id_string);
  15. let token_id = match deserialize::<jubjub::Fr>(&data) {
  16. Ok(v) => v,
  17. Err(_) => {
  18. let mut counter = 0;
  19. loop {
  20. data.truncate(28);
  21. let serialized_counter = serialize(&counter);
  22. data.extend(serialized_counter.iter());
  23. let mut hasher = Sha256::new();
  24. hasher.update(&data);
  25. let hash = hasher.finalize();
  26. let token_id = deserialize::<jubjub::Fr>(&hash);
  27. if token_id.is_err() {
  28. counter += 1;
  29. continue;
  30. }
  31. return Ok(token_id.unwrap());
  32. }
  33. }
  34. };
  35. Ok(token_id)
  36. }
  37. pub fn assign_id(network: &str, token: &str, _tokenlist: &SolTokenList) -> Result<String> {
  38. let token = token.to_lowercase();
  39. let _token = token.as_str();
  40. match NetworkName::from_str(network)? {
  41. #[cfg(feature = "sol")]
  42. NetworkName::Solana => {
  43. // (== 44) can represent a Solana base58 token mint address
  44. let id = if _token.len() == 44 {
  45. _token.to_string()
  46. } else {
  47. symbol_to_id(_token, _tokenlist)?
  48. };
  49. Ok(id)
  50. }
  51. #[cfg(feature = "btc")]
  52. NetworkName::Bitcoin => {
  53. let id = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa".to_string();
  54. Ok(id)
  55. }
  56. _ => Err(Error::NotSupportedNetwork),
  57. }
  58. }
  59. pub fn symbol_to_id(token: &str, tokenlist: &SolTokenList) -> Result<String> {
  60. let vec: Vec<char> = token.chars().collect();
  61. let mut counter = 0;
  62. for c in vec {
  63. if c.is_alphabetic() {
  64. counter += 1;
  65. }
  66. }
  67. if counter == token.len() {
  68. if let Some(id) = tokenlist.search_id(token)? {
  69. Ok(id)
  70. } else {
  71. Err(Error::TokenParseError)
  72. }
  73. } else {
  74. Ok(token.to_string())
  75. }
  76. }
  77. fn is_digit(c: char) -> bool {
  78. ('0'..='9').contains(&c)
  79. }
  80. fn char_eq(a: char, b: char) -> bool {
  81. a == b
  82. }
  83. pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Result<u64> {
  84. let mut s: Vec<char> = amount.to_string().chars().collect();
  85. // Get rid of the decimal point:
  86. let point: usize;
  87. if let Some(p) = amount.find('.') {
  88. s.remove(p);
  89. point = p;
  90. } else {
  91. point = s.len();
  92. }
  93. // Only digits should remain
  94. for i in &s {
  95. if !is_digit(*i) {
  96. return Err(Error::ParseFailed("Found non-digits"));
  97. }
  98. }
  99. // Add digits to the end if there are too few:
  100. let actual_places = s.len() - point;
  101. if actual_places < decimal_places {
  102. s.extend(vec!['0'; decimal_places - actual_places])
  103. }
  104. // Remove digits from the end if there are too many:
  105. let mut round = false;
  106. if actual_places > decimal_places {
  107. let end = point + decimal_places;
  108. for i in &s[end..s.len()] {
  109. if !char_eq(*i, '0') {
  110. round = true;
  111. break;
  112. }
  113. }
  114. s.truncate(end);
  115. }
  116. if strict && round {
  117. return Err(Error::ParseFailed("Would end up rounding while strict"));
  118. }
  119. // Convert to an integer
  120. let number = u64::from_str(&String::from_iter(&s))?;
  121. // Round and return
  122. if round && number == u64::MAX {
  123. return Err(Error::ParseFailed("u64 overflow"));
  124. }
  125. Ok(number + round as u64)
  126. }
  127. pub fn encode_base10(amount: u64, decimal_places: usize) -> String {
  128. let mut s: Vec<char> = format!("{:0width$}", amount, width = 1 + decimal_places)
  129. .chars()
  130. .collect();
  131. s.insert(s.len() - decimal_places, '.');
  132. String::from_iter(&s)
  133. .trim_end_matches('0')
  134. .trim_end_matches('.')
  135. .to_string()
  136. }
  137. pub fn truncate(amount: u64, decimals: u16, token_decimals: u16) -> Result<u64> {
  138. let mut amount: Vec<char> = amount.to_string().chars().collect();
  139. if token_decimals > decimals {
  140. if amount.len() <= (token_decimals - decimals) as usize {
  141. return Ok(0);
  142. }
  143. amount.truncate(amount.len() - (token_decimals - decimals) as usize);
  144. }
  145. if token_decimals < decimals {
  146. amount.resize(amount.len() + (decimals - token_decimals) as usize, '0');
  147. }
  148. let amount = u64::from_str(&String::from_iter(amount))?;
  149. Ok(amount)
  150. }
  151. #[allow(unused_imports)]
  152. mod tests {
  153. use super::{decode_base10, encode_base10, truncate};
  154. #[test]
  155. fn test_decode_base10() {
  156. assert_eq!(124, decode_base10("12.33", 1, false).unwrap());
  157. assert_eq!(1233000, decode_base10("12.33", 5, false).unwrap());
  158. assert_eq!(1200000, decode_base10("12.", 5, false).unwrap());
  159. assert_eq!(1200000, decode_base10("12", 5, false).unwrap());
  160. assert!(decode_base10("12.33", 1, true).is_err());
  161. }
  162. #[test]
  163. fn test_encode_base10() {
  164. assert_eq!("23.4321111", &encode_base10(234321111, 7));
  165. assert_eq!("23432111.1", &encode_base10(234321111, 1));
  166. assert_eq!("234321.1", &encode_base10(2343211, 1));
  167. assert_eq!("2343211", &encode_base10(2343211, 0));
  168. assert_eq!("0.00002343", &encode_base10(2343, 8));
  169. }
  170. #[test]
  171. fn test_truncate() {
  172. // Token decimals is equal to 8
  173. assert_eq!(100, truncate(100, 8, 8).unwrap());
  174. assert_eq!(12, truncate(12, 8, 8).unwrap());
  175. // Token decimals is bigger than 8
  176. assert_eq!(100000000, truncate(1000000000, 8, 9).unwrap());
  177. assert_eq!(10, truncate(100, 8, 9).unwrap());
  178. assert_eq!(1, truncate(12, 8, 9).unwrap());
  179. assert_eq!(10, truncate(102, 8, 9).unwrap());
  180. assert_eq!(0, truncate(1, 8, 9).unwrap());
  181. assert_eq!(1, truncate(100000000, 8, 16).unwrap());
  182. assert_eq!(10, truncate(100000000, 8, 15).unwrap());
  183. assert_eq!(0, truncate(100000000, 8, 17).unwrap());
  184. assert_eq!(0, truncate(10, 8, 16).unwrap());
  185. // Token decimals is less than 8
  186. assert_eq!(1000, truncate(100, 8, 7).unwrap());
  187. assert_eq!(12000, truncate(120, 8, 6).unwrap());
  188. assert_eq!(1000000, truncate(100, 8, 4).unwrap());
  189. // token decimals is 0
  190. assert_eq!(00000000, truncate(0, 8, 0).unwrap());
  191. assert_eq!(100000000, truncate(1, 8, 0).unwrap());
  192. //
  193. // reverse truncate
  194. //
  195. // Token decimals is less than decimals
  196. assert_eq!(1000000000, truncate(100000000, 9, 8).unwrap());
  197. assert_eq!(100000000, truncate(10000000, 9, 8).unwrap());
  198. assert_eq!(100, truncate(10, 9, 8).unwrap());
  199. assert_eq!(10, truncate(1, 9, 8).unwrap());
  200. assert_eq!(100, truncate(10, 9, 8).unwrap());
  201. assert_eq!(0, truncate(0, 9, 8).unwrap());
  202. assert_eq!(100000000, truncate(1, 16, 8).unwrap());
  203. assert_eq!(100000000, truncate(10, 15, 8).unwrap());
  204. assert_eq!(0, truncate(0, 17, 8).unwrap());
  205. // Token decimals is bigger than decimals
  206. assert_eq!(100, truncate(1000, 7, 8).unwrap());
  207. assert_eq!(120, truncate(12000, 6, 8).unwrap());
  208. assert_eq!(100, truncate(1000000, 4, 8).unwrap());
  209. // token decimals is 0
  210. assert_eq!(0, truncate(00000000, 0, 8).unwrap());
  211. assert_eq!(1, truncate(100000000, 0, 8).unwrap());
  212. }
  213. }