Skip to main content

lean_ctx_protocol/
money.rs

1use serde::{Deserialize, Serialize};
2
3/// ISO 4217 currency code.
4pub type CurrencyCode = String;
5
6/// Sub-cent precision money. NOT floating point.
7/// Rounding to legal minor units happens only at invoice time.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub struct MoneyV1 {
10    pub currency: CurrencyCode,
11    pub coefficient: i128,
12    pub scale: u8,
13}
14
15#[cfg(test)]
16mod tests {
17    use crate::MoneyV1;
18
19    #[test]
20    fn serialization_round_trip() {
21        let money = MoneyV1 {
22            currency: "USD".to_owned(),
23            coefficient: 12345,
24            scale: 4,
25        };
26        let json = serde_json::to_string(&money).expect("money should serialize");
27        let decoded: MoneyV1 = serde_json::from_str(&json).expect("money should deserialize");
28        assert_eq!(decoded, money);
29    }
30
31    #[test]
32    fn coefficient_and_scale_represent_sub_cent_value() {
33        let money = MoneyV1 {
34            currency: "USD".to_owned(),
35            coefficient: 1,
36            scale: 3,
37        };
38        assert_eq!(money.coefficient, 1);
39        assert_eq!(money.scale, 3);
40    }
41}