1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#![allow(clippy::upper_case_acronyms)]

use crate::{CurrencyStore, Error};
use runtime::{FixedPointNumber, FixedPointTraits::*, FixedU128};
use serde::Deserialize;
use std::fmt::{self, Debug};

pub trait ExchangeRate {
    fn invert(self) -> Self;
}

impl ExchangeRate for f64 {
    fn invert(self) -> Self {
        1.0 / self
    }
}

pub trait CurrencyInfo<Currency> {
    fn name(&self, id: &Currency) -> Option<String>;
    fn decimals(&self, id: &Currency) -> Option<u32>;
}

#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Currency {
    #[serde(deserialize_with = "deserialize_as_string")]
    Symbol(String),
    #[serde(deserialize_with = "deserialize_as_tuple")]
    Path(String, String),
}

fn deserialize_as_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;
    let value = String::deserialize(deserializer)?;
    if value.contains('=') {
        return Err(Error::custom("Not string"));
    }
    Ok(value)
}

fn deserialize_as_tuple<'de, D>(deserializer: D) -> Result<(String, String), D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;
    let value = String::deserialize(deserializer)?;
    match value.split('=').collect::<Vec<_>>()[..] {
        [symbol, path] => Ok((symbol.to_string(), path.to_string())),
        _ => Err(Error::custom("Not tuple")),
    }
}

impl Currency {
    pub fn symbol(&self) -> String {
        match self {
            Self::Symbol(symbol) => symbol.to_owned(),
            Self::Path(symbol, _) => symbol.to_owned(),
        }
    }

    pub fn path(&self) -> Option<String> {
        match self {
            Self::Symbol(_) => None,
            Self::Path(_, path) => Some(path.to_owned()),
        }
    }
}

impl PartialEq for Currency {
    fn eq(&self, other: &Self) -> bool {
        // only compare symbols, path may differ
        self.symbol() == other.symbol()
    }
}

impl From<Currency> for String {
    fn from(currency: Currency) -> Self {
        currency.symbol()
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CurrencyPair<Currency> {
    /// This is the currency to **buy** - one unit.
    /// Also known as the "transaction" currency.
    pub base: Currency,
    /// This is the currency to **sell**.
    /// Used to determine the value of the base currency.
    /// Also known as the "counter" currency.
    pub quote: Currency,
}

impl fmt::Display for CurrencyPair<Currency> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.base.symbol(), self.quote.symbol())
    }
}

impl<Currency> From<(Currency, Currency)> for CurrencyPair<Currency> {
    fn from((base, quote): (Currency, Currency)) -> Self {
        CurrencyPair { base, quote }
    }
}

impl<Currency: PartialEq> CurrencyPair<Currency> {
    pub fn contains(&self, currency: &Currency) -> bool {
        &self.base == currency || &self.quote == currency
    }

    pub fn has_shared(&self, currency_pair: &Self) -> bool {
        self.contains(&currency_pair.base) || self.contains(&currency_pair.quote)
    }

    pub fn invert(self) -> Self {
        Self {
            base: self.quote,
            quote: self.base,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CurrencyPairAndPrice<Currency> {
    pub pair: CurrencyPair<Currency>,
    /// Indicates how much of the quote currency is needed to
    /// buy one unit of the base currency.
    ///
    /// ## Example
    /// The quotation BTC/USD = 19037.96 means that 1 BTC can
    /// be exchanged for $19037.96 USD. In this case, BTC is the
    /// base currency and USD is the quote (counter) currency.
    ///
    /// NOTE: this stores the whole unit (i.e. BTC not satoshi)
    pub price: f64,
}

impl fmt::Display for CurrencyPairAndPrice<Currency> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} => {}", self.pair, self.price)
    }
}

impl<Currency: Clone + PartialEq> CurrencyPairAndPrice<Currency> {
    pub fn invert(self) -> Self {
        Self {
            pair: self.pair.invert(),
            price: self.price.invert(),
        }
    }

    /// Calculate the price for the smallest unit of the base currency.
    ///
    /// ## Example
    /// BTC/DOT = 3081
    /// 1 BTC = 3081 DOT
    /// 1 * 10**8 Satoshi = 3081 * 10**10 Planck
    /// 1 Satoshi = 3081 * 10**2 Planck
    /// 308100 = 3081 * (10**10 / 10**8) = 3081 * 10**2
    pub fn exchange_rate<Symbol: Ord + ToString + From<Currency>>(
        &self,
        currency_store: &CurrencyStore<Symbol>,
    ) -> Result<FixedU128, Error> {
        let quote_decimals = currency_store
            .decimals(&self.pair.quote.clone().into())
            .ok_or(Error::InvalidCurrency)?;
        let base_decimals = currency_store
            .decimals(&self.pair.base.clone().into())
            .ok_or(Error::InvalidCurrency)?;
        let conversion_factor =
            FixedU128::checked_from_rational(10_u128.pow(quote_decimals), 10_u128.pow(base_decimals))
                .ok_or(Error::InvalidExchangeRate)?;
        FixedU128::from_float(self.price)
            .checked_mul(&conversion_factor)
            .ok_or(Error::InvalidExchangeRate)
    }

