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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Module for Bailsman pallet interest rate calculations

use eq_primitives::{currency::Currency, InterestRateError};
use eq_utils::{eq_ensure, log::eq_log, math::MathUtils};
#[allow(unused_imports)]
use frame_support::{debug, ensure};
use sp_arithmetic::{FixedI64, FixedPointNumber};
use sp_std::{cmp, fmt::Debug, prelude::*};

/// Struct for storing total collateral and debt values for account or
/// accounts group
#[derive(Debug)]
pub struct TotalBalance {
    issuance: FixedI64,
    debt: FixedI64,
}

impl TotalBalance {
    pub fn new(issuance: FixedI64, debt: FixedI64) -> TotalBalance {
        TotalBalance { issuance, debt }
    }
}

/// Pallet settings object. Settings are stored in pallet's [`Trait`](../trait.Trait.html)
pub struct InterestRateSettings {
    lover_bound: FixedI64,
    upper_bound: FixedI64,
    target: FixedI64,
    n_sigma: FixedI64,
    rho: FixedI64,
    alpha: FixedI64,
}

impl InterestRateSettings {
    pub fn new(
        lover_bound: FixedI64,
        upper_bound: FixedI64,
        target: FixedI64,
        n_sigma: FixedI64,
        rho: FixedI64,
        alpha: FixedI64,
    ) -> InterestRateSettings {
        InterestRateSettings {
            lover_bound,
            upper_bound,
            target,
            n_sigma,
            rho,
            alpha,
        }
    }
}

/// Interface for receiving data required for Bailsman pallet fee calculations
pub trait InterestRateDataSource {
    type AccountId: Debug;

    /// Gets bailsman fee settings
    fn get_settings() -> InterestRateSettings;

    /// Gets `currency` price from oracle
    fn get_price(currency: &Currency) -> Result<FixedI64, sp_runtime::DispatchError>;

    /// Gets covariance value for currencies `c1` and `c2` from Volatility Pallet
    fn get_covariance(c1: &Currency, c2: &Currency) -> FixedI64;

    /// Gets aggregated USD value of collateral and debt for all bailsmen
    fn get_bailsman_total_balance(currency: &Currency) -> TotalBalance;

    /// Gets `SignedBalance` for `account_id` in given `currency` and converts
    /// it into `TotalBalance` used for calculations in Bailsman Pallet
    fn get_balance(account_id: &Self::AccountId, currency: &Currency) -> TotalBalance;

    /// Gets `TotalAggregates` for all user accounts and converts it into
    /// `TotalBalance` used for calculations in Bailsman Pallet
    fn get_total_balance(currency: &Currency) -> TotalBalance;
}

/// Struct for storing and transferring associated collateral, debt and
/// bail values
#[derive(PartialEq, Debug)]
pub struct Cdb<T> {
    pub collateral: T,
    pub debt: T,
    pub bail: T,
}

/// Gets vector of currencies used in system
fn currencies() -> Vec<Currency> {
    Currency::iterator_with_usd().map(|x| *x).collect()
}

/// Iterates over a vector of currencies, returning a vector of corresponding
/// currency prices
fn prices<T: InterestRateDataSource>(
    currencies: &Vec<Currency>,
) -> Result<Vec<FixedI64>, InterestRateError> {
    let prices = currencies.into_iter().map(|x| T::get_price(&x)).collect();

    match prices {
        Ok(ps) => Ok(ps),
        Err(e) => {
            debug::error!("{}:{}. Unable to fetch price: {:?}", file!(), line!(), e);
            eq_log!("Unable to fetch price: {:?}", e);
            Err(InterestRateError::ExternalError)
        }
    }
}

/// Multiplies values it 2-member tuples iterator and returns their sum
fn sumproduct<'a, I>(items: I) -> FixedI64
where
    I: Iterator<Item = (&'a FixedI64, &'a FixedI64)>,
{
    items.fold(FixedI64::zero(), |acc, (&x, &y)| acc + x * y)
}

