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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! # Equilibrium Balances Pallet
//! 
//! Equilibrium's Balances Pallet is a Substrate module that stores and
//! modifies users balances. Apart from basic balances functionality this 
//! pallet was developed to support negative balance values.

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

pub mod balance_adapter;
mod benchmarking;
mod benchmarks;
pub mod imbalances;
mod mock;
mod tests;

use codec::{Codec, Decode, Encode, FullCodec};
use eq_oracle::PriceGetter;
pub use eq_primitives::currency as currency;
pub use eq_primitives::signed_balance::{SignedBalance, SignedBalance::*};
use eq_primitives::{currency::Currency, Aggregates, UserGroup, TransferReason};
use eq_utils::{eq_ensure, log::eq_log, ok_or_error};
use frame_support::{
    debug, decl_error, decl_event, decl_module, decl_storage,
    dispatch::{DispatchError, DispatchResult},
    storage::IterableStorageDoubleMap,
    storage::IterableStorageMap,
    traits::{
        ExistenceRequirement, Get, Imbalance, OnKilledAccount, SignedImbalance, TryDrop,
        WithdrawReasons,
    },
    weights::Weight,
    Parameter,
};
pub use imbalances::{NegativeImbalance, PositiveImbalance};
use impl_trait_for_tuples::impl_for_tuples;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_arithmetic::{FixedI128, FixedI64, FixedPointNumber};
use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Member, Zero};
use sp_std::prelude::*;
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, result};
use system as frame_system;
use system::{ensure_root, ensure_signed};

pub trait WeightInfo {
    fn transfer(b: u32) -> Weight;
    fn deposit(b: u32) -> Weight;
    fn burn(b: u32) -> Weight;
}

/// Substrate pallet configuration trait
pub trait Trait: system::Trait {
    // add enum currency as a type
    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
    type WeightInfo: WeightInfo;

    /// Numerical representation of stored balances
    type Balance: Parameter
        + Member
        + AtLeast32BitUnsigned
        + Codec
        + Default
        + Copy
        + MaybeSerializeDeserialize
        + Debug
        + From<u64>
        + Into<u64>;
    /// Minimum account balance. Accounts with deposit less than 
    /// `ExistentialDeposit` must be killed
    type ExistentialDeposit: Get<Self::Balance>;
    /// Interface for pallet balance check
    type BalanceChecker: BalanceChecker<Self::Balance, Self::AccountId>;
    /// Interface for accessing currency prices 
    type PriceGetter: PriceGetter;
    /// Interface for managing currency values aggregated for user groups
    type Aggregates: Aggregates<Self::AccountId, Self::Balance>;
}

decl_storage! {
    trait Store for Module<T: Trait> as EqBalances {
        /// Pallet storage - balances for all accounts
        pub Account: double_map hasher(blake2_128_concat) T::AccountId, hasher(blake2_128_concat) currency::Currency => SignedBalance<T::Balance>;
    }
    add_extra_genesis {
        config(balances): Vec<(T::AccountId, T::Balance, u8)>;
        
        build(|config: &GenesisConfig<T>| {
            for &(ref who, free, currency) in config.balances.iter() {
                let currency_typed: currency::Currency = currency.into();
                <Module<T>>::deposit_creating(currency_typed, who, free, true);
            }
        });
    }
}

decl_event!(
    /// Balances pallet events
    pub enum Event<T> where
        <T as system::Trait>::AccountId,
        <T as Trait>::Balance
    {
        /// Transfer event. Included values are:
        /// - from `AccountId`
        /// - to `AccountId`
        /// - transfer `Currency`
        /// - transferred amount 
        /// - transfer reason
        Transfer(AccountId, AccountId, Currency, Balance, TransferReason),
    }
);

decl_error! {
    /// Balances pallet errors
    pub enum Error for Module<T: Trait> {
        // TODO remove unused errors?
        // /// Vesting balance too high to send value
        // VestingBalance,
        // /// Account liquidity restrictions prevent withdrawal
        // LiquidityRestrictions,
        /// Balance too low to send value
        // InsufficientBalance,
        // /// Value too low to create account due to existential deposit
        // ExistentialDeposit,
        // /// Transfer/payment would kill account
        // KeepAlive,

        /// Got an overflow after adding or subtracting balance
        Overflow,
        /// A vesting schedule already exists for this account
        ExistingVestingSchedule,
        /// Beneficiary account must pre-exist
        DeadAccount,
        /// Self documented error code
        NotAllowedToChangeBalance,
    }
}

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

        fn deposit_event() = default;

        /// Transfers `value` amount of `currency` from trx sender to account id `to`
        #[weight = T::WeightInfo::transfer(1)]
        pub fn transfer(origin, currency: currency::Currency, to: <T as system::Trait>::AccountId, value: T::Balance) -> DispatchResult
        {
            let from = ensure_signed(origin)?;
            Self::currency_transfer(currency, &from, &to, value, ExistenceRequirement::AllowDeath, TransferReason::Common, true)
        }

        /// Adds currency to account balance (sudo only). Used to deposit currency 
        /// into system
        #[weight = T::WeightInfo::deposit(1)]
        pub fn deposit(origin, currency: currency::Currency, to: <T as system::Trait>::AccountId, value: T::Balance) -> DispatchResult
        {
            ensure_root(origin)?;

            Self::deposit_creating(currency, &to, value, true);
            Ok(())
        }

        /// Burns currency (sudo only). Used to withdraw currency from the system
        #[weight = T::WeightInfo::burn(1)]
        pub fn burn(origin, currency: currency::Currency, from: <T as system::Trait>::AccountId, value: T::Balance) -> DispatchResult
        {
            ensure_root(origin)?;
            #[allow(unused_must_use)]
            {
                Self::withdraw(currency, &from, value, WithdrawReasons::all(), ExistenceRequirement::AllowDeath, true)?;
            }
            Ok(())
        }
    }
}

impl<T: Trait> Module<T> {
    // for tests only! #[cfg(test)] is not visible in other pallets

    // TODO: remove
    pub fn set_balance_with_agg_unsafe(
        who: &T::AccountId,
        currency: &currency::Currency,
        value: SignedBalance<T::Balance>,
    ) {
        let delta = value - <Account<T>>::get(who, currency);
        match delta {
            Positive(d) => {
                Self::deposit_creating(*currency, who, d, false);
            }
            Negative(d) => {
                Self::withdraw(*currency, who, d, WithdrawReasons::all(), ExistenceRequirement::AllowDeath, false);
            }
        }

    }
}


/// Balances reading interface
pub trait BalanceGetter<AccountId, Balance>
where
    Balance: Debug + Member + Into<u64>,
{
    type PriceGetter: eq_oracle::PriceGetter;

    // Gets account `who` balance for given currency
    fn get_balance(who: &AccountId, currency: &currency::Currency) -> SignedBalance<Balance>; 
       
    /// Gets total USD value of positive currency balances
    fn get_total_collateral_value() -> FixedI64;

    /// Gets total USD value of of negative currency balances
    fn get_total_debt_value() -> FixedI64;

    /// Used for iteration over whole balances storage. DO NOT USE IN RUNTIME, 
    /// only for offchain workers
    fn iterate_balances() -> BTreeMap<AccountId, Vec<(currency::Currency, SignedBalance<Balance>)>>;

    /// Used to iterate over each currency balance of `account`
    fn iterate_account_balances(
        account: &AccountId,
    ) -> Vec<(currency::Currency, SignedBalance<Balance>)>;

    /// Gets total value of account's debt and collateral in USD
    fn get_debt_and_colaterall(who: &AccountId) -> (FixedI128, FixedI128) {
        let mut debt = FixedI128::zero();
        let mut collaterall = FixedI128::zero();
        let accuracy = FixedI128::accuracy() / FixedI64::accuracy() as i128;

        for abalance in Self::iterate_account_balances(who) {
            let (currency, balance) = abalance;
            let price = Self::PriceGetter::get_price(&currency).unwrap_or(FixedI64::zero());
            let price = FixedI128::from_inner((price.into_inner() as i128) * accuracy);

            match balance {
                Positive(value) => {
                    let value = Into::<u64>::into(value);
                    collaterall =
                        collaterall + FixedI128::from_inner(value as i128 * accuracy) * price;
                }
                Negative(value) => {
                    if price.is_zero() {
                        debug::warn!("No price for {:?} !", currency);
                        (FixedI128::from_inner(0), FixedI128::from_inner(0));
                    }
                    let value = Into::<u64>::into(value);
                    debt = debt + FixedI128::from_inner(value as i128 * accuracy) * price;
                }
            };
        }

        (debt, collaterall)
    }
}

impl<T: Trait> BalanceGetter<T::AccountId, T::Balance> for Module<T> {
    type PriceGetter = T::PriceGetter;
    fn get_balance(who: &T::AccountId, currency: &currency::Currency) -> SignedBalance<T::Balance> {
        <Account<T>>::get(who, currency)
    }
    fn get_total_collateral_value() -> FixedI64 {
        let mut total_usd = FixedI64::zero();
        for balance in T::Aggregates::iter_total(&UserGroup::Balances) {
            let issuance = FixedI64::from_inner(Into::<u64>::into(balance.1.collateral) as i64);
            let price = T::PriceGetter::get_price(&balance.0).unwrap_or(FixedI64::zero());
            total_usd = total_usd + issuance * price;
        }
        total_usd
    }

    fn iterate_balances(
    ) -> BTreeMap<T::AccountId, Vec<(currency::Currency, SignedBalance<T::Balance>)>> {
        let mut res: BTreeMap<T::AccountId, Vec<(currency::Currency, SignedBalance<T::Balance>)>> =
            BTreeMap::new();
        <Account<T>>::iter().for_each(|(acc, curr, balance)| {
            res.entry(acc.clone())
                .and_modify(|items| items.push((curr, balance.clone())))
                .or_insert(vec![(curr, balance)]);
        });
        res
    }

    fn iterate_account_balances(
        account: &T::AccountId,
    ) -> Vec<(currency::Currency, SignedBalance<T::Balance>)> {
        <Account<T>>::iter_prefix(account).collect::<Vec<_>>()
    }

    fn get_total_debt_value() -> FixedI64 {
        let mut total_usd = FixedI64::zero();
        for balance in T::Aggregates::iter_total(&UserGroup::Balances) {
            let debt = FixedI64::from_inner(Into::<u64>::into(balance.1.debt) as i64);
            let price = T::PriceGetter::get_price(&balance.0).unwrap_or(FixedI64::zero());
            total_usd = total_usd + debt * price;
        }
        total_usd
    }
}



/// Interface for balance checks
pub trait BalanceChecker<Balance, AccountId>
where
    Balance: Member + Debug,
{
    /// Checks whether a specific operation can be performed on user's balance
    fn can_change_balance(
        _who: &AccountId,
        _currency: &currency::Currency,
        _change: &SignedBalance<Balance>,
        reason: Option<WithdrawReasons>,
    ) -> Result<bool, sp_runtime::DispatchError>;
}

#[impl_for_tuples(5)]
impl<Balance: Member + Debug, AccountId> BalanceChecker<Balance, AccountId> for Tuple {
    fn can_change_balance(
        who: &AccountId,
        currency: &currency::Currency,
        change: &SignedBalance<Balance>,
        reason: Option<WithdrawReasons>,
    ) -> Result<bool, sp_runtime::DispatchError> {
        let mut res: bool = true;
        for_tuples!( #( res &= Tuple::can_change_balance(&who, &currency, &change, reason)?; )* );
        Ok(res)
    }
}

/// An extension to Substrate standard Currency, adapting it to work in 
/// Equilibrium substrate
pub trait EqCurrency<AccountId, Balance>
where
    Balance: Member
        + AtLeast32BitUnsigned
        + FullCodec
        + Copy
        + MaybeSerializeDeserialize
        + Debug
        + Default,
{
    /// Returns balance value if balance is positive or zero if negative
    fn total_balance(currency: currency::Currency, who: &AccountId) -> Balance;

    /// Returns balance value if balance is negative or zero if negative
    fn debt(currency: currency::Currency, who: &AccountId) -> Balance;

    // Unimplemented. Slash currently unsupported
    fn can_slash(currency: currency::Currency, who: &AccountId, value: Balance) -> bool;

    /// Gets total issuance of given currency
    fn currency_total_issuance(currency: currency::Currency) -> Balance;

    /// Returns [`ExistentialDeposit`](./trait.Trait.html#associatedtype.ExistentialDeposit)
    /// for given `currency`
    fn currency_minimum_balance(currency: currency::Currency) -> Balance;

    /// Unimplemented
    fn burn(currency: currency::Currency, amount: Balance) -> PositiveImbalance<Balance>;

    /// Unimplemented. Use [`deposit`](./struct.Module.html#method.deposit) instead
    fn issue(currency: currency::Currency, amount: Balance) -> NegativeImbalance<Balance>;

    /// Same as `total_balance`
    fn free_balance(currency: currency::Currency, who: &AccountId) -> Balance;

    /// Used to ensure that user's balance in specified currency can be 
    /// decreased for `amount`
    fn ensure_can_withdraw(
        currency: currency::Currency,
        who: &AccountId,
        amount: Balance,
        reasons: WithdrawReasons,
        new_balance: Balance,
    ) -> DispatchResult;

    /// Operates transfers inside pallet functions
    /// - `transactor` - account sending currency
    /// - `dest` - account receiving currency
    /// - `value` - amount transferred
    /// - `existence_requirement` - currently unused
    /// - `ensure_can_change` - flag for ensuring transfer can be performed with [`can_change_balance`](./trait.BalanceChecker.html#tymethod.can_change_balance)
    fn currency_transfer(
        currency: currency::Currency,
        transactor: &AccountId,
        dest: &AccountId,
        value: Balance,
        existence_requirement: ExistenceRequirement,
        transfer_reason: TransferReason,
        ensure_can_change: bool,
    ) -> DispatchResult;

    // Unimplemented. Slash currently unsupported
    fn slash(
        currency: currency::Currency,
        who: &AccountId,
        value: Balance,
    ) -> (NegativeImbalance<Balance>, Balance);

    /// Adds given amount of currency to account's balance
    fn deposit_into_existing(
        currency: currency::Currency,
        who: &AccountId,
        value: Balance,
    ) -> Result<PositiveImbalance<Balance>, DispatchError>;

    /// Performs a deposit creating balance storage for account if it does 
    /// not exist
    fn deposit_creating(
        currency: currency::Currency,
        who: &AccountId,
        value: Balance,
        ensure_can_change: bool,
    ) -> PositiveImbalance<Balance>;

    /// Similar to `deposit_creating`, only accepts a `NegativeImbalance` and returns 
    /// nothing on success
    fn resolve_creating(
        currency: currency::Currency,
        who: &AccountId,
        value: NegativeImbalance<Balance>,
    ) {
        let v = value.peek();
        drop(value.offset(Self::deposit_creating(currency, who, v, true)));
    }

    /// Decreases `who` account balance for specified amount of currency
    /// - `ensure_can_change` - flag for ensuring transfer can be performed with 
    ///   [`can_change_balance`](./trait.BalanceChecker.html#tymethod.can_change_balance)
    fn withdraw(
        currency: currency::Currency,
        who: &AccountId,
        value: Balance,
        reasons: WithdrawReasons,
        liveness: ExistenceRequirement,
        ensure_can_change: bool,
    ) -> Result<NegativeImbalance<Balance>, DispatchError>;

    /// Force the new free balance of a target account to some new value
    fn make_free_balance_be(
        currency: currency::Currency,
        who: &AccountId,
        value: Balance,
    ) -> SignedImbalance<Balance, PositiveImbalance<Balance>>;
}

impl<T: Trait> EqCurrency<T::AccountId, T::Balance> for Module<T> {
    fn total_balance(currency: currency::Currency, who: &T::AccountId) -> T::Balance {
        let balance = <Account<T>>::get(&who, &currency);
        match balance {
            SignedBalance::Positive(balance) => balance,
            SignedBalance::Negative(_) => T::Balance::zero(),
        }
    }

    fn debt(currency: currency::Currency, who: &T::AccountId) -> T::Balance {
        let balance = <Account<T>>::get(&who, &currency);
        match balance {
            SignedBalance::Negative(balance) => balance,
            SignedBalance::Positive(_) => T::Balance::zero(),
        }
    }

    fn can_slash(_currency: currency::Currency, _who: &T::AccountId, _value: T::Balance) -> bool {
        unimplemented!("fn can_slash")
    }

    fn currency_total_issuance(currency: currency::Currency) -> T::Balance {
        T::Aggregates::get_total(&UserGroup::Balances, &currency).collateral
    }

    fn currency_minimum_balance(_currency: currency::Currency) -> T::Balance {
        T::ExistentialDeposit::get()
    }

    fn burn(_currency: currency::Currency, _amount: T::Balance) -> PositiveImbalance<T::Balance> {
        unimplemented!("fn burn");
        // todo: почему unimplemented? Вроде у нас в decl_module используется withdraw
        // для этого.
    }

    fn issue(_currency: currency::Currency, _amount: T::Balance) -> NegativeImbalance<T::Balance> {
        unimplemented!("fn issue");
    }

    fn free_balance(currency: currency::Currency, who: &T::AccountId) -> T::Balance {
        let balance = <Account<T>>::get(&who, &currency);
        match balance {
            SignedBalance::Positive(balance) => balance,
            SignedBalance::Negative(_) => T::Balance::zero(),
        }
    }

    fn ensure_can_withdraw(
        currency: currency::Currency,
        who: &T::AccountId,
        amount: T::Balance,
        reasons: WithdrawReasons,
        _new_balance: T::Balance, // wtf is this? !!!!!
    ) -> DispatchResult {
        // TODO: reason debt

        eq_log!(
            "ensure_can_withdraw: who: {:?}, amount: {:?}",
            &who,
            &amount
        );
        eq_ensure!(
            T::BalanceChecker::can_change_balance(
                &who,
                &currency,
                &SignedBalance::Negative(amount),
                Option::Some(reasons),
            )?,
            Error::<T>::NotAllowedToChangeBalance,
            "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
            file!(),
            line!(),
            who,
            amount,
            currency
        );
        Ok(())
    }

    fn currency_transfer(
        currency: currency::Currency,
        transactor: &T::AccountId,
        dest: &T::AccountId,
        value: T::Balance,
        _existence_requirement: ExistenceRequirement,
        transfer_reason: TransferReason,
        ensure_can_change: bool,
    ) -> DispatchResult {
        if value.is_zero() || transactor == dest {
            return Ok(());
        }

        eq_log!(
            "transfer: currency: {:?}, transactor: {:?}, dest: {:?}, value: {:?}",
            currency,
            &transactor,
            &dest,
            value
        );

        <Account<T>>::mutate(transactor, &currency, |from_account| -> DispatchResult {
            <Account<T>>::mutate(dest, &currency, |to_account| -> DispatchResult {
                eq_ensure!(!ensure_can_change ||
                    T::BalanceChecker::can_change_balance(
                        &transactor,
                        &currency,
                        &SignedBalance::Negative(value),
                        Option::None,
                    )?,
                    Error::<T>::NotAllowedToChangeBalance,
                    "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
                    file!(),
                    line!(),
                    transactor,
                    value,
                    currency
                );
                eq_ensure!(!ensure_can_change ||
                    T::BalanceChecker::can_change_balance(
                        &dest,
                        &currency,
                        &SignedBalance::Positive(value),
                        Option::None,
                    )?,
                    Error::<T>::NotAllowedToChangeBalance,
                    "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
                    file!(),
                    line!(),
                    dest,
                    value,
                    currency
                );

                T::Aggregates::update_total(&transactor, &currency, from_account, &SignedBalance::Negative(value));
                T::Aggregates::set_usergroup(&dest, &UserGroup::Balances, &true);
                T::Aggregates::update_total(&dest, &currency, to_account, &SignedBalance::Positive(value)); 

                let mut option_signed_balance = from_account.sub_balance(value);
                *from_account = ok_or_error!(option_signed_balance, Error::<T>::Overflow,
                "{}:{}. Overflow sub balance. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
                file!(), line!(), transactor, from_account, value, currency)?;

                option_signed_balance = to_account.add_balance(value);
                *to_account = ok_or_error!(option_signed_balance, Error::<T>::Overflow,
                "{}:{}. Overflow add balance. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
                file!(), line!(), dest, to_account, value, currency)?;

                // checks new account + can transfer
                // delete account from if < min

                Ok(())
            })?;

            Self::deposit_event(RawEvent::Transfer(
                transactor.clone(),
                dest.clone(),
                currency.clone(),
                value,
                transfer_reason,
            ));
            Ok(())
        })
    }

    fn slash(
        _currency: currency::Currency,
        _who: &T::AccountId,
        _value: T::Balance,
    ) -> (NegativeImbalance<T::Balance>, T::Balance) {
        unimplemented!("fn slash")
    }

    fn deposit_into_existing(
        currency: currency::Currency,
        who: &T::AccountId,
        value: T::Balance,
    ) -> Result<PositiveImbalance<T::Balance>, DispatchError> {
        if value.is_zero() {
            return Ok(PositiveImbalance::zero());
        }

        eq_ensure!(<Account<T>>::iter_prefix(
            &who).any(|bal| !bal.1.is_zero()), 
            Error::<T>::DeadAccount,
            "{}:{}. Cannot deposit dead balance. Who: {:?}.",
            file!(),
            line!(),
            who);

        <Account<T>>::mutate(
            &who,
            &currency,
            |bal| -> Result<PositiveImbalance<T::Balance>, DispatchError> {
                eq_log!(
                    "deposit_into_existing: who: {:?}, value: {:?}",
                    &who,
                    &value
                );
                eq_ensure!(
                    T::BalanceChecker::can_change_balance(
                        &who,
                        &currency,
                        &SignedBalance::Positive(value),
                        Option::None,
                    )?,
                    Error::<T>::NotAllowedToChangeBalance,
                    "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
                    file!(),
                    line!(),
                    who,
                    value,
                    currency
                );
                let option_signed_balance = bal.add_balance(value);
                T::Aggregates::update_total(&who, &currency, bal, &SignedBalance::Positive(value));
                *bal = ok_or_error!(option_signed_balance, Error::<T>::Overflow,
                "{}:{}. Overflow add balance. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
                file!(), line!(), who, bal, value, currency)?;
                Ok(PositiveImbalance::new(value))
            },
        )
    }

    fn deposit_creating(
        currency: currency::Currency,
        who: &T::AccountId,
        value: T::Balance,
        ensure_can_change: bool,
    ) -> PositiveImbalance<T::Balance> {
        if value.is_zero() {
            return PositiveImbalance::zero();
        }

        <Account<T>>::mutate(
            &who,
            &currency,
            |bal| -> Result<PositiveImbalance<T::Balance>, PositiveImbalance<T::Balance>> {
                // check for min  amount
                if !ensure_can_change || T::BalanceChecker::can_change_balance(
                    &who,
                    &currency,
                    &SignedBalance::Positive(value),
                    Option::None,
                ).unwrap_or(false) {
                    T::Aggregates::set_usergroup(&who, &UserGroup::Balances, &true);
                    let option_signed_balance = bal.add_balance(value);
                    T::Aggregates::update_total(&who, &currency, bal, &SignedBalance::Positive(value));
                    *bal = ok_or_error!(option_signed_balance, PositiveImbalance::zero(),
                        "{}:{}. Add balance error. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
                        file!(), line!(), who, bal, value, currency)?;
                    
                    Ok(PositiveImbalance::new(value))
                } else {
                    eq_log!("deposit_creating error who:{:?}, currency:{:?}, value:{:?}, ensure_can_change:{:?}",
                        *who,
                        currency,                        
                        value,
                        ensure_can_change);
                    Ok(PositiveImbalance::zero())
                }
            },
        )
        .unwrap_or_else(|x| x)
    }

    fn withdraw(
        currency: currency::Currency,
        who: &T::AccountId,
        value: T::Balance,
        reasons: WithdrawReasons,
        _liveness: ExistenceRequirement,
        ensure_can_change: bool,
    ) -> result::Result<NegativeImbalance<T::Balance>, DispatchError> {
        if value.is_zero() {
            return Ok(NegativeImbalance::zero());
        }

        <Account<T>>::mutate(
            &who,
            &currency,
            |bal| -> Result<NegativeImbalance<T::Balance>, DispatchError> {
                // ensure!(bal.is_some(), Error::<T>::DeadAccount);
                // !!!!!!!! Check all balances!

                eq_log!("withdraw: who: {:?}, value: {:?}", &who, &value);

                eq_ensure!(!ensure_can_change ||
                    T::BalanceChecker::can_change_balance(
                        &who,
                        &currency,
                        &SignedBalance::Negative(value),
                        Option::Some(reasons)
                    )?,
                    Error::<T>::NotAllowedToChangeBalance,
                    "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
                    file!(),
                    line!(),
                    who,
                    value,
                    currency
                );
                let option_signed_balance = bal.sub_balance(value);
                T::Aggregates::update_total(&who, &currency, bal, &SignedBalance::Negative(value));
                *bal = ok_or_error!(option_signed_balance, Error::<T>::Overflow,
                    "{}:{}. Overflow sub balance. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
                    file!(), line!(), who, bal, value, currency)?;
                Ok(NegativeImbalance::new(value))
            },
        )
    }

    fn make_free_balance_be(
        currency: currency::Currency,
        who: &T::AccountId,
        value: T::Balance,
    ) -> SignedImbalance<T::Balance, PositiveImbalance<T::Balance>> {
        <Account<T>>::mutate(
            who,
            &currency,
            |account| -> Result<SignedImbalance<T::Balance, PositiveImbalance<T::Balance>>, ()> {
                // check collaterall

                let imbalance = match account {
                    SignedBalance::Positive(balance) => {
                        let a_balance = balance.clone();
                        if value > a_balance {
                            SignedImbalance::Positive(PositiveImbalance::new(value - a_balance))
                        } else {
                            SignedImbalance::Negative(NegativeImbalance::new(a_balance - value))
                        }
                    }
                    SignedBalance::Negative(balance) => {
                        let a_balance = balance.clone();
                        SignedImbalance::Positive(PositiveImbalance::new(value + a_balance))
                    }
                };

                let signed_balance = SignedBalance::from(&imbalance);
                let balance = match signed_balance {
                    SignedBalance::Positive(balance) => balance,
                    SignedBalance::Negative(balance) => balance,
                };
                eq_ensure!(
                    T::BalanceChecker::can_change_balance(
                        &who,
                        &currency,
                        &SignedBalance::from(&imbalance),
                        Option::None,
                    )
                    .unwrap_or(false),
                    (),
                    "{}:{}. Cannot change balance. Who: {:?}, amount: {:?}, currency: {:?}.",
                    file!(),
                    line!(),
                    who,
                    balance,
                    currency
                );

                *account = SignedBalance::Positive(value);

                Ok(imbalance)
            },
        )
        .unwrap_or(SignedImbalance::Positive(PositiveImbalance::zero()))
    }
}

impl<T: Trait> OnKilledAccount<T::AccountId> for Module<T> {
    fn on_killed_account(who: &T::AccountId) {
        Account::<T>::remove_prefix(who);
    }
}