1use std::{collections::HashMap, fmt::Display};
17
18use nautilus_core::{Params, UUID4, UnixNanos};
19use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
20
21use crate::{
22 enums::AccountType,
23 identifiers::{AccountId, InstrumentId},
24 types::{AccountBalance, Currency, MarginBalance, balance::WalletAccountBalances},
25};
26
27pub const BALANCES_SNAPSHOT_COMPLETE_INFO_KEY: &str = "balances_snapshot_complete";
29
30#[repr(C)]
37#[derive(Debug, Clone, Deserialize)]
38#[cfg_attr(
39 feature = "python",
40 pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
41)]
42#[cfg_attr(
43 feature = "python",
44 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
45)]
46pub struct AccountState {
47 pub account_id: AccountId,
49 pub account_type: AccountType,
51 pub base_currency: Option<Currency>,
53 pub balances: Vec<AccountBalance>,
55 pub margins: Vec<MarginBalance>,
57 pub is_reported: bool,
60 pub event_id: UUID4,
62 pub ts_event: UnixNanos,
64 pub ts_init: UnixNanos,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub info: Option<Params>,
69}
70
71impl Serialize for AccountState {
72 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73 where
74 S: Serializer,
75 {
76 let field_count = 9 + usize::from(self.info.is_some());
77 let mut state = serializer.serialize_struct("AccountState", field_count)?;
78 state.serialize_field("account_id", &self.account_id)?;
79 state.serialize_field("account_type", &self.account_type)?;
80 state.serialize_field("base_currency", &self.base_currency)?;
81 if self.account_type == AccountType::Wallet {
82 state.serialize_field("balances", &WalletAccountBalances::new(&self.balances))?;
83 } else {
84 state.serialize_field("balances", &self.balances)?;
85 }
86 state.serialize_field("margins", &self.margins)?;
87 state.serialize_field("is_reported", &self.is_reported)?;
88 state.serialize_field("event_id", &self.event_id)?;
89 state.serialize_field("ts_event", &self.ts_event)?;
90 state.serialize_field("ts_init", &self.ts_init)?;
91 if let Some(info) = &self.info {
92 state.serialize_field("info", info)?;
93 }
94 state.end()
95 }
96}
97
98impl AccountState {
99 #[expect(clippy::too_many_arguments)]
101 #[must_use]
102 pub fn new(
103 account_id: AccountId,
104 account_type: AccountType,
105 balances: Vec<AccountBalance>,
106 margins: Vec<MarginBalance>,
107 is_reported: bool,
108 event_id: UUID4,
109 ts_event: UnixNanos,
110 ts_init: UnixNanos,
111 base_currency: Option<Currency>,
112 ) -> Self {
113 Self {
114 account_id,
115 account_type,
116 base_currency,
117 balances,
118 margins,
119 is_reported,
120 event_id,
121 ts_event,
122 ts_init,
123 info: None,
124 }
125 }
126
127 #[must_use]
129 pub fn with_info(mut self, info: Option<Params>) -> Self {
130 self.info = info;
131 self
132 }
133
134 #[must_use]
145 pub fn has_same_balances_and_margins(&self, other: &Self) -> bool {
146 if self.balances.len() != other.balances.len() || self.margins.len() != other.margins.len()
148 {
149 return false;
150 }
151
152 let self_balances: HashMap<Currency, &AccountBalance> = self
154 .balances
155 .iter()
156 .map(|balance| (balance.currency, balance))
157 .collect();
158
159 let other_balances: HashMap<Currency, &AccountBalance> = other
160 .balances
161 .iter()
162 .map(|balance| (balance.currency, balance))
163 .collect();
164
165 for (currency, self_balance) in &self_balances {
167 match other_balances.get(currency) {
168 Some(other_balance) => {
169 if self_balance != other_balance {
170 return false;
171 }
172 }
173 None => return false, }
175 }
176
177 let self_margins: HashMap<(Option<InstrumentId>, Currency), &MarginBalance> = self
181 .margins
182 .iter()
183 .map(|margin| ((margin.instrument_id, margin.currency), margin))
184 .collect();
185
186 let other_margins: HashMap<(Option<InstrumentId>, Currency), &MarginBalance> = other
187 .margins
188 .iter()
189 .map(|margin| ((margin.instrument_id, margin.currency), margin))
190 .collect();
191
192 for (key, self_margin) in &self_margins {
194 match other_margins.get(key) {
195 Some(other_margin) => {
196 if self_margin != other_margin {
197 return false;
198 }
199 }
200 None => return false, }
202 }
203
204 true
205 }
206}
207
208impl Display for AccountState {
209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210 write!(
211 f,
212 "{}(account_id={}, account_type={}, base_currency={}, is_reported={}, balances=[{}], margins=[{}], event_id={})",
213 stringify!(AccountState),
214 self.account_id,
215 self.account_type,
216 self.base_currency.map_or_else(
217 || "None".to_string(),
218 |base_currency| format!("{}", base_currency.code)
219 ),
220 self.is_reported,
221 self.balances
222 .iter()
223 .map(|b| format!("{b}"))
224 .collect::<Vec<String>>()
225 .join(", "),
226 self.margins
227 .iter()
228 .map(|m| format!("{m}"))
229 .collect::<Vec<String>>()
230 .join(", "),
231 self.event_id
232 )
233 }
234}
235
236impl PartialEq for AccountState {
237 fn eq(&self, other: &Self) -> bool {
238 self.account_id == other.account_id
239 && self.account_type == other.account_type
240 && self.event_id == other.event_id
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 #[cfg(feature = "defi")]
247 use std::process::Command;
248
249 use indexmap::IndexMap;
250 use nautilus_core::{Params, UUID4, UnixNanos};
251 use rstest::rstest;
252 use serde_json::json;
253
254 use crate::{
255 enums::{AccountType, CurrencyType},
256 events::{
257 AccountState,
258 account::stubs::{cash_account_state, margin_account_state},
259 },
260 identifiers::{AccountId, InstrumentId},
261 types::{AccountBalance, Currency, MarginBalance, Money},
262 };
263
264 #[rstest]
265 fn test_equality() {
266 let cash_account_state_1 = cash_account_state();
267 let cash_account_state_2 = cash_account_state();
268 assert_eq!(cash_account_state_1, cash_account_state_2);
269 }
270
271 #[rstest]
272 fn test_display_cash_account_state(cash_account_state: AccountState) {
273 let display = format!("{cash_account_state}");
274 assert_eq!(
275 display,
276 "AccountState(account_id=SIM-001, account_type=CASH, base_currency=USD, is_reported=true, \
277 balances=[AccountBalance(total=1525000.00 USD, locked=25000.00 USD, free=1500000.00 USD)], \
278 margins=[], event_id=16578139-a945-4b65-b46c-bc131a15d8e7)"
279 );
280 }
281
282 #[rstest]
283 fn test_display_margin_account_state(margin_account_state: AccountState) {
284 let display = format!("{margin_account_state}");
285 assert_eq!(
286 display,
287 "AccountState(account_id=SIM-001, account_type=MARGIN, base_currency=USD, is_reported=true, \
288 balances=[AccountBalance(total=1525000.00 USD, locked=25000.00 USD, free=1500000.00 USD)], \
289 margins=[MarginBalance(initial=5000.00 USD, maintenance=20000.00 USD, instrument_id=BTCUSDT.COINBASE)], \
290 event_id=16578139-a945-4b65-b46c-bc131a15d8e7)"
291 );
292 }
293
294 #[rstest]
295 fn test_has_same_balances_and_margins_when_identical() {
296 let state1 = cash_account_state();
297 let state2 = cash_account_state();
298 assert!(state1.has_same_balances_and_margins(&state2));
299 }
300
301 #[rstest]
302 fn test_has_same_balances_and_margins_when_different_balance_amounts() {
303 let state1 = cash_account_state();
304 let mut state2 = cash_account_state();
305 let usd = Currency::USD();
307 let different_balance = AccountBalance::new(
308 Money::new(2_000_000.0, usd),
309 Money::new(50000.0, usd),
310 Money::new(1_950_000.0, usd),
311 );
312 state2.balances = vec![different_balance];
313 assert!(!state1.has_same_balances_and_margins(&state2));
314 }
315
316 #[rstest]
317 fn test_has_same_balances_and_margins_when_different_balance_currencies() {
318 let state1 = cash_account_state();
319 let mut state2 = cash_account_state();
320 let eur = Currency::EUR();
322 let different_balance = AccountBalance::new(
323 Money::new(1_525_000.0, eur),
324 Money::new(25000.0, eur),
325 Money::new(1_500_000.0, eur),
326 );
327 state2.balances = vec![different_balance];
328 assert!(!state1.has_same_balances_and_margins(&state2));
329 }
330
331 #[rstest]
332 fn test_has_same_balances_and_margins_when_missing_balance() {
333 let state1 = cash_account_state();
334 let mut state2 = cash_account_state();
335 let eur = Currency::EUR();
337 let additional_balance = AccountBalance::new(
338 Money::new(1_000_000.0, eur),
339 Money::new(0.0, eur),
340 Money::new(1_000_000.0, eur),
341 );
342 state2.balances.push(additional_balance);
343 assert!(!state1.has_same_balances_and_margins(&state2));
344 }
345
346 #[rstest]
347 fn test_has_same_balances_and_margins_when_different_margin_amounts() {
348 let state1 = margin_account_state();
349 let mut state2 = margin_account_state();
350 let usd = Currency::USD();
352 let instrument_id = InstrumentId::from("BTCUSDT.COINBASE");
353 let different_margin = MarginBalance::new(
354 Money::new(10000.0, usd),
355 Money::new(40000.0, usd),
356 Some(instrument_id),
357 );
358 state2.margins = vec![different_margin];
359 assert!(!state1.has_same_balances_and_margins(&state2));
360 }
361
362 #[rstest]
363 fn test_has_same_balances_and_margins_when_different_margin_instruments() {
364 let state1 = margin_account_state();
365 let mut state2 = margin_account_state();
366 let usd = Currency::USD();
368 let different_instrument_id = InstrumentId::from("ETHUSDT.BINANCE");
369 let different_margin = MarginBalance::new(
370 Money::new(5000.0, usd),
371 Money::new(20000.0, usd),
372 Some(different_instrument_id),
373 );
374 state2.margins = vec![different_margin];
375 assert!(!state1.has_same_balances_and_margins(&state2));
376 }
377
378 #[rstest]
379 fn test_has_same_balances_and_margins_when_missing_margin() {
380 let state1 = margin_account_state();
381 let mut state2 = margin_account_state();
382 let usd = Currency::USD();
384 let additional_instrument_id = InstrumentId::from("ETHUSDT.BINANCE");
385 let additional_margin = MarginBalance::new(
386 Money::new(3000.0, usd),
387 Money::new(15000.0, usd),
388 Some(additional_instrument_id),
389 );
390 state2.margins.push(additional_margin);
391 assert!(!state1.has_same_balances_and_margins(&state2));
392 }
393
394 #[rstest]
395 fn test_has_same_balances_and_margins_with_empty_collections() {
396 let account_id = AccountId::new("TEST-001");
397 let event_id = UUID4::new();
398 let ts_event = UnixNanos::from(1);
399 let ts_init = UnixNanos::from(2);
400
401 let state1 = AccountState::new(
402 account_id,
403 AccountType::Cash,
404 vec![], vec![], true,
407 event_id,
408 ts_event,
409 ts_init,
410 Some(Currency::USD()),
411 );
412
413 let state2 = AccountState::new(
414 account_id,
415 AccountType::Cash,
416 vec![], vec![], true,
419 UUID4::new(), UnixNanos::from(3), UnixNanos::from(4),
422 Some(Currency::USD()),
423 );
424
425 assert!(state1.has_same_balances_and_margins(&state2));
426 }
427
428 #[rstest]
429 fn test_has_same_balances_and_margins_with_multiple_balances_and_margins() {
430 let account_id = AccountId::new("TEST-001");
431 let event_id = UUID4::new();
432 let ts_event = UnixNanos::from(1);
433 let ts_init = UnixNanos::from(2);
434
435 let usd = Currency::USD();
436 let eur = Currency::EUR();
437 let btc_instrument = InstrumentId::from("BTCUSDT.COINBASE");
438 let eth_instrument = InstrumentId::from("ETHUSDT.BINANCE");
439
440 let balances = vec![
441 AccountBalance::new(
442 Money::new(1_000_000.0, usd),
443 Money::new(0.0, usd),
444 Money::new(1_000_000.0, usd),
445 ),
446 AccountBalance::new(
447 Money::new(500_000.0, eur),
448 Money::new(10000.0, eur),
449 Money::new(490_000.0, eur),
450 ),
451 ];
452
453 let margins = vec![
454 MarginBalance::new(
455 Money::new(5000.0, usd),
456 Money::new(20000.0, usd),
457 Some(btc_instrument),
458 ),
459 MarginBalance::new(
460 Money::new(3000.0, usd),
461 Money::new(15000.0, usd),
462 Some(eth_instrument),
463 ),
464 ];
465
466 let state1 = AccountState::new(
467 account_id,
468 AccountType::Margin,
469 balances.clone(),
470 margins.clone(),
471 true,
472 event_id,
473 ts_event,
474 ts_init,
475 Some(usd),
476 );
477
478 let state2 = AccountState::new(
479 account_id,
480 AccountType::Margin,
481 balances,
482 margins,
483 true,
484 UUID4::new(), UnixNanos::from(3), UnixNanos::from(4),
487 Some(usd),
488 );
489
490 assert!(state1.has_same_balances_and_margins(&state2));
491 }
492
493 fn account_state_with_info() -> AccountState {
494 let mut info = IndexMap::new();
495 info.insert("total_wallet_balance".to_string(), json!(1525.0_f64));
496 info.insert("available_balance".to_string(), json!(1500.0_f64));
497 AccountState::new(
498 AccountId::new("SIM-001"),
499 AccountType::Cash,
500 vec![],
501 vec![],
502 true,
503 UUID4::new(),
504 UnixNanos::default(),
505 UnixNanos::default(),
506 Some(Currency::USD()),
507 )
508 .with_info(Some(Params::new(info)))
509 }
510
511 #[rstest]
512 fn test_new_defaults_info_to_none() {
513 let state = cash_account_state();
514 assert!(state.info.is_none());
515 }
516
517 #[rstest]
518 fn test_with_info_attaches_params() {
519 let state = account_state_with_info();
520 let info = state.info.expect("info should be set");
521 assert_eq!(info.get_f64("total_wallet_balance"), Some(1525.0));
522 assert_eq!(info.get_f64("available_balance"), Some(1500.0));
523 assert_eq!(info.get_f64("missing"), None);
524 }
525
526 #[rstest]
527 fn test_serde_round_trips_info() {
528 let state = account_state_with_info();
529 let serialized = serde_json::to_string(&state).expect("serialize");
530 let deserialized: AccountState = serde_json::from_str(&serialized).expect("deserialize");
531 let info = deserialized.info.expect("info should round-trip");
532 assert_eq!(info.get_f64("total_wallet_balance"), Some(1525.0));
533 assert_eq!(info.get_f64("available_balance"), Some(1500.0));
534 }
535
536 #[rstest]
537 fn test_serde_back_compatible_without_info() {
538 let state = cash_account_state();
542 let mut value = serde_json::to_value(&state)
543 .expect("serialize")
544 .as_object()
545 .cloned()
546 .unwrap();
547 value.remove("info");
548 let deserialized: AccountState =
549 serde_json::from_value(serde_json::Value::Object(value)).expect("deserialize legacy");
550 assert!(deserialized.info.is_none());
551 }
552
553 #[rstest]
554 fn test_cash_account_state_exact_usd_roundtrip() {
555 let total = Money::from_str_exact("1.0001 USD").unwrap();
556 let locked = Money::from_str_exact("0.000001 USD").unwrap();
557 let free = Money::from_str_exact("1.000099 USD").unwrap();
558 let balance = AccountBalance::new_checked(total, locked, free).unwrap();
559
560 let state = AccountState::new(
561 AccountId::new("EXACT-001"),
562 AccountType::Cash,
563 vec![balance],
564 vec![],
565 true,
566 UUID4::new(),
567 UnixNanos::from(123),
568 UnixNanos::from(456),
569 Some(Currency::USD()),
570 );
571 let json = serde_json::to_value(&state).unwrap();
572 let restored: AccountState = serde_json::from_value(json.clone()).unwrap();
573 let msgpack = rmp_serde::to_vec_named(&state).unwrap();
574 let restored_msgpack: AccountState = rmp_serde::from_slice(&msgpack).unwrap();
575
576 assert_eq!(json["balances"][0]["total"], "1.0001 USD");
577 assert_eq!(json["balances"][0]["locked"], "0.000001 USD");
578 assert_eq!(json["balances"][0]["free"], "1.000099 USD");
579
580 for restored in [restored, restored_msgpack] {
581 assert_eq!(restored.balances[0].total, total);
582 assert_eq!(restored.balances[0].locked, locked);
583 assert_eq!(restored.balances[0].free, free);
584 assert_eq!(serde_json::to_value(restored).unwrap(), json);
585 }
586 }
587
588 #[rstest]
589 #[case(AccountType::Cash, false)]
590 #[case(AccountType::Margin, false)]
591 #[case(AccountType::Betting, false)]
592 #[case(AccountType::Wallet, true)]
593 fn test_registered_account_balance_keeps_legacy_fields(
594 #[case] account_type: AccountType,
595 #[case] has_wallet_identity: bool,
596 ) {
597 let currency = Currency::USD();
598 let total = Money::from("10.25 USD");
599 let state = AccountState::new(
600 AccountId::new("SERDE-001"),
601 account_type,
602 vec![AccountBalance::new(total, Money::zero(currency), total)],
603 vec![],
604 true,
605 UUID4::new(),
606 UnixNanos::from(1),
607 UnixNanos::from(2),
608 None,
609 );
610
611 let value = serde_json::to_value(&state).expect("serialize account state");
612 let balance = &value["balances"][0];
613 let restored: AccountState =
614 serde_json::from_value(value.clone()).expect("deserialize account state");
615
616 assert_eq!(balance["currency"], "USD");
617 assert_eq!(balance["total"], "10.25 USD");
618 assert_eq!(balance["locked"], "0.00 USD");
619 assert_eq!(balance["free"], "10.25 USD");
620 assert_eq!(
621 balance.get("currency_identity").is_some(),
622 has_wallet_identity
623 );
624 assert_eq!(restored.balances[0].total.raw(), total.raw());
625 assert_currency_identity(restored.balances[0].currency, currency);
626 }
627
628 #[rstest]
629 fn test_wallet_account_state_rejects_unaligned_raw_balance() {
630 let currency = Currency::USD();
631 let total = Money::from_raw(1, currency);
632 let state = AccountState::new(
633 AccountId::new("WALLET-SERDE-INVALID"),
634 AccountType::Wallet,
635 vec![AccountBalance::new(total, Money::zero(currency), total)],
636 vec![],
637 true,
638 UUID4::new(),
639 UnixNanos::from(1),
640 UnixNanos::from(2),
641 None,
642 );
643
644 let error = serde_json::to_string(&state).unwrap_err();
645
646 assert!(
647 error
648 .to_string()
649 .contains("is not aligned to currency precision 2"),
650 "was: {error}"
651 );
652 }
653
654 #[rstest]
655 fn test_wallet_account_state_rejects_inconsistent_exact_balance() {
656 let currency = Currency::USD();
657 let total = Money::from("10.25 USD");
658 let state = AccountState::new(
659 AccountId::new("WALLET-SERDE-CORRUPT"),
660 AccountType::Wallet,
661 vec![AccountBalance::new(total, Money::zero(currency), total)],
662 vec![],
663 true,
664 UUID4::new(),
665 UnixNanos::from(1),
666 UnixNanos::from(2),
667 None,
668 );
669 let mut value = serde_json::to_value(&state).expect("serialize account state");
670 value["balances"][0]["free_minor"] = json!("999");
671
672 let error = serde_json::from_value::<AccountState>(value).unwrap_err();
673
674 assert!(
675 error
676 .to_string()
677 .contains("`total` (10.25 USD) - `locked` (0.00 USD) != `free` (9.99 USD)"),
678 "was: {error}"
679 );
680 }
681
682 #[rstest]
683 fn test_wallet_account_state_rejects_same_code_currency_identity_mismatch() {
684 let balance_currency =
685 Currency::new("ENG729D", 6, 0, "Balance token", CurrencyType::Crypto);
686 let money_currency = Currency::new("ENG729D", 8, 0, "Money token", CurrencyType::Crypto);
687 let total = Money::from_mantissa_exponent(123_456_789, -8, money_currency);
688 let balance = AccountBalance {
689 currency: balance_currency,
690 total,
691 locked: Money::zero(money_currency),
692 free: total,
693 };
694 let state = AccountState::new(
695 AccountId::new("WALLET-SERDE-IDENTITY"),
696 AccountType::Wallet,
697 vec![balance],
698 vec![],
699 true,
700 UUID4::new(),
701 UnixNanos::from(1),
702 UnixNanos::from(2),
703 None,
704 );
705
706 let error = serde_json::to_string(&state).unwrap_err();
707
708 assert!(
709 error
710 .to_string()
711 .contains("Wallet account balance currency identity ENG729D does not match"),
712 "was: {error}"
713 );
714 }
715
716 #[cfg(feature = "defi")]
717 #[rstest]
718 fn test_wallet_account_state_fresh_process_round_trip() {
719 const PAYLOAD_ENV: &str = "NAUTILUS_WALLET_ACCOUNT_STATE_PAYLOAD";
720 const SUCCESS_SENTINEL: &str = "wallet account state fresh-process assertions passed";
721 const TEST_NAME: &str =
722 "events::account::state::tests::test_wallet_account_state_fresh_process_round_trip";
723
724 if let Ok(payload) = std::env::var(PAYLOAD_ENV) {
725 assert!(Currency::try_from_str("ENG729A").is_none());
726 assert!(Currency::try_from_str("ENG729B").is_none());
727
728 let restored: AccountState =
729 serde_json::from_str(&payload).expect("deserialize wallet account state");
730 let expected = wallet_serde_balances();
731
732 assert_eq!(restored.balances.len(), expected.len());
733 for (restored, expected) in restored.balances.iter().zip(&expected) {
734 assert_eq!(restored.total.raw(), expected.total.raw());
735 assert_eq!(restored.locked.raw(), expected.locked.raw());
736 assert_eq!(restored.free.raw(), expected.free.raw());
737 assert_currency_identity(restored.currency, expected.currency);
738 assert_currency_identity(restored.total.currency, expected.total.currency);
739 assert_currency_identity(restored.locked.currency, expected.locked.currency);
740 assert_currency_identity(restored.free.currency, expected.free.currency);
741 }
742 assert!(Currency::try_from_str("ENG729A").is_none());
743 assert!(Currency::try_from_str("ENG729B").is_none());
744 println!("{SUCCESS_SENTINEL}");
745 return;
746 }
747
748 let producer_currency = Currency::new(
749 "ENG729A",
750 6,
751 0,
752 "Producer registered token",
753 CurrencyType::Crypto,
754 );
755 Currency::register(producer_currency, false).expect("register producer-only currency");
756 let state = AccountState::new(
757 AccountId::new("WALLET-SERDE-001"),
758 AccountType::Wallet,
759 wallet_serde_balances(),
760 vec![],
761 true,
762 UUID4::new(),
763 UnixNanos::from(1),
764 UnixNanos::from(2),
765 None,
766 );
767 let payload = serde_json::to_string(&state).expect("serialize wallet account state");
768
769 let output = Command::new(std::env::current_exe().expect("current test executable"))
770 .args(["--exact", TEST_NAME, "--nocapture"])
771 .env(PAYLOAD_ENV, payload)
772 .output()
773 .expect("run fresh-process wallet round-trip");
774
775 assert!(
776 output.status.success(),
777 "fresh-process wallet round-trip failed\nstdout:\n{}\nstderr:\n{}",
778 String::from_utf8_lossy(&output.stdout),
779 String::from_utf8_lossy(&output.stderr)
780 );
781 assert!(
782 String::from_utf8_lossy(&output.stdout).contains(SUCCESS_SENTINEL),
783 "fresh-process wallet round-trip did not run child assertions\nstdout:\n{}\nstderr:\n{}",
784 String::from_utf8_lossy(&output.stdout),
785 String::from_utf8_lossy(&output.stderr)
786 );
787 }
788
789 #[cfg(feature = "defi")]
790 fn wallet_serde_balances() -> Vec<AccountBalance> {
791 let eth = Currency::new("ETH", 18, 0, "Ethereum", CurrencyType::Crypto);
792 let registered = Currency::new(
793 "ENG729A",
794 6,
795 0,
796 "Producer registered token",
797 CurrencyType::Crypto,
798 );
799 let unregistered =
800 Currency::new("ENG729B", 8, 0, "Unregistered token", CurrencyType::Crypto);
801 let eth_total = Money::from_raw(1_234_567_890_123_456_789, eth);
802 let registered_total = Money::from_mantissa_exponent(123_456_789, -6, registered);
803 let unregistered_total = Money::from_mantissa_exponent(98_765_432, -8, unregistered);
804
805 [eth_total, registered_total, unregistered_total]
806 .into_iter()
807 .map(|total| AccountBalance::new(total, Money::zero(total.currency), total))
808 .collect()
809 }
810
811 fn assert_currency_identity(actual: Currency, expected: Currency) {
812 assert_eq!(actual.code, expected.code);
813 assert_eq!(actual.precision, expected.precision);
814 assert_eq!(actual.iso4217, expected.iso4217);
815 assert_eq!(actual.name, expected.name);
816 assert_eq!(actual.currency_type, expected.currency_type);
817 }
818
819 #[rstest]
820 fn test_info_excluded_from_equality() {
821 let base = account_state_with_info();
824 let mut other_info = IndexMap::new();
825 other_info.insert("different".to_string(), json!(1_u64));
826 let other = AccountState {
827 info: Some(Params::new(other_info)),
828 ..base.clone()
829 };
830 assert_eq!(base, other);
831 }
832}