/// Returns total USD value of some balances (represented as `FixedI64` vector
/// `xs`) using their corresponding prices vector `prices`
pub fn total_usd(xs: &Vec<FixedI64>, prices: &Vec<FixedI64>) -> FixedI64 {
    sumproduct(xs.into_iter().zip(prices.into_iter()))
}

/// Service function for volatility calculations
pub fn total_weights(
    xs: &Vec<FixedI64>,
    prices: &Vec<FixedI64>,
    total: FixedI64,
) -> Result<Vec<FixedI64>, InterestRateError> {
    eq_ensure!(
        total != FixedI64::zero(),
        InterestRateError::ValueError,
        "{}:{}. Total is equal to zero.",
        file!(),
        line!()
    );
    Ok(xs
        .into_iter()
        .zip(prices.into_iter())
        .map(move |(&x, &p)| (x * p) / total)
        .collect())
}

/// Gets all covariance values for `currency` from Volatility Pallet
fn covariance_column<T: InterestRateDataSource>(
    currency: Currency,
    currencies: &Vec<Currency>,
) -> Vec<FixedI64> {
    currencies
        .into_iter()
        .map(|c| T::get_covariance(&currency, &c))
        .collect()
}

/// Service function for volatility calculations
pub fn total_interim(
    weights: &Vec<FixedI64>,
    covariance_matrix: &Vec<Vec<FixedI64>>,
) -> Vec<FixedI64> {
    covariance_matrix
        .into_iter()
        .map(|covs| sumproduct(covs.into_iter().zip(weights.into_iter())))
        .collect()
}

/// Aggregates `Cdb` for given `currencies`
fn currency_totals<T: InterestRateDataSource>(currencies: &Vec<Currency>) -> Cdb<Vec<FixedI64>> {
    let total_bails: Vec<_> = (&currencies)
        .into_iter()
        .map(|x| T::get_bailsman_total_balance(&x).issuance)
        .collect();
    let total_bail_debts: Vec<_> = (&currencies)
        .into_iter()
        .map(|x| T::get_bailsman_total_balance(&x).debt)
        .collect();
    let total_collaterals: Vec<_> = (&currencies)
        .into_iter()
        .map(|x| T::get_total_balance(x).issuance)
        .zip((&total_bails).into_iter())
        .map(|(all, &bail)| all - bail)
        .collect();
    let total_debts: Vec<_> = (&currencies)
        .into_iter()
        .map(|x| T::get_total_balance(x).debt)
        .zip((&total_bail_debts).into_iter())
        .map(|(all, &bail)| all - bail)
        .collect();

    Cdb::<_> {
        collateral: total_collaterals,
        debt: total_debts,
        bail: total_bails,
    }
}

/// Gets all bailsmen debts and calculates their total USD value
fn totals_bailsman_debt<T: InterestRateDataSource>(
    prices: &Vec<FixedI64>,
    currencies: &Vec<Currency>,
) -> FixedI64 {
    let total_bail_debt: Vec<_> = (&currencies)
        .into_iter()
        .map(|x| T::get_bailsman_total_balance(&x).debt)
        .collect();
    return total_usd(&total_bail_debt, &prices);
}

/// Calculates total USD values for `Cdb` `currency_totals`
fn totals(prices: &Vec<FixedI64>, currency_totals: &Cdb<Vec<FixedI64>>) -> Cdb<FixedI64> {
    let total_issuance = total_usd(&currency_totals.collateral, &prices);
    let total_debt = total_usd(&currency_totals.debt, &prices);
    let total_bail = total_usd(&currency_totals.bail, &prices);

    Cdb::<_> {
        collateral: total_issuance,
        debt: total_debt,
        bail: total_bail,
    }
}

/// Calculates bailsman and collateral pools volatilities
pub fn aggregate_portfolio_volatilities<T: InterestRateDataSource>(
    _currencies: &Vec<Currency>,
    prices: &Vec<FixedI64>,
    currency_totals: &Cdb<Vec<FixedI64>>,
    covariance_matrix: &Vec<Vec<FixedI64>>,
) -> Result<Cdb<FixedI64>, InterestRateError> {
    let totals = totals(prices, currency_totals);

    let total_collateral_weights =
        total_weights(&currency_totals.collateral, &prices, totals.collateral)?;
    let total_debt_weights = total_weights(&currency_totals.debt, &prices, totals.debt)?;
    let total_bail_weights = total_weights(&currency_totals.bail, &prices, totals.bail)?;

    let total_collateral_interim = total_interim(&total_collateral_weights, covariance_matrix);
    let total_debt_interim = total_interim(&total_debt_weights, covariance_matrix);
    let total_bail_interim = total_interim(&total_bail_weights, covariance_matrix);

    let total_collateral_volatility = sumproduct(
        (&total_collateral_weights)
            .into_iter()
            .zip((&total_collateral_interim).into_iter()),
    )
    .sqrt()
    .map_err(|_| {
        debug::error!("{}:{}", file!(), line!());
        InterestRateError::MathError
    })?;
    let total_debt_volatility = sumproduct(
        (&total_debt_weights)
            .into_iter()
            .zip((&total_debt_interim).into_iter()),
    )
    .sqrt()
    .map_err(|_| {
        debug::error!("{}:{}", file!(), line!());
        InterestRateError::MathError
    })?;
    let total_bail_volatility = sumproduct(
        (&total_bail_weights)
            .into_iter()
            .zip((&total_bail_interim).into_iter()),
    )
    .sqrt()
    .map_err(|_| {
        debug::error!("{}:{}", file!(), line!());
        InterestRateError::MathError
    })?;

    Ok(Cdb::<_> {
        collateral: total_collateral_volatility,
        debt: total_debt_volatility,
        bail: total_bail_volatility,
    })
}

/// System risk model calculations
pub fn scale<T: InterestRateDataSource>(
    currencies: &Vec<Currency>,
    prices: &Vec<FixedI64>,
    covariance_matrix: &Vec<Vec<FixedI64>>,
) -> Result<FixedI64, InterestRateError> {
    let InterestRateSettings {
        lover_bound,
        upper_bound,
        target: _,
        n_sigma,
        rho,
        alpha: _,
    } = T::get_settings();

    let currency_totals = currency_totals::<T>(&currencies);

    let totals = totals(&prices, &currency_totals);

    let total_volatilities = aggregate_portfolio_volatilities::<T>(
        currencies,
        prices,
        &currency_totals,
        covariance_matrix,
    )?;

    let collateral_discount = n_sigma * total_volatilities.collateral;
    let debt_discount = n_sigma * total_volatilities.debt;
    let bail_discount = n_sigma * total_volatilities.bail;

    let totals_bailsman_debt = totals_bailsman_debt::<T>(&prices, &currencies);

    let insufficient_collateral = cmp::max(
        FixedI64::zero(),
        totals.debt * (FixedI64::one() + debt_discount)
            - totals.collateral * (FixedI64::one() - collateral_discount),
    );
    let stressed_bail = (totals.bail - totals_bailsman_debt) * (FixedI64::one() - bail_discount);
    let scale: FixedI64;

    if stressed_bail <= FixedI64::zero() {
        scale = upper_bound;
    } else {
        scale = cmp::max(
            cmp::min(
                (insufficient_collateral / stressed_bail)
                    .pow(rho)
                    .map_err(|_| {
                        debug::error!("{}:{}", file!(), line!());
                        InterestRateError::MathError
                    })?,
                upper_bound,
            ),
            lover_bound,
        );
    }
    Ok(scale)
}

/// Gets account `TotalBalance` for given currencies as a tuple (vec of issuances, vec of debts)
pub fn balances<T: InterestRateDataSource>(
    account_id: &T::AccountId,
    currencies: &Vec<Currency>,
) -> (Vec<FixedI64>, Vec<FixedI64>) {
    let bs: Vec<TotalBalance> = currencies
        .into_iter()
        .map(|x| T::get_balance(account_id, x))
        .collect();

    (
        bs.iter().map(|x| x.issuance).collect(),
        bs.iter().map(|x| x.debt).collect(),
    )
}

/// LTV calculation errors
#[derive(PartialEq)]
pub enum LtvError {
    /// Cannot calculate LTV because account doesn't have any collateral
    ZeroCollateral,
    /// Cannot calculate LTV because account doesn't have debt
    ZeroDebt,
}

/// Calculates LTV for given vectors of collaterals and debts
pub fn ltv(
    positive_balances: &Vec<FixedI64>,
    negative_balances: &Vec<FixedI64>,
    prices: &Vec<FixedI64>,
) -> Result<FixedI64, LtvError> {
    let collateral = sumproduct(positive_balances.into_iter().zip(prices.into_iter()));
    let debt = sumproduct(negative_balances.into_iter().zip(prices.into_iter()));

    match (collateral, debt) {
        (c, _d) if c == FixedI64::zero() => {
            debug::error!("{}:{}. Collateral is zero.", file!(), line!());
            Err(LtvError::ZeroCollateral)
        }
        // do not log ZeroDebt error, because it can be norm case in fee scenario
        (_c, d) if d == FixedI64::zero() => Err(LtvError::ZeroDebt),
        (c, d) => Ok(c / d),
    }
}

/// Calculates volatility for `positive_balances` - given set of collateral values
pub fn borrower_volatility(
    prices: &Vec<FixedI64>,
    positive_balances: &Vec<FixedI64>,
    covariance_matrix: &Vec<Vec<FixedI64>>,
) -> Result<FixedI64, InterestRateError> {
    let total = sumproduct(prices.into_iter().zip(positive_balances.into_iter()));

    let weights = total_weights(positive_balances, prices, total)?;
    let interim = total_interim(&weights, covariance_matrix);

    let volatility = sumproduct((&weights).into_iter().zip((&interim).into_iter()))
        .sqrt()
        .map_err(|_| {
            debug::error!("{}:{}", file!(), line!());
            InterestRateError::MathError
        })?;

    Ok(volatility)
}

/// Calculates Bailsman fee interest rate for `account_id`
pub fn interest_rate<T: InterestRateDataSource>(
    account_id: &T::AccountId,
) -> Result<FixedI64, InterestRateError> {
    let settings = T::get_settings();
    let alpha = settings.alpha;
    let currencies = currencies();
    let prices = prices::<T>(&currencies)?;

    let covariance_matrix: Vec<_> = (&currencies)
        .into_iter()
        .map(|&c1| covariance_column::<T>(c1, &currencies))
        .collect();

    let scale = scale::<T>(&currencies, &prices, &covariance_matrix)?;

    let (positive_balances, negative_balances) = balances::<T>(account_id, &currencies);

    let ltv = ltv(&positive_balances, &negative_balances, &prices).map_err(|err| {
        // zero debt is only about 0 fee, not an error
        if err != LtvError::ZeroDebt {
            debug::error!("{}:{}", file!(), line!());
        }
        InterestRateError::ValueError
    })?;
    let sigma = borrower_volatility(&prices, &positive_balances, &covariance_matrix)?;

    let interest_rate = alpha
        * (ltv / (ltv - FixedI64::one()) * (scale * sigma).sqr()
            / FixedI64::saturating_from_integer(2)
            * FixedI64::saturating_from_integer(365));

    eq_log!("interest_rate({:?}) = alpha({:?}) * (ltv({:?} / (ltv - 1)) * (scale({:?}) * sigma({:?}))^2 / 2 * 365",
        interest_rate, alpha, ltv, scale, sigma
    );
    Ok(interest_rate)
}