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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! # Equilibrium Bailsman Pallet
//!
//! Equilibrium's Bailsman Pallet is a Substrate module that manages users
//! payment responsibility. Registered bailsmen receive fees payed by users and
//! provide payment security for users positions

#![cfg_attr(not(feature = "std"), no_std)]

mod benchmarking;
mod mock;
pub mod rate;
mod rate_tests;
mod tests;
extern crate alloc;

pub use eq_oracle;
pub use eq_volatility::VolatilityGetter;

use codec::Codec;
use eq_balances::{BalanceChecker, BalanceGetter, EqCurrency, SignedBalance, SignedBalance::*};
use eq_oracle::PriceGetter;
use eq_primitives::{
    currency, currency::Currency::*, currency::*, Aggregates, FeeManager, InterestRateError,
    UserGroup,
};
use eq_utils::{eq_ensure, log::eq_log, ok_or_error, *};
use frame_support::{
    debug, decl_error, decl_event, decl_module, decl_storage,
    dispatch::DispatchResult,
    storage::IterableStorageMap,
    traits::{ExistenceRequirement, Get, UnixTime, WithdrawReason, WithdrawReasons},
    Parameter,
};
use sp_arithmetic::{traits::Saturating, FixedI128, FixedI64, FixedPointNumber};
#[cfg(feature = "std")]
use sp_runtime::serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use sp_runtime::traits::Zero;
use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, MaybeSerializeDeserialize, Member};
use sp_runtime::Permill;
use sp_runtime::{traits::AccountIdConversion, ModuleId};
use sp_std::convert::From;
use sp_std::{collections::btree_map::BTreeMap, default::Default, fmt::Debug, prelude::*};
use system as frame_system;
use system::{self as system, ensure_root, ensure_signed};

/// Substrate pallet configuration trait
pub trait Trait: system::Trait {
    // type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; // todel
    type ModuleId: Get<ModuleId>;

    /// Gets currency prices from oracle
    type PriceGetter: eq_oracle::PriceGetter;
    /// Receives volatility information for currency prices from other pallet
    type VolatilityGetter: VolatilityGetter;
    /// Timestamp provider
    type UnixTime: UnixTime;
    /// Numerical representation of stored balances
    type Balance: Member
        + AtLeast32BitUnsigned
        + MaybeSerializeDeserialize
        + Codec
        + Copy
        + Parameter
        + Default
        + From<u64>
        + Into<u64>;
    /// Gets users balances to calculate fees and check margin calls
    type BalanceGetter: BalanceGetter<Self::AccountId, Self::Balance>;
    /// Used for currency-related operations and calculations
    type EqCurrency: eq_balances::EqCurrency<Self::AccountId, Self::Balance>;
    /// Used to work with `TotalAggregates` storing aggregated collateral and
    /// debt for users and bailsmen
    type Aggregates: Aggregates<Self::AccountId, Self::Balance>;

    /// Pallet setting indicating at which collateral/debt ratio should occur
    /// margin call
    type CriticalLtv: Get<Permill>; // Critical part (if ltv is 105%, part is 05)

    /// Minimal USD value of aggregated bailsman balances
    type MinTempBalanceUsd: Get<Self::Balance>;
    /// Minimum amount of non-Eq balances account should have to register as bailsman
    type MinimalCollaterall: Get<Self::Balance>;
    /// Lower bound for scaling risk model
    type RiskLoverBound: Get<FixedI64>;
    /// Upper bound for scaling risk model
    type RiskUpperBound: Get<FixedI64>;
    /// Defines the target liquidity with default value set to 1 (bailout pool
    /// has to cover stressed collateral losses in full)
    type RiskTarget: Get<FixedI64>;
    /// Number of standard deviations to consider when stress testing
    type RiskNSigma: Get<FixedI64>;
    /// Power coefficient for scale calculations
    type RiskRho: Get<FixedI64>;
    /// Pricing model scaling factor
    type Alpha: Get<FixedI64>;
}

decl_storage! {
    trait Store for Module<T: Trait> as Bailsman {}
    add_extra_genesis {
        build(|_| {
            T::Aggregates::set_usergroup(&Module::<T>::get_account_id(), &UserGroup::Bailsmen, &true);
            T::Aggregates::set_usergroup(&Module::<T>::get_account_id(), &UserGroup::Balances, &true);
        });
    }
}