    /// Combines two currency pairs with a common element.
    ///
    /// ## Example
    /// BTC/USD * USD/DOT = BTC/DOT
    /// BTC/USD * DOT/USD = BTC/DOT
    /// BTC/USD * BTC/DOT = USD/DOT
    /// BTC/USD * DOT/BTC = USD/DOT
    pub fn reduce(self, other: Self) -> Self {
        let (left, right) = if self.pair.quote == other.pair.quote {
            // quote is same so invert other
            (self, other.invert())
        } else if self.pair.base == other.pair.base {
            // base is same so invert self
            (self.invert(), other)
        } else if self.pair.base == other.pair.quote {
            // base is the same as quote so invert both
            (self.invert(), other.invert())
        } else {
            (self, other)
        };

        Self {
            pair: CurrencyPair {
                base: left.pair.base,
                quote: right.pair.quote,
            },
            price: left.price * right.price,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::config::CurrencyConfig;

    use super::*;

    #[test]
    fn should_invert_currency_pair_and_price() {
        assert_eq!(
            CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "BTC",
                    quote: "DOT"
                },
                price: 2333.0,
            }
            .invert(),
            CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "DOT",
                    quote: "BTC"
                },
                price: 0.0004286326618088298,
            }
        );
    }

    macro_rules! assert_reduce {
        (
            ($left_base:tt / $left_quote:tt @ $left_price:tt)
            *
            ($right_base:tt / $right_quote:tt @ $right_price:tt)
            =
            ($base:tt / $quote:tt @ $price:tt)
        ) => {{
            assert_eq!(
                CurrencyPairAndPrice {
                    pair: CurrencyPair {
                        base: $left_base,
                        quote: $left_quote
                    },
                    price: $left_price,
                }
                .reduce(CurrencyPairAndPrice {
                    pair: CurrencyPair {
                        base: $right_base,
                        quote: $right_quote
                    },
                    price: $right_price,
                }),
                CurrencyPairAndPrice {
                    pair: CurrencyPair {
                        base: $base,
                        quote: $quote
                    },
                    price: $price,
                }
            );
        }};
    }

    #[test]
    fn should_reduce_currencies() {
        // BTC/USD * USD/DOT = BTC/DOT
        assert_reduce!(("BTC" / "USD" @ 19184.24) * ("USD" / "DOT" @ 0.16071505) = ("BTC" / "DOT" @ 3083.1960908120004));

        // BTC/USD * DOT/USD = BTC/DOT
        assert_reduce!(("BTC" / "USD" @ 19184.24) * ("DOT" / "USD" @ 6.23) = ("BTC" / "DOT" @ 3079.332263242376));

        // BTC/USD * BTC/DOT = USD/DOT
        assert_reduce!(("BTC" / "USD" @ 19184.24) * ("BTC" / "DOT" @ 3081.0) = ("USD" / "DOT" @ 0.1606005763063848));

        // BTC/USD * DOT/BTC = USD/DOT
        assert_reduce!(("BTC" / "USD" @ 19184.24) * ("DOT" / "BTC" @ 0.00032457) = ("USD" / "DOT" @ 0.16060054900429147));

        // BTC/USD * KSM/USD = BTC/KSM
        assert_reduce!(("BTC" / "USD" @ 27356.159557758947) * ("KSM" / "USD" @ 19.743996225593296) = ("BTC" / "KSM" @ 1385.5431922286498));

        // USD/BTC * USD/KSM = BTC/KSM
        assert_reduce!(("USD" / "BTC" @ 3.655107115877481e-5) * ("USD" / "KSM" @ 0.05052177613811538) = ("BTC" / "KSM" @ 1382.2242286321239));
    }

    #[test]
    fn should_reduce_currencies_same() {
        assert_eq!(
            CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "KSM",
                    quote: "USD"
                },
                price: 42.73,
            }
            .reduce(CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "KSM",
                    quote: "USD"
                },
                price: 42.73,
            }),
            CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "KSM",
                    quote: "KSM"
                },
                price: 1.0,
            }
        );
    }

    #[test]
    fn should_calculate_exchange_rate() {
        let mut currency_store = CurrencyStore::new();
        currency_store.insert(
            "BTC",
            CurrencyConfig {
                name: format!("Bitcoin"),
                decimals: 8,
            },
        );
        currency_store.insert(
            "KSM",
            CurrencyConfig {
                name: format!("Kusama"),
                decimals: 12,
            },
        );

        assert_eq!(
            CurrencyPairAndPrice {
                pair: CurrencyPair {
                    base: "BTC",
                    quote: "KSM"
                },
                price: 453.4139805666768,
            }
            .exchange_rate(&currency_store)
            .unwrap(),
            FixedU128::from_inner(4534139805666767667200000)
        );
    }
}