1use std::{
21 fmt::{Debug, Display},
22 hash::{Hash, Hasher},
23 str::FromStr,
24};
25
26use nautilus_core::correctness::{
27 CorrectnessResult, CorrectnessResultExt, FAILED, check_nonempty_string, check_valid_string_utf8,
28};
29use serde::{Deserialize, Serialize, Serializer};
30use thiserror::Error;
31use ustr::Ustr;
32
33#[allow(unused_imports)]
34use super::fixed::{FIXED_PRECISION, check_fixed_precision};
35use crate::{currencies::CURRENCY_MAP, deserialization::StringInput, enums::CurrencyType};
36
37#[derive(Clone, Debug, Error, Eq, PartialEq)]
39pub enum CurrencyLookupError {
40 #[error("Failed to acquire lock on `CURRENCY_MAP`: {reason}")]
44 LockFailure {
45 reason: String,
47 },
48 #[error("Unknown currency: {code}")]
50 UnknownCode {
51 code: String,
53 },
54}
55
56#[repr(C)]
60#[derive(Clone, Copy, Eq)]
61#[cfg_attr(
62 feature = "python",
63 pyo3::pyclass(module = "nautilus_trader.model", frozen, eq, hash, from_py_object)
64)]
65#[cfg_attr(
66 feature = "python",
67 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
68)]
69pub struct Currency {
70 pub code: Ustr,
72 pub precision: u8,
74 pub iso4217: u16,
76 pub name: Ustr,
78 pub currency_type: CurrencyType,
80}
81
82impl Currency {
83 pub fn new_checked<T: AsRef<str>>(
96 code: T,
97 precision: u8,
98 iso4217: u16,
99 name: T,
100 currency_type: CurrencyType,
101 ) -> CorrectnessResult<Self> {
102 let code = code.as_ref();
103 let name = name.as_ref();
104 check_valid_string_utf8(code, "code")?;
105 check_nonempty_string(name, "name")?;
106 check_fixed_precision(precision)?;
107 Ok(Self {
108 code: Ustr::from(code),
109 precision,
110 iso4217,
111 name: Ustr::from(name),
112 currency_type,
113 })
114 }
115
116 pub fn new<T: AsRef<str>>(
122 code: T,
123 precision: u8,
124 iso4217: u16,
125 name: T,
126 currency_type: CurrencyType,
127 ) -> Self {
128 Self::new_checked(code, precision, iso4217, name, currency_type).expect_display(FAILED)
129 }
130
131 pub fn register(currency: Self, overwrite: bool) -> CorrectnessResult<()> {
143 let mut map = CURRENCY_MAP.lock();
144
145 #[cfg(feature = "defi")]
146 if let Some(registered) = crate::defi::currency::check_registration(currency)? {
147 map.insert(registered.code.to_string(), registered);
148 return Ok(());
149 }
150
151 if !overwrite && map.contains_key(currency.code.as_str()) {
152 return Ok(());
154 }
155
156 map.insert(currency.code.to_string(), currency);
158 Ok(())
159 }
160
161 pub fn try_from_str(s: &str) -> Option<Self> {
163 let map_guard = CURRENCY_MAP.lock();
164 map_guard.get(s).copied()
165 }
166
167 pub fn is_fiat(code: &str) -> Result<bool, CurrencyLookupError> {
173 let currency = Self::from_str(code)?;
174 Ok(currency.currency_type == CurrencyType::Fiat)
175 }
176
177 pub fn is_crypto(code: &str) -> Result<bool, CurrencyLookupError> {
183 let currency = Self::from_str(code)?;
184 Ok(currency.currency_type == CurrencyType::Crypto)
185 }
186
187 pub fn is_commodity_backed(code: &str) -> Result<bool, CurrencyLookupError> {
194 let currency = Self::from_str(code)?;
195 Ok(currency.currency_type == CurrencyType::CommodityBacked)
196 }
197
198 #[must_use]
209 pub fn get_or_create_crypto<T: AsRef<str>>(code: T) -> Self {
210 let code_str = code.as_ref();
211 Self::try_from_str(code_str).unwrap_or_else(|| {
212 let currency = Self::new(code_str, 8, 0, code_str, CurrencyType::Crypto);
213
214 if let Err(e) = Self::register(currency, false) {
215 log::error!("Failed to register currency '{code_str}': {e}");
216
217 #[cfg(feature = "defi")]
218 if let Some((registered, _)) = crate::defi::currency::lookup(currency.code) {
219 return registered;
220 }
221 }
222
223 currency
224 })
225 }
226
227 #[must_use]
241 pub fn get_or_create_crypto_with_context<T: AsRef<str>>(
242 code: T,
243 context: Option<&str>,
244 ) -> Self {
245 let trimmed = code.as_ref().trim();
246 let ctx = context.unwrap_or("unknown");
247
248 if trimmed.is_empty() {
249 log::warn!(
250 "get_or_create_crypto_with_context called with empty code (context: {ctx}), using USDT as fallback"
251 );
252 return Self::USDT();
253 }
254
255 Self::get_or_create_crypto(trimmed)
256 }
257}
258
259impl PartialEq for Currency {
260 fn eq(&self, other: &Self) -> bool {
261 self.code == other.code
262 }
263}
264
265impl Hash for Currency {
266 fn hash<H: Hasher>(&self, state: &mut H) {
267 self.code.hash(state);
268 }
269}
270
271impl Debug for Currency {
272 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273 write!(
274 f,
275 "{}(code='{}', precision={}, iso4217={}, name='{}', currency_type={})",
276 stringify!(Currency),
277 self.code,
278 self.precision,
279 self.iso4217,
280 self.name,
281 self.currency_type,
282 )
283 }
284}
285
286impl Display for Currency {
287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288 write!(f, "{}", self.code)
289 }
290}
291
292impl FromStr for Currency {
293 type Err = CurrencyLookupError;
294
295 fn from_str(s: &str) -> Result<Self, Self::Err> {
296 let map_guard = CURRENCY_MAP.lock();
297 map_guard
298 .get(s)
299 .copied()
300 .ok_or_else(|| CurrencyLookupError::UnknownCode {
301 code: s.to_string(),
302 })
303 }
304}
305
306impl<T: AsRef<str>> From<T> for Currency {
307 fn from(value: T) -> Self {
308 match Self::from_str(value.as_ref()) {
309 Ok(currency) => currency,
310 Err(e) => panic!("{FAILED}: {e}"),
311 }
312 }
313}
314
315impl Serialize for Currency {
316 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
317 where
318 S: Serializer,
319 {
320 self.code.serialize(serializer)
321 }
322}
323
324impl<'de> Deserialize<'de> for Currency {
325 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
326 where
327 D: serde::Deserializer<'de>,
328 {
329 let StringInput(currency_str) = Deserialize::deserialize(deserializer)?;
330 Self::from_str(currency_str.as_ref()).map_err(serde::de::Error::custom)
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use std::str::FromStr;
337
338 use rstest::rstest;
339
340 use crate::{
341 enums::CurrencyType,
342 types::{Currency, CurrencyLookupError},
343 };
344
345 #[rstest]
346 fn test_debug() {
347 let currency = Currency::AUD();
348 assert_eq!(
349 format!("{currency:?}"),
350 "Currency(code='AUD', precision=2, iso4217=36, name='Australian dollar', currency_type=FIAT)".to_string()
351 );
352 }
353
354 #[rstest]
355 fn test_display() {
356 let currency = Currency::AUD();
357 assert_eq!(format!("{currency}"), "AUD");
358 }
359
360 #[rstest]
361 #[should_panic(expected = "code")]
362 fn test_invalid_currency_code() {
363 let _ = Currency::new("", 2, 840, "United States dollar", CurrencyType::Fiat);
364 }
365
366 #[cfg(not(feature = "defi"))]
367 #[rstest]
368 #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
369 fn test_invalid_precision() {
370 let _ = Currency::new("USD", 19, 840, "United States dollar", CurrencyType::Fiat);
372 }
373
374 #[cfg(feature = "defi")]
375 #[rstest]
376 #[should_panic(expected = "Condition failed: `precision` exceeded maximum `WEI_PRECISION`")]
377 fn test_invalid_precision() {
378 let _ = Currency::new("ETH", 19, 0, "Ethereum", CurrencyType::Crypto);
380 }
381
382 #[rstest]
383 fn test_register_no_overwrite() {
384 let currency1 = Currency::new("TEST1", 2, 999, "Test Currency 1", CurrencyType::Fiat);
385 Currency::register(currency1, false).unwrap();
386
387 let currency2 = Currency::new(
388 "TEST1",
389 2,
390 999,
391 "Test Currency 2 Updated",
392 CurrencyType::Fiat,
393 );
394 Currency::register(currency2, false).unwrap();
395
396 let found = Currency::try_from_str("TEST1").unwrap();
397 assert_eq!(found.name.as_str(), "Test Currency 1");
398 }
399
400 #[rstest]
401 fn test_register_with_overwrite() {
402 let currency1 = Currency::new("TEST2", 2, 998, "Test Currency 2", CurrencyType::Fiat);
403 Currency::register(currency1, false).unwrap();
404
405 let currency2 = Currency::new(
406 "TEST2",
407 2,
408 998,
409 "Test Currency 2 Overwritten",
410 CurrencyType::Fiat,
411 );
412 Currency::register(currency2, true).unwrap();
413
414 let found = Currency::try_from_str("TEST2").unwrap();
415 assert_eq!(found.name.as_str(), "Test Currency 2 Overwritten");
416 }
417
418 #[rstest]
419 fn test_new_for_fiat() {
420 let currency = Currency::new("AUD", 2, 36, "Australian dollar", CurrencyType::Fiat);
421 assert_eq!(currency, currency);
422 assert_eq!(currency.code.as_str(), "AUD");
423 assert_eq!(currency.precision, 2);
424 assert_eq!(currency.iso4217, 36);
425 assert_eq!(currency.name.as_str(), "Australian dollar");
426 assert_eq!(currency.currency_type, CurrencyType::Fiat);
427 }
428
429 #[rstest]
430 fn test_new_for_crypto() {
431 let currency = Currency::new("ETH", 8, 0, "Ether", CurrencyType::Crypto);
432 assert_eq!(currency, currency);
433 assert_eq!(currency.code.as_str(), "ETH");
434 assert_eq!(currency.precision, 8);
435 assert_eq!(currency.iso4217, 0);
436 assert_eq!(currency.name.as_str(), "Ether");
437 assert_eq!(currency.currency_type, CurrencyType::Crypto);
438 }
439
440 #[rstest]
441 fn test_try_from_str_valid() {
442 let test_currency = Currency::new("TEST", 2, 999, "Test Currency", CurrencyType::Fiat);
443 Currency::register(test_currency, true).unwrap();
444
445 let currency = Currency::try_from_str("TEST");
446 assert!(currency.is_some());
447 assert_eq!(currency.unwrap(), test_currency);
448 }
449
450 #[rstest]
451 fn test_try_from_str_invalid() {
452 let invalid_currency = Currency::try_from_str("INVALID");
453 assert!(invalid_currency.is_none());
454 }
455
456 #[rstest]
457 fn test_equality() {
458 let currency1 = Currency::new("USD", 2, 840, "United States dollar", CurrencyType::Fiat);
459 let currency2 = Currency::new("USD", 2, 840, "United States dollar", CurrencyType::Fiat);
460 assert_eq!(currency1, currency2);
461 }
462
463 #[rstest]
464 fn test_currency_partial_eq_only_checks_code() {
465 let c1 = Currency::new("ABC", 2, 999, "Currency ABC", CurrencyType::Fiat);
466 let c2 = Currency::new("ABC", 8, 100, "Completely Different", CurrencyType::Crypto);
467
468 assert_eq!(c1, c2, "Should be equal if 'code' is the same");
469 }
470
471 #[rstest]
472 fn test_is_fiat() {
473 let currency = Currency::new("TESTFIAT", 2, 840, "Test Fiat", CurrencyType::Fiat);
474 Currency::register(currency, true).unwrap();
475
476 let result = Currency::is_fiat("TESTFIAT");
477 assert!(result.is_ok());
478 assert!(
479 result.unwrap(),
480 "Expected TESTFIAT to be recognized as fiat"
481 );
482 }
483
484 #[rstest]
485 fn test_is_crypto() {
486 let currency = Currency::new("TESTCRYPTO", 8, 0, "Test Crypto", CurrencyType::Crypto);
487 Currency::register(currency, true).unwrap();
488
489 let result = Currency::is_crypto("TESTCRYPTO");
490 assert!(result.is_ok());
491 assert!(
492 result.unwrap(),
493 "Expected TESTCRYPTO to be recognized as crypto"
494 );
495 }
496
497 #[rstest]
498 fn test_is_commodity_backed() {
499 let currency = Currency::new("TESTGOLD", 5, 0, "Test Gold", CurrencyType::CommodityBacked);
500 Currency::register(currency, true).unwrap();
501
502 let result = Currency::is_commodity_backed("TESTGOLD");
503 assert!(result.is_ok());
504 assert!(
505 result.unwrap(),
506 "Expected TESTGOLD to be recognized as commodity-backed"
507 );
508 }
509
510 #[rstest]
511 fn test_is_fiat_unknown_currency() {
512 let err = Currency::is_fiat("NON_EXISTENT").unwrap_err();
513 assert_eq!(
514 err,
515 CurrencyLookupError::UnknownCode {
516 code: "NON_EXISTENT".to_string()
517 }
518 );
519 assert_eq!(err.to_string(), "Unknown currency: NON_EXISTENT");
520 }
521
522 #[rstest]
523 #[case(Currency::is_fiat)]
524 #[case(Currency::is_crypto)]
525 #[case(Currency::is_commodity_backed)]
526 fn test_currency_classification_unknown_code_returns_typed_error(
527 #[case] classify: fn(&str) -> Result<bool, CurrencyLookupError>,
528 ) {
529 let err = classify("UNKNOWN_CLASSIFICATION").unwrap_err();
530
531 assert_eq!(
532 err,
533 CurrencyLookupError::UnknownCode {
534 code: "UNKNOWN_CLASSIFICATION".to_string()
535 }
536 );
537 assert_eq!(err.to_string(), "Unknown currency: UNKNOWN_CLASSIFICATION");
538 }
539
540 #[rstest]
541 fn test_from_str_unknown_code_returns_typed_error() {
542 let err = Currency::from_str("UNKNOWN_FROM_STR").unwrap_err();
543
544 assert_eq!(
545 err,
546 CurrencyLookupError::UnknownCode {
547 code: "UNKNOWN_FROM_STR".to_string()
548 }
549 );
550 assert_eq!(err.to_string(), "Unknown currency: UNKNOWN_FROM_STR");
551 }
552
553 #[rstest]
554 fn test_currency_lookup_error_legacy_lock_failure_display() {
555 let err = CurrencyLookupError::LockFailure {
556 reason: "legacy lock failure".to_string(),
557 };
558
559 assert_eq!(
560 err,
561 CurrencyLookupError::LockFailure {
562 reason: "legacy lock failure".to_string()
563 }
564 );
565 assert_eq!(
566 err.to_string(),
567 "Failed to acquire lock on `CURRENCY_MAP`: legacy lock failure"
568 );
569 }
570
571 #[rstest]
572 #[should_panic(expected = "Unknown currency: UNKNOWN_FROM_PANIC")]
573 fn test_from_unknown_code_panics_with_display_error() {
574 let _: Currency = Currency::from("UNKNOWN_FROM_PANIC");
575 }
576
577 #[rstest]
578 fn test_serialization_deserialization() {
579 let currency = Currency::USD();
580 let serialized = serde_json::to_string(¤cy).unwrap();
581 let deserialized: Currency = serde_json::from_str(&serialized).unwrap();
582 assert_eq!(currency, deserialized);
583 }
584
585 #[rstest]
586 fn test_get_or_create_crypto_existing() {
587 let currency = Currency::get_or_create_crypto("BTC");
589 assert_eq!(currency.code.as_str(), "BTC");
590 assert_eq!(currency.currency_type, CurrencyType::Crypto);
591 }
592
593 #[rstest]
594 fn test_get_or_create_crypto_new() {
595 let currency = Currency::get_or_create_crypto("NEWCOIN");
597 assert_eq!(currency.code.as_str(), "NEWCOIN");
598 assert_eq!(currency.precision, 8);
599 assert_eq!(currency.iso4217, 0);
600 assert_eq!(currency.name.as_str(), "NEWCOIN");
601 assert_eq!(currency.currency_type, CurrencyType::Crypto);
602
603 let retrieved = Currency::try_from_str("NEWCOIN");
605 assert!(retrieved.is_some());
606 assert_eq!(retrieved.unwrap(), currency);
607 }
608
609 #[rstest]
610 fn test_get_or_create_crypto_idempotent() {
611 let currency1 = Currency::get_or_create_crypto("TESTCOIN");
613
614 let currency2 = Currency::get_or_create_crypto("TESTCOIN");
616
617 assert_eq!(currency1, currency2);
618 }
619
620 #[rstest]
621 fn test_get_or_create_crypto_with_ustr() {
622 use ustr::Ustr;
623
624 let code = Ustr::from("USTRCOIN");
626 let currency = Currency::get_or_create_crypto(code);
627 assert_eq!(currency.code.as_str(), "USTRCOIN");
628 assert_eq!(currency.currency_type, CurrencyType::Crypto);
629 }
630
631 #[rstest]
632 fn test_get_or_create_crypto_with_context_valid() {
633 let result = Currency::get_or_create_crypto_with_context("BTC", Some("test context"));
634 assert_eq!(result, Currency::BTC());
635 }
636
637 #[rstest]
638 fn test_get_or_create_crypto_with_context_empty() {
639 let result = Currency::get_or_create_crypto_with_context("", Some("test context"));
640 assert_eq!(result, Currency::USDT());
641 }
642
643 #[rstest]
644 fn test_get_or_create_crypto_with_context_whitespace() {
645 let result = Currency::get_or_create_crypto_with_context(" ", Some("test context"));
646 assert_eq!(result, Currency::USDT());
647 }
648
649 #[rstest]
650 fn test_get_or_create_crypto_with_context_unknown() {
651 let result = Currency::get_or_create_crypto_with_context("NEWCOIN", Some("test context"));
653 assert_eq!(result.code.as_str(), "NEWCOIN");
654 assert_eq!(result.precision, 8);
655 }
656}