// todel
// decl_event!(
//     pub enum Event<T> where  <T as system::Trait>::AccountId {
//         AEvent(AccountId),
//     }
// );

decl_error! {
    /// Pallet's errors
    pub enum Error for Module<T: Trait> {
        /// Account has insufficient balance to register as bailsman
        CollaterallMustBeMoreThanMin,
        /// Cannot register account as bailsman because account is already a bailsman
        AlreadyBailsman,  // in future add custom errors for processors
        /// Cannot unregister bailsman account - account is not bailsman
        NotAnBailsman,
        /// Prices received from oracle are outdated
        PricesAreOutdated,
    }
}

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        type Error = Error<T>;

        // fn deposit_event() = default; // todel

        #[weight = 10_000]
        fn reinit(origin) {
            ensure_signed(origin)?;
            Self::_reinit()?;
        }

        /// Transaction for registering `origin` as bailsman. Account must meet collateral
        /// requirements to become a bailsman (see
        /// [`MinimalCollateral`](./trait.Trait.html#associatedtype.MinimalCollaterall))
        #[weight = 10_000]
        pub fn register_bailsman(origin)
        {
            let who = ensure_signed(origin)?;
            Self::_register_bailsman(&who)?;
        }

        /// Transaction to unregister `origin` as bailsman
        #[weight = 10_000]
        pub fn unregister_bailsman(origin)
        {
            let who = ensure_signed(origin)?;
            Self::_unregister_bailsman(&who)?;
        }

        /// Unregister `who` as bailsman by sudo
        #[weight = 10_000]
        pub fn force_unregister_bailsman(origin, who: T::AccountId)
        {
            ensure_root(origin)?;
            Self::_unregister_bailsman(&who)?;
        }


        /// Bailsman module currency transfer that will trigger reinit
        #[weight = 10_000]
        fn transfer(origin, currency: Currency, to: T::AccountId, value: T::Balance) -> DispatchResult
        {
            let from = ensure_signed(origin)?;
            // TODO: update ex fee if reinit not needed
            Self::_reinit()?;
            T::EqCurrency::currency_transfer(currency, &from, &to, value, ExistenceRequirement::AllowDeath, eq_primitives::TransferReason::Common, true)
        }
    }
}

// TODO type for calculation (not u128), check overflow, remove clone
impl<T: Trait> BalanceChecker<T::Balance, T::AccountId> for Module<T> {
    fn can_change_balance(
        who: &T::AccountId,
        currency: &currency::Currency,
        change: &SignedBalance<T::Balance>,
        reason: Option<WithdrawReasons>,
    ) -> Result<bool, sp_runtime::DispatchError> {
        let is_tx_fee = reason
            .map(|rs| rs.contains(WithdrawReason::TransactionPayment))
            .unwrap_or(false);
        // we allow bailsman to pay tx fee even if temp balances are more than min allowed
        if T::Aggregates::in_usergroup(who, &UserGroup::Bailsmen) && !is_tx_fee {
            let bails_balance =
                T::BalanceGetter::get_debt_and_colaterall(&Module::<T>::get_account_id());
            let min_temp_balance_usd = fixedi128_from_balance(T::MinTempBalanceUsd::get());

            if (bails_balance.0 > min_temp_balance_usd) || (bails_balance.1 > min_temp_balance_usd)
            {
                return Ok(false);
            }
        }

        if *who == Self::get_account_id() {
            // no basic transfers from / to bailsman temp balances
            return Ok(false);
        }
        let new_balance = T::BalanceGetter::get_balance(who, currency) + change.clone();

        if let Negative(_) = &new_balance {
            // check only EQ and USD can be less 0
            if *currency != Usd {
                return Ok(false);
            }
        }

        Self::check_ltv(who, change, currency)
    }
}

/// LTV calculations and checks. LTV is a ratio of USD collateral value to
/// USD debt value
pub trait LtvChecker<AccountId, Balance>
where
    Balance: Member + Debug,
{
    /// Calculates  `owner` LTV after his balance would change for `change` amount
    /// of `currency`
    fn calculate_ltv(
        owner: &AccountId,
        change: &SignedBalance<Balance>,
        currency: &currency::Currency,
    ) -> Result<FixedI128, sp_runtime::DispatchError>;

    /// Checks if `owner` LTV would be acceptable after changing its balance
    /// for `change` amount of `currency`
    fn check_ltv(
        owner: &AccountId,
        change: &SignedBalance<Balance>,
        currency: &currency::Currency,
    ) -> Result<bool, sp_runtime::DispatchError>;
}

impl<T: Trait> LtvChecker<T::AccountId, T::Balance> for Module<T> {
    fn calculate_ltv(
        owner: &T::AccountId,
        change: &SignedBalance<T::Balance>,
        acurrency: &currency::Currency,
    ) -> Result<FixedI128, sp_runtime::DispatchError> {
        let mut debt = FixedI128::zero();
        let mut collateral = FixedI128::zero();
        let mut prices_with_errors = false;

        for currency in eq_primitives::currency::Currency::iterator_with_usd() {
            let mut balance = T::BalanceGetter::get_balance(owner, currency);
            if balance.is_zero() && currency != acurrency {
                continue;
            }
            if currency == acurrency {
                balance = balance + change.clone();
            }

            let raw_price = T::PriceGetter::get_price(currency);
            prices_with_errors = prices_with_errors || raw_price.is_err();
            let price = fixedi128_from_fixedi64(raw_price.unwrap_or(FixedI64::zero()));

            match balance {
                Positive(value) => {
                    collateral = collateral + fixedi128_from_balance(value) * price;
                }
                Negative(value) => {
                    eq_ensure!(!raw_price.is_err() && !price.is_zero(), Error::<T>::PricesAreOutdated,
                    "{}:{}. Price is zero or not retrieved. Currency: {:?}, is_error: {:?}, is_zero: {:?}.", 
                    file!(), line!(), currency, raw_price.is_err(), price.is_zero());

                    debt = debt + fixedi128_from_balance(value) * price;
                }
            };
        }

        if debt.is_zero() {
            return Ok(FixedI128::max_value());
        }
        eq_ensure!(
            !prices_with_errors,
            Error::<T>::PricesAreOutdated,
            "{}:{}. Some prices are not retrieved.",
            file!(),
            line!()
        );

        if collateral.is_zero() {
            return Ok(FixedI128::min_value());
        }
        let ltv = collateral / debt;
        Ok(ltv)
    }

    fn check_ltv(
        owner: &T::AccountId,
        change: &SignedBalance<T::Balance>,
        currency: &currency::Currency,
    ) -> Result<bool, sp_runtime::DispatchError> {
        let ltv = Self::calculate_ltv(owner, change, currency)?;
        Ok(ltv >= FixedI128::from(T::CriticalLtv::get()) + FixedI128::one())
    }
}

impl<T: Trait> Module<T> {
    pub fn get_account_id() -> T::AccountId {
        T::ModuleId::get().into_account()
    }

    /// Inner function that distributes Bailsman pallet temp balances
    fn _reinit() -> Result<(), Error<T>> {
        let mut total_collateral_usd = FixedI128::zero();
        let mut total_debt_usd = FixedI128::zero();

        let self_account = Self::get_account_id();

        let self_balances = T::BalanceGetter::iterate_account_balances(&self_account);
        let mut self_balances_usd = FixedI128::from_inner(0);

        for balance in &self_balances {
            let price =
                fixedi128_from_fixedi64(T::PriceGetter::get_price(&balance.0).map_err(|_| {
                    debug::error!("{}:{}.", file!(), line!());
                    Error::<T>::PricesAreOutdated
                })?);

            match balance.1 {
                Positive(value) => {
                    self_balances_usd = self_balances_usd + fixedi128_from_balance(value) * price;
                }
                Negative(value) => {
                    self_balances_usd = self_balances_usd - fixedi128_from_balance(value) * price;
                }
            };
        }

        let min_temp_balance_usd = fixedi128_from_balance(T::MinTempBalanceUsd::get());
        if self_balances_usd.saturating_abs() <= min_temp_balance_usd {
            // no need to reinit
            eq_log!("no need to reinit {:?}", self_balances_usd);
            return Ok(());
        }

        for balances_aggregate in T::Aggregates::iter_total(&UserGroup::Bailsmen) {
            let price = fixedi128_from_fixedi64(
                T::PriceGetter::get_price(&balances_aggregate.0).map_err(|_| {
                    debug::error!("{}:{}.", file!(), line!());
                    Error::<T>::PricesAreOutdated
                })?,
            );
            // unwrap is safe because we already added all prices
            total_collateral_usd = total_collateral_usd
                + fixedi128_from_balance(balances_aggregate.1.collateral) * price;

            eq_log!(
                "total_debt_usd {:?} = total_debt_usd {:?} + balaggr {:?}",
                total_debt_usd + fixedi128_from_balance(balances_aggregate.1.debt) * price,
                total_debt_usd,
                fixedi128_from_balance(balances_aggregate.1.debt) * price
            );
            total_debt_usd =
                total_debt_usd + fixedi128_from_balance(balances_aggregate.1.debt) * price;
        }

        eq_log!(
            "total_collateral_usd {:?} , total_debt_usd {:?}",
            total_collateral_usd,
            total_debt_usd
        );

        let total_usd = total_collateral_usd - total_debt_usd - self_balances_usd;
        eq_log!(
            "total_usd {:?} = total_collateral_usd {:?} - total_debt_usd {:?}",
            total_usd,
            total_collateral_usd,
            total_debt_usd
        );

        for bailsman_acc in T::Aggregates::iter_account(&UserGroup::Bailsmen) {
            if bailsman_acc == self_account {
                continue;
            }
            let bailsman_balances = T::BalanceGetter::iterate_account_balances(&bailsman_acc);
            let mut bailsman_debt_usd = FixedI128::zero();
            let mut bailsman_collat_usd = FixedI128::zero();

            let mut bailsman_balances_cache: BTreeMap<Currency, SignedBalance<T::Balance>> =
                BTreeMap::new();

            for signed_balance in bailsman_balances {
                let price = fixedi128_from_fixedi64(
                    T::PriceGetter::get_price(&signed_balance.0).map_err(|_| {
                        debug::error!("{}:{}.", file!(), line!());
                        Error::<T>::PricesAreOutdated
                    })?,
                );
                bailsman_balances_cache.insert(signed_balance.0, signed_balance.1.clone());
                match signed_balance.1 {
                    SignedBalance::Positive(abalance) => {
                        bailsman_collat_usd =
                            bailsman_collat_usd + fixedi128_from_balance(abalance) * price;
                    }
                    SignedBalance::Negative(abalance) => {
                        bailsman_debt_usd =
                            bailsman_debt_usd + fixedi128_from_balance(abalance) * price;
                    }
                };
            }

            // portion is less than 1, so we can multiply balance by it and cast to Balance
            let portion = (bailsman_collat_usd - bailsman_debt_usd) / total_usd;
            eq_log!(
                "portion {:?} = bailsman_collat_usd {:?} - bailsman_debt_usd {:?}) / total_usd {:?}",
                portion,
                bailsman_collat_usd,
                bailsman_debt_usd,
                total_usd
            );

            #[allow(unused_must_use)]
            for self_balance in &self_balances {
                match self_balance.1 {
                    SignedBalance::Positive(abalance) => {
                        // balance and portion both are > 0, so unsrap is safe
                        // let hui = fixedi128_from_balance(abalance);
                        // eq_log!("hui {:?}", hui);
                        // let pizda: FixedI128 = hui * portion;
                        // eq_log!("pizda {:?}", pizda);
                        // let djigurda: Option<T::Balance> = balance_from_fixedi128(pizda);
                        // eq_log!("djigurda {:?}", djigurda);
                        let amount: T::Balance =
                            balance_from_fixedi128(fixedi128_from_balance(abalance) * portion)
                                .unwrap();

                        T::EqCurrency::currency_transfer(
                            self_balance.0,
                            &self_account,
                            &bailsman_acc,
                            amount,
                            ExistenceRequirement::KeepAlive,
                            eq_primitives::TransferReason::BailsmenRedistribution,
                            false,
                        ); // shoud we expect error here?
                    }
                    SignedBalance::Negative(abalance) => {
                        // balance and portion both are > 0, so unsrap is safe
                        let amount: T::Balance =
                            balance_from_fixedi128(fixedi128_from_balance(abalance) * portion)
                                .unwrap();
                        eq_log!("portion amount - is {:?} {:?}", self_balance.0, amount);

                        T::EqCurrency::currency_transfer(
                            self_balance.0,
                            &bailsman_acc,
                            &self_account,
                            amount,
                            ExistenceRequirement::KeepAlive,
                            eq_primitives::TransferReason::BailsmenRedistribution,
                            false,
                        ); // shoud we expect error here?
                    }
                }
            }
        }
        Ok(())
    }

    /// Inner implementation of bailsman registration
    fn _register_bailsman(who: &T::AccountId) -> Result<(), Error<T>> {
        Self::_reinit()?;
        let existing = T::Aggregates::in_usergroup(who, &UserGroup::Bailsmen);
        eq_ensure!(
            !existing,
            Error::<T>::AlreadyBailsman,
            "{}:{}. Account is already bailsman. Who: {:?}.",
            file!(),
            line!(),
            who
        );

        let mut balances_vec: Vec<(Currency, (T::Balance, T::Balance))> = Vec::new();
        let mut balance_usd: FixedI64 = FixedI64::zero();
        for abalance in T::BalanceGetter::iterate_account_balances(who) {
            let (currency, balance) = abalance;
            match balance {
                Positive(value) => {
                    balances_vec.push((currency, (value.clone(), T::Balance::zero())));
                    let price = T::PriceGetter::get_price(&currency).unwrap_or(FixedI64::zero());
                    let collateral_usd = fixedi64_from_balance(value).saturating_mul(price);
                    balance_usd = balance_usd + collateral_usd;
                }
                Negative(value) => {
                    balances_vec.push((currency, (T::Balance::zero(), value.clone())));
                    let price = T::PriceGetter::get_price(&currency).unwrap_or(FixedI64::zero());
                    let debt_usd = fixedi64_from_balance(value).saturating_mul(price);
                    balance_usd = balance_usd - debt_usd;
                }
            }
        }

        let min_collaterall = Into::<u64>::into(T::MinimalCollaterall::get());
        let min_collaterall = FixedI64::saturating_from_integer(min_collaterall);
        eq_ensure!(
            balance_usd > min_collaterall,
            Error::<T>::CollaterallMustBeMoreThanMin,
            "{}:{}. Total usd balance less or equal to min value. Total usd balance: {:?}, min value: {:?}.",
            file!(), line!(), balance_usd, min_collaterall
        );

        T::Aggregates::set_usergroup(who, &UserGroup::Bailsmen, &true);

        Ok(())
    }

    /// Inner implementation of unregistering bailsman
    fn _unregister_bailsman(who: &T::AccountId) -> Result<(), Error<T>> {
        Self::_reinit()?;
        let existing = T::Aggregates::in_usergroup(who, &UserGroup::Bailsmen);
        eq_ensure!(
            existing == true,
            Error::<T>::NotAnBailsman,
            "{}:{}. Account not a bailsman. Who: {:?}.",
            file!(),
            line!(),
            who
        );

        T::Aggregates::set_usergroup(who, &UserGroup::Bailsmen, &false);

        Ok(())
    }

    // todel ипмл был отдельный
    /// Calculates Bailsman fee
    fn calc_fee_percent(owner: &T::AccountId) -> Result<FixedI128, InterestRateError> {
        if cfg!(feature = "test") {
            // hardcoded 2% for main logic tests
            Ok(FixedI128::saturating_from_rational(2i128, 100i128))
        } else {
            let interest_rate = rate::interest_rate::<Self>(owner)?;
            Ok(fixedi128_from_fixedi64(interest_rate))
        }
    }
}

impl<T: Trait> rate::InterestRateDataSource for Module<T> {
    type AccountId = T::AccountId;

    fn get_settings() -> rate::InterestRateSettings {
        rate::InterestRateSettings::new(
            T::RiskLoverBound::get(),
            T::RiskUpperBound::get(),
            T::RiskTarget::get(),
            T::RiskNSigma::get(),
            T::RiskRho::get(),
            T::Alpha::get(),
        )
    }

    fn get_price(currency: &Currency) -> Result<FixedI64, sp_runtime::DispatchError> {
        T::PriceGetter::get_price(currency)
    }

    fn get_covariance(c1: &Currency, c2: &Currency) -> FixedI64 {
        T::VolatilityGetter::get_covariance(c1, c2)
    }

    fn get_bailsman_total_balance(currency: &Currency) -> rate::TotalBalance {
        let totals = T::Aggregates::get_total(&UserGroup::Bailsmen, currency);

        rate::TotalBalance::new(
            fixedi64_from_balance(totals.collateral),
            fixedi64_from_balance(totals.debt),
        )
    }

    fn get_total_balance(currency: &Currency) -> rate::TotalBalance {
        let totals = T::Aggregates::get_total(&UserGroup::Balances, currency);

        rate::TotalBalance::new(
            fixedi64_from_balance(totals.collateral),
            fixedi64_from_balance(totals.debt),
        )
    }

    fn get_balance(account_id: &T::AccountId, currency: &Currency) -> rate::TotalBalance {
        let balance = T::BalanceGetter::get_balance(account_id, currency);

        match balance {
            SignedBalance::Positive(value) => rate::TotalBalance::new(
                fixedi64_from_balance(value),
                FixedI64::saturating_from_integer(0),
            ),
            SignedBalance::Negative(value) => rate::TotalBalance::new(
                FixedI64::saturating_from_integer(0),
                fixedi64_from_balance(value),
            ),
        }
    }
}

/// Manages bailsman operation. OFFCHAIN ONLY
pub trait BailsmanManager<AccountId> {
    /// OFFCHAIN ONLY. Returns total USD value of Bailsman Pallet balances
    fn get_temp_balances_usd() -> Result<FixedI128, sp_runtime::DispatchError>;
    /// OFFCHAIN ONLY. Receives account `who` balances in case of margin call. Account balances
    /// are sent to Bailsman Pallet balance
    fn receive_position(who: &AccountId);
    /// OFFCHAIN ONLY. Reinit to check and redistribute balances
    fn reinit();
}

// for offchain only!
impl<T: Trait> BailsmanManager<T::AccountId> for Module<T> {
    fn get_temp_balances_usd() -> Result<FixedI128, sp_runtime::DispatchError> {
        let self_account = Self::get_account_id();
        let self_balances = T::BalanceGetter::iterate_account_balances(&self_account);
        let mut balance_usd = FixedI128::from_inner(0);

        for balance in self_balances {
            let price = T::PriceGetter::get_price(&balance.0)?;
            let price = fixedi128_from_fixedi64(price);

            match balance.1 {
                Positive(value) => {
                    balance_usd = balance_usd + fixedi128_from_balance(value) * price;
                }
                Negative(value) => {
                    balance_usd = balance_usd - fixedi128_from_balance(value) * price;
                }
            };
        }

        Ok(balance_usd)
    }

    #[allow(unused_must_use)]
    fn reinit() {
        Self::_reinit();
    }

    #[allow(unused_must_use)]
    fn receive_position(who: &T::AccountId) {
        let self_account = Module::<T>::get_account_id();
        for balance in T::BalanceGetter::iterate_account_balances(who) {
            match balance.1 {
                SignedBalance::Positive(abalance) => {
                    T::EqCurrency::currency_transfer(
                        balance.0,
                        who,
                        &self_account,
                        abalance,
                        ExistenceRequirement::KeepAlive,
                        eq_primitives::TransferReason::MarginCall,
                        false,
                    ); // shoud we expect error here?
                }
                SignedBalance::Negative(abalance) => {
                    T::EqCurrency::currency_transfer(
                        balance.0,
                        &self_account,
                        who,
                        abalance,
                        ExistenceRequirement::KeepAlive,
                        eq_primitives::TransferReason::MarginCall,
                        false,
                    ); // shoud we expect error here?
                }
            }
        }
        // we need to kill account here!
    }
}

impl<T: Trait> FeeManager<T::AccountId, T::Balance> for Module<T> {
    fn calc_fee(owner: &T::AccountId, last_update: &u64) -> Result<T::Balance, InterestRateError> {
        let fee = Self::calc_fee_percent(owner)?;
        let (debt, _) = T::BalanceGetter::get_debt_and_colaterall(owner);
        let current_time = T::UnixTime::now().as_secs();
        let elapsed = FixedI128::saturating_from_integer(current_time - *last_update);

        let debt_amount_usd =
            fee * debt * elapsed / FixedI128::saturating_from_integer(365 as i128 * 24 * 60 * 60);
        let price = T::PriceGetter::get_price(&Currency::Eq).map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            InterestRateError::ExternalError
        })?;
        let debt_amount = debt_amount_usd / fixedi128_from_fixedi64(price);
        let option_balance = balance_from_fixedi128(debt_amount);
        ok_or_error!(
            option_balance,
            InterestRateError::ValueError,
            "{}:{}. Couldn't convert debt amount from FixedI128 to balance. Amount: {:?}.",
            file!(),
            line!(),
            debt_amount
        )
    }
    #[allow(unused_must_use)]
    fn charge_fee_inner(owner: &T::AccountId, fee_amount: &T::Balance) {
        let self_account = Module::<T>::get_account_id();

        T::EqCurrency::currency_transfer(
            Currency::Eq,
            owner,
            &self_account,
            *fee_amount,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::InterestFee,
            false,
        );
    }
}