-
Notifications
You must be signed in to change notification settings - Fork 300
/
lib.rs
2597 lines (2339 loc) · 79.3 KB
/
lib.rs
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Tokens Module
//!
//! ## Overview
//!
//! The tokens module provides fungible multi-currency functionality that
//! implements `MultiCurrency` trait.
//!
//! The tokens module provides functions for:
//!
//! - Querying and setting the balance of a given account.
//! - Getting and managing total issuance.
//! - Balance transfer between accounts.
//! - Depositing and withdrawing balance.
//! - Slashing an account balance.
//!
//! ### Implementations
//!
//! The tokens module provides implementations for following traits.
//!
//! - `MultiCurrency` - Abstraction over a fungible multi-currency system.
//! - `MultiCurrencyExtended` - Extended `MultiCurrency` with additional helper
//! types and methods, like updating balance
//! by a given signed integer amount.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! - `transfer` - Transfer some balance to another account.
//! - `transfer_all` - Transfer all balance to another account.
//!
//! ### Genesis Config
//!
//! The tokens module depends on the `GenesisConfig`. Endowed accounts could be
//! configured in genesis configs.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![allow(clippy::comparison_chain)]
pub use crate::imbalances::{NegativeImbalance, PositiveImbalance};
use frame_support::{
ensure,
pallet_prelude::*,
traits::{
tokens::{
fungible, fungibles, DepositConsequence, Fortitude, Precision, Preservation, Provenance, Restriction,
WithdrawConsequence,
},
BalanceStatus as Status, Contains, Currency as PalletCurrency, DefensiveSaturating, ExistenceRequirement, Get,
Imbalance, LockableCurrency as PalletLockableCurrency,
NamedReservableCurrency as PalletNamedReservableCurrency, ReservableCurrency as PalletReservableCurrency,
SignedImbalance, WithdrawReasons,
},
transactional, BoundedVec,
};
use frame_system::{ensure_signed, pallet_prelude::*};
use parity_scale_codec::MaxEncodedLen;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, Saturating,
StaticLookup, Zero,
},
ArithmeticError, DispatchError, DispatchResult, FixedPointOperand, RuntimeDebug, TokenError,
};
use sp_std::{cmp, convert::Infallible, marker, prelude::*, vec::Vec};
use orml_traits::{
arithmetic::{self, Signed},
currency::{MutationHooks, OnDeposit, OnDust, OnSlash, OnTransfer, TransferAll},
BalanceStatus, GetByKey, Happened, LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency,
MultiReservableCurrency, NamedMultiReservableCurrency,
};
mod imbalances;
mod impls;
mod mock;
mod tests;
mod tests_currency_adapter;
mod tests_events;
mod tests_fungibles;
mod tests_multicurrency;
mod weights;
pub use impls::*;
pub use weights::WeightInfo;
pub struct TransferDust<T, GetAccountId>(marker::PhantomData<(T, GetAccountId)>);
impl<T, GetAccountId> OnDust<T::AccountId, T::CurrencyId, T::Balance> for TransferDust<T, GetAccountId>
where
T: Config,
GetAccountId: Get<T::AccountId>,
{
fn on_dust(who: &T::AccountId, currency_id: T::CurrencyId, amount: T::Balance) {
// transfer the dust to treasury account, ignore the result,
// if failed will leave some dust which still could be recycled.
let _ = Pallet::<T>::do_transfer(
currency_id,
who,
&GetAccountId::get(),
amount,
ExistenceRequirement::AllowDeath,
);
}
}
pub struct BurnDust<T>(marker::PhantomData<T>);
impl<T: Config> OnDust<T::AccountId, T::CurrencyId, T::Balance> for BurnDust<T> {
fn on_dust(who: &T::AccountId, currency_id: T::CurrencyId, amount: T::Balance) {
// burn the dust, ignore the result,
// if failed will leave some dust which still could be recycled.
let _ = Pallet::<T>::do_withdraw(currency_id, who, amount, ExistenceRequirement::AllowDeath, true);
}
}
/// A single lock on a balance. There can be many of these on an account and
/// they "overlap", so the same balance is frozen by multiple locks.
#[derive(Encode, Decode, Clone, PartialEq, Eq, MaxEncodedLen, RuntimeDebug, TypeInfo)]
pub struct BalanceLock<Balance> {
/// An identifier for this lock. Only one lock may be in existence for
/// each identifier.
pub id: LockIdentifier,
/// The amount which the free balance may not drop below when this lock
/// is in effect.
pub amount: Balance,
}
/// Store named reserved balance.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct ReserveData<ReserveIdentifier, Balance> {
/// The identifier for the named reserve.
pub id: ReserveIdentifier,
/// The amount of the named reserve.
pub amount: Balance,
}
/// balance information for an account.
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, MaxEncodedLen, RuntimeDebug, TypeInfo)]
pub struct AccountData<Balance> {
/// Non-reserved part of the balance. There may still be restrictions on
/// this, but it is the total pool what may in principle be transferred,
/// reserved.
///
/// This is the only balance that matters in terms of most operations on
/// tokens.
pub free: Balance,
/// Balance which is reserved and may not be used at all.
///
/// This can still get slashed, but gets slashed last of all.
///
/// This balance is a 'reserve' balance that other subsystems use in
/// order to set aside tokens that are still 'owned' by the account
/// holder, but which are suspendable.
pub reserved: Balance,
/// The amount that `free` may not drop below when withdrawing.
pub frozen: Balance,
}
impl<Balance: Saturating + Copy + Ord> AccountData<Balance> {
/// The amount that this account's free balance may not be reduced
/// beyond.
pub(crate) fn frozen(&self) -> Balance {
self.frozen
}
/// The total balance in this account including any that is reserved and
/// ignoring any frozen.
fn total(&self) -> Balance {
self.free.saturating_add(self.reserved)
}
}
pub use module::*;
#[frame_support::pallet]
pub mod module {
use orml_traits::currency::MutationHooks;
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The balance type
type Balance: Parameter
+ Member
+ AtLeast32BitUnsigned
+ Default
+ Copy
+ MaybeSerializeDeserialize
+ MaxEncodedLen
+ FixedPointOperand;
/// The amount type, should be signed version of `Balance`
type Amount: Signed
+ TryInto<Self::Balance>
+ TryFrom<Self::Balance>
+ Parameter
+ Member
+ arithmetic::SimpleArithmetic
+ Default
+ Copy
+ MaybeSerializeDeserialize
+ MaxEncodedLen;
/// The currency ID type
type CurrencyId: Parameter + Member + Copy + MaybeSerializeDeserialize + Ord + TypeInfo + MaxEncodedLen;
/// Weight information for extrinsics in this module.
type WeightInfo: WeightInfo;
/// The minimum amount required to keep an account.
/// It's deprecated to config 0 as ED for any currency_id,
/// zero ED will retain account even if its total is zero.
/// Since accounts of orml_tokens are also used as providers of
/// System::AccountInfo, zero ED may cause some problems.
type ExistentialDeposits: GetByKey<Self::CurrencyId, Self::Balance>;
/// Hooks are actions that are executed on certain events.
/// For example: OnDust, OnNewTokenAccount
type CurrencyHooks: MutationHooks<Self::AccountId, Self::CurrencyId, Self::Balance>;
#[pallet::constant]
type MaxLocks: Get<u32>;
/// The maximum number of named reserves that can exist on an account.
#[pallet::constant]
type MaxReserves: Get<u32>;
/// The id type for named reserves.
type ReserveIdentifier: Parameter + Member + MaxEncodedLen + Ord + Copy;
// The whitelist of accounts that will not be reaped even if its total
// is zero or below ED.
type DustRemovalWhitelist: Contains<Self::AccountId>;
}
#[pallet::error]
pub enum Error<T> {
/// The balance is too low
BalanceTooLow,
/// Cannot convert Amount into Balance type
AmountIntoBalanceFailed,
/// Failed because liquidity restrictions due to locking
LiquidityRestrictions,
/// Failed because the maximum locks was exceeded
MaxLocksExceeded,
/// Transfer/payment would kill account
KeepAlive,
/// Value too low to create account due to existential deposit
ExistentialDeposit,
/// Beneficiary account must pre-exist
DeadAccount,
// Number of named reserves exceed `T::MaxReserves`
TooManyReserves,
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
/// An account was created with some free balance.
Endowed {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// An account was removed whose balance was non-zero but below
/// ExistentialDeposit, resulting in an outright loss.
DustLost {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Transfer succeeded.
Transfer {
currency_id: T::CurrencyId,
from: T::AccountId,
to: T::AccountId,
amount: T::Balance,
},
/// Some balance was reserved (moved from free to reserved).
Reserved {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some balance was unreserved (moved from reserved to free).
Unreserved {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some reserved balance was repatriated (moved from reserved to
/// another account).
ReserveRepatriated {
currency_id: T::CurrencyId,
from: T::AccountId,
to: T::AccountId,
amount: T::Balance,
status: BalanceStatus,
},
/// A balance was set by root.
BalanceSet {
currency_id: T::CurrencyId,
who: T::AccountId,
free: T::Balance,
reserved: T::Balance,
},
/// The total issuance of an currency has been set
TotalIssuanceSet {
currency_id: T::CurrencyId,
amount: T::Balance,
},
/// Some balances were withdrawn (e.g. pay for transaction fee)
Withdrawn {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some balances were slashed (e.g. due to mis-behavior)
Slashed {
currency_id: T::CurrencyId,
who: T::AccountId,
free_amount: T::Balance,
reserved_amount: T::Balance,
},
/// Deposited some balance into an account
Deposited {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some funds are locked
LockSet {
lock_id: LockIdentifier,
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some locked funds were unlocked
LockRemoved {
lock_id: LockIdentifier,
currency_id: T::CurrencyId,
who: T::AccountId,
},
/// Some free balance was locked.
Locked {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
/// Some locked balance was freed.
Unlocked {
currency_id: T::CurrencyId,
who: T::AccountId,
amount: T::Balance,
},
Issued {
currency_id: T::CurrencyId,
amount: T::Balance,
},
Rescinded {
currency_id: T::CurrencyId,
amount: T::Balance,
},
}
/// The total issuance of a token type.
#[pallet::storage]
#[pallet::getter(fn total_issuance)]
pub type TotalIssuance<T: Config> = StorageMap<_, Twox64Concat, T::CurrencyId, T::Balance, ValueQuery>;
/// Any liquidity locks of a token type under an account.
/// NOTE: Should only be accessed when setting, changing and freeing a lock.
#[pallet::storage]
#[pallet::getter(fn locks)]
pub type Locks<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::AccountId,
Twox64Concat,
T::CurrencyId,
BoundedVec<BalanceLock<T::Balance>, T::MaxLocks>,
ValueQuery,
>;
/// The balance of a token type under an account.
///
/// NOTE: If the total is ever zero, decrease account ref account.
///
/// NOTE: This is only used in the case that this module is used to store
/// balances.
#[pallet::storage]
#[pallet::getter(fn accounts)]
pub type Accounts<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::AccountId,
Twox64Concat,
T::CurrencyId,
AccountData<T::Balance>,
ValueQuery,
>;
/// Named reserves on some account balances.
#[pallet::storage]
#[pallet::getter(fn reserves)]
pub type Reserves<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::AccountId,
Twox64Concat,
T::CurrencyId,
BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves>,
ValueQuery,
>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub balances: Vec<(T::AccountId, T::CurrencyId, T::Balance)>,
}
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
balances: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
// ensure no duplicates exist.
let unique_endowed_accounts = self
.balances
.iter()
.map(|(account_id, currency_id, _)| (account_id, currency_id))
.collect::<sp_std::collections::btree_set::BTreeSet<_>>();
assert!(
unique_endowed_accounts.len() == self.balances.len(),
"duplicate endowed accounts in genesis."
);
self.balances
.iter()
.for_each(|(account_id, currency_id, initial_balance)| {
assert!(
*initial_balance >= T::ExistentialDeposits::get(currency_id),
"the balance of any account should always be more than existential deposit.",
);
Pallet::<T>::mutate_account(account_id, *currency_id, |account_data, _| {
account_data.free = *initial_balance
});
TotalIssuance::<T>::mutate(*currency_id, |total_issuance| {
*total_issuance = total_issuance
.checked_add(initial_balance)
.expect("total issuance cannot overflow when building genesis")
});
});
}
}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Transfer some liquid free balance to another account.
///
/// `transfer` will set the `FreeBalance` of the sender and receiver.
/// It will decrease the total issuance of the system by the
/// `TransferFee`. If the sender's account is below the existential
/// deposit as a result of the transfer, the account will be reaped.
///
/// The dispatch origin for this call must be `Signed` by the
/// transactor.
///
/// - `dest`: The recipient of the transfer.
/// - `currency_id`: currency type.
/// - `amount`: free balance amount to tranfer.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::transfer())]
pub fn transfer(
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
currency_id: T::CurrencyId,
#[pallet::compact] amount: T::Balance,
) -> DispatchResult {
let from = ensure_signed(origin)?;
let to = T::Lookup::lookup(dest)?;
Self::do_transfer(currency_id, &from, &to, amount, ExistenceRequirement::AllowDeath)
}
/// Transfer all remaining balance to the given account.
///
/// NOTE: This function only attempts to transfer _transferable_
/// balances. This means that any locked, reserved, or existential
/// deposits (when `keep_alive` is `true`), will not be transferred by
/// this function. To ensure that this function results in a killed
/// account, you might need to prepare the account by removing any
/// reference counters, storage deposits, etc...
///
/// The dispatch origin for this call must be `Signed` by the
/// transactor.
///
/// - `dest`: The recipient of the transfer.
/// - `currency_id`: currency type.
/// - `keep_alive`: A boolean to determine if the `transfer_all`
/// operation should send all of the funds the account has, causing
/// the sender account to be killed (false), or transfer everything
/// except at least the existential deposit, which will guarantee to
/// keep the sender account alive (true).
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::transfer_all())]
pub fn transfer_all(
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
currency_id: T::CurrencyId,
keep_alive: bool,
) -> DispatchResult {
let from = ensure_signed(origin)?;
let to = T::Lookup::lookup(dest)?;
let preservation = if keep_alive {
Preservation::Protect
} else {
Preservation::Expendable
};
let reducible_balance = <Self as fungibles::Inspect<T::AccountId>>::reducible_balance(
currency_id,
&from,
preservation,
Fortitude::Polite,
);
<Self as fungibles::Mutate<_>>::transfer(currency_id, &from, &to, reducible_balance, preservation)
.map(|_| ())
}
/// Same as the [`transfer`] call, but with a check that the transfer
/// will not kill the origin account.
///
/// 99% of the time you want [`transfer`] instead.
///
/// The dispatch origin for this call must be `Signed` by the
/// transactor.
///
/// - `dest`: The recipient of the transfer.
/// - `currency_id`: currency type.
/// - `amount`: free balance amount to tranfer.
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::transfer_keep_alive())]
pub fn transfer_keep_alive(
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
currency_id: T::CurrencyId,
#[pallet::compact] amount: T::Balance,
) -> DispatchResultWithPostInfo {
let from = ensure_signed(origin)?;
let to = T::Lookup::lookup(dest)?;
Self::do_transfer(currency_id, &from, &to, amount, ExistenceRequirement::KeepAlive)?;
Ok(().into())
}
/// Exactly as `transfer`, except the origin must be root and the source
/// account may be specified.
///
/// The dispatch origin for this call must be _Root_.
///
/// - `source`: The sender of the transfer.
/// - `dest`: The recipient of the transfer.
/// - `currency_id`: currency type.
/// - `amount`: free balance amount to tranfer.
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::force_transfer())]
pub fn force_transfer(
origin: OriginFor<T>,
source: <T::Lookup as StaticLookup>::Source,
dest: <T::Lookup as StaticLookup>::Source,
currency_id: T::CurrencyId,
#[pallet::compact] amount: T::Balance,
) -> DispatchResult {
ensure_root(origin)?;
let from = T::Lookup::lookup(source)?;
let to = T::Lookup::lookup(dest)?;
Self::do_transfer(currency_id, &from, &to, amount, ExistenceRequirement::AllowDeath)
}
/// Set the balances of a given account.
///
/// This will alter `FreeBalance` and `ReservedBalance` in storage. it
/// will also decrease the total issuance of the system
/// (`TotalIssuance`). If the new free or reserved balance is below the
/// existential deposit, it will reap the `AccountInfo`.
///
/// The dispatch origin for this call is `root`.
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::set_balance())]
pub fn set_balance(
origin: OriginFor<T>,
who: <T::Lookup as StaticLookup>::Source,
currency_id: T::CurrencyId,
#[pallet::compact] new_free: T::Balance,
#[pallet::compact] new_reserved: T::Balance,
) -> DispatchResult {
ensure_root(origin)?;
let who = T::Lookup::lookup(who)?;
Self::try_mutate_account(&who, currency_id, |account, _| -> DispatchResult {
let mut new_total = new_free.checked_add(&new_reserved).ok_or(ArithmeticError::Overflow)?;
let (new_free, new_reserved) = if new_total < T::ExistentialDeposits::get(¤cy_id) {
new_total = Zero::zero();
(Zero::zero(), Zero::zero())
} else {
(new_free, new_reserved)
};
let old_total = account.total();
account.free = new_free;
account.reserved = new_reserved;
if new_total > old_total {
TotalIssuance::<T>::try_mutate(currency_id, |t| -> DispatchResult {
*t = t
.checked_add(&(new_total.defensive_saturating_sub(old_total)))
.ok_or(ArithmeticError::Overflow)?;
Ok(())
})?;
} else if new_total < old_total {
TotalIssuance::<T>::try_mutate(currency_id, |t| -> DispatchResult {
*t = t
.checked_sub(&(old_total.defensive_saturating_sub(new_total)))
.ok_or(ArithmeticError::Underflow)?;
Ok(())
})?;
}
Self::deposit_event(Event::BalanceSet {
currency_id,
who: who.clone(),
free: new_free,
reserved: new_reserved,
});
Ok(())
})?;
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
pub(crate) fn deposit_consequence(
_who: &T::AccountId,
currency_id: T::CurrencyId,
amount: T::Balance,
account: &AccountData<T::Balance>,
) -> DepositConsequence {
if amount.is_zero() {
return DepositConsequence::Success;
}
if TotalIssuance::<T>::get(currency_id).checked_add(&amount).is_none() {
return DepositConsequence::Overflow;
}
let new_total_balance = match account.total().checked_add(&amount) {
Some(x) => x,
None => return DepositConsequence::Overflow,
};
if new_total_balance < T::ExistentialDeposits::get(¤cy_id) {
return DepositConsequence::BelowMinimum;
}
// NOTE: We assume that we are a provider, so don't need to do any checks in the
// case of account creation.
DepositConsequence::Success
}
pub(crate) fn withdraw_consequence(
who: &T::AccountId,
currency_id: T::CurrencyId,
amount: T::Balance,
account: &AccountData<T::Balance>,
) -> WithdrawConsequence<T::Balance> {
if amount.is_zero() {
return WithdrawConsequence::Success;
}
if TotalIssuance::<T>::get(currency_id).checked_sub(&amount).is_none() {
return WithdrawConsequence::Underflow;
}
let new_total_balance = match account.total().checked_sub(&amount) {
Some(x) => x,
None => return WithdrawConsequence::BalanceLow,
};
// Provider restriction - total account balance cannot be reduced to zero if it
// cannot sustain the loss of a provider reference.
// NOTE: This assumes that the pallet is a provider (which is true). Is this
// ever changes, then this will need to adapt accordingly.
let ed = T::ExistentialDeposits::get(¤cy_id);
let success = if new_total_balance < ed {
if frame_system::Pallet::<T>::can_dec_provider(who) {
WithdrawConsequence::ReducedToZero(new_total_balance)
} else {
return WithdrawConsequence::WouldDie;
}
} else {
WithdrawConsequence::Success
};
// Enough free funds to have them be reduced.
let new_free_balance = match account.free.checked_sub(&amount) {
Some(b) => b,
None => return WithdrawConsequence::BalanceLow,
};
// Eventual free funds must be no less than the frozen balance.
if new_free_balance < account.frozen() {
return WithdrawConsequence::Frozen;
}
success
}
// Ensure that an account can withdraw from their free balance given any
// existing withdrawal restrictions like locks and vesting balance.
// Is a no-op if amount to be withdrawn is zero.
pub(crate) fn ensure_can_withdraw(
currency_id: T::CurrencyId,
who: &T::AccountId,
amount: T::Balance,
) -> DispatchResult {
if amount.is_zero() {
return Ok(());
}
let new_balance = Self::free_balance(currency_id, who)
.checked_sub(&amount)
.ok_or(Error::<T>::BalanceTooLow)?;
ensure!(
new_balance >= Self::accounts(who, currency_id).frozen(),
Error::<T>::LiquidityRestrictions
);
Ok(())
}
pub(crate) fn try_mutate_account<R, E>(
who: &T::AccountId,
currency_id: T::CurrencyId,
f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> sp_std::result::Result<R, E>,
) -> sp_std::result::Result<(R, Option<T::Balance>), E> {
Accounts::<T>::try_mutate_exists(who, currency_id, |maybe_account| {
let existed = maybe_account.is_some();
let mut account = maybe_account.take().unwrap_or_default();
f(&mut account, existed).map(move |result| {
let maybe_endowed = if !existed { Some(account.free) } else { None };
let mut maybe_dust: Option<T::Balance> = None;
let total = account.total();
*maybe_account = if total < T::ExistentialDeposits::get(¤cy_id) {
// if ED is not zero, but account total is zero, account will be reaped
if total.is_zero() {
None
} else {
if !T::DustRemovalWhitelist::contains(who) {
maybe_dust = Some(total);
}
Some(account)
}
} else {
// Note: if ED is zero, account will never be reaped
Some(account)
};
(maybe_endowed, existed, maybe_account.is_some(), maybe_dust, result)
})
})
.map(|(maybe_endowed, existed, exists, maybe_dust, result)| {
if existed && !exists {
// If existed before, decrease account provider.
// Ignore the result, because if it failed then there are remaining consumers,
// and the account storage in frame_system shouldn't be reaped.
let _ = frame_system::Pallet::<T>::dec_providers(who);
<T::CurrencyHooks as MutationHooks<T::AccountId, T::CurrencyId, T::Balance>>::OnKilledTokenAccount::happened(&(who.clone(), currency_id));
} else if !existed && exists {
// if new, increase account provider
frame_system::Pallet::<T>::inc_providers(who);
<T::CurrencyHooks as MutationHooks<T::AccountId, T::CurrencyId, T::Balance>>::OnNewTokenAccount::happened(&(who.clone(), currency_id));
}
if let Some(endowed) = maybe_endowed {
Self::deposit_event(Event::Endowed {
currency_id,
who: who.clone(),
amount: endowed,
});
}
if let Some(dust_amount) = maybe_dust {
// `OnDust` maybe get/set storage `Accounts` of `who`, trigger handler here
// to avoid some unexpected errors.
<T::CurrencyHooks as MutationHooks<T::AccountId, T::CurrencyId, T::Balance>>::OnDust::on_dust(who, currency_id, dust_amount);
Self::deposit_event(Event::DustLost {
currency_id,
who: who.clone(),
amount: dust_amount,
});
}
(result, maybe_dust)
})
}
pub(crate) fn mutate_account<R>(
who: &T::AccountId,
currency_id: T::CurrencyId,
f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> R,
) -> (R, Option<T::Balance>) {
Self::try_mutate_account(who, currency_id, |account, existed| -> Result<R, Infallible> {
Ok(f(account, existed))
})
.expect("Error is infallible; qed")
}
/// Set free balance of `who` to a new value.
///
/// Note: this will not maintain total issuance, and the caller is expected
/// to do it. If it will cause the account to be removed dust, shouldn't use
/// it, because maybe the account that should be reaped to remain due to
/// failed transfer/withdraw dust.
pub(crate) fn set_free_balance(currency_id: T::CurrencyId, who: &T::AccountId, amount: T::Balance) {
Self::mutate_account(who, currency_id, |account, _| {
account.free = amount;
Self::deposit_event(Event::BalanceSet {
currency_id,
who: who.clone(),
free: account.free,
reserved: account.reserved,
});
});
}
/// Set reserved balance of `who` to a new value.
///
/// Note: this will not maintain total issuance, and the caller is expected
/// to do it. If it will cause the account to be removed dust, shouldn't use
/// it, because maybe the account that should be reaped to remain due to
/// failed transfer/withdraw dust.
pub(crate) fn set_reserved_balance(currency_id: T::CurrencyId, who: &T::AccountId, amount: T::Balance) {
Self::mutate_account(who, currency_id, |account, _| {
account.reserved = amount;
Self::deposit_event(Event::BalanceSet {
currency_id,
who: who.clone(),
free: account.free,
reserved: account.reserved,
});
});
}
/// Update the account entry for `who` under `currency_id`, given the
/// locks.
pub(crate) fn update_locks(
currency_id: T::CurrencyId,
who: &T::AccountId,
locks: &[BalanceLock<T::Balance>],
) -> DispatchResult {
// track lock delta
let mut total_frozen_prev = Zero::zero();
let mut total_frozen_after = Zero::zero();
// update account data
Self::mutate_account(who, currency_id, |account, _| {
total_frozen_prev = account.frozen;
account.frozen = Zero::zero();
for lock in locks.iter() {
account.frozen = account.frozen.max(lock.amount);
}
total_frozen_after = account.frozen;
});
// update locks
let existed = Locks::<T>::contains_key(who, currency_id);
if locks.is_empty() {
Locks::<T>::remove(who, currency_id);
if existed {
// decrease account ref count when destruct lock
frame_system::Pallet::<T>::dec_consumers(who);
}
} else {
let bounded_locks: BoundedVec<BalanceLock<T::Balance>, T::MaxLocks> =
locks.to_vec().try_into().map_err(|_| Error::<T>::MaxLocksExceeded)?;
Locks::<T>::insert(who, currency_id, bounded_locks);
if !existed {
// increase account ref count when initialize lock
if frame_system::Pallet::<T>::inc_consumers(who).is_err() {
// No providers for the locks. This is impossible under normal circumstances
// since the funds that are under the lock will themselves be stored in the
// account and therefore will need a reference.
log::warn!(
"Warning: Attempt to introduce lock consumer reference, yet no providers. \
This is unexpected but should be safe."
);
}
}
}
if total_frozen_prev < total_frozen_after {
let amount = total_frozen_after.saturating_sub(total_frozen_prev);
Self::deposit_event(Event::Locked {
currency_id,
who: who.clone(),
amount,
});
} else if total_frozen_prev > total_frozen_after {
let amount = total_frozen_prev.saturating_sub(total_frozen_after);
Self::deposit_event(Event::Unlocked {
currency_id,
who: who.clone(),
amount,
});
}
Ok(())
}
/// Transfer some free balance from `from` to `to`. Ensure from_account
/// allow death or new balance will not be reaped, and ensure
/// to_account will not be removed dust.
///
/// Is a no-op if value to be transferred is zero or the `from` is the same
/// as `to`.
pub(crate) fn do_transfer(
currency_id: T::CurrencyId,
from: &T::AccountId,
to: &T::AccountId,
amount: T::Balance,
existence_requirement: ExistenceRequirement,
) -> DispatchResult {
if amount.is_zero() || from == to {
return Ok(());
}
<T::CurrencyHooks as MutationHooks<T::AccountId, T::CurrencyId, T::Balance>>::PreTransfer::on_transfer(
currency_id,
from,
to,
amount,
)?;
Self::try_mutate_account(to, currency_id, |to_account, _existed| -> DispatchResult {
Self::try_mutate_account(from, currency_id, |from_account, _existed| -> DispatchResult {
from_account.free = from_account
.free
.checked_sub(&amount)
.ok_or(Error::<T>::BalanceTooLow)?;
to_account.free = to_account.free.checked_add(&amount).ok_or(ArithmeticError::Overflow)?;
let ed = T::ExistentialDeposits::get(¤cy_id);
// if the total of `to_account` is below existential deposit, would return an
// error.
// Note: if `to_account` is in `T::DustRemovalWhitelist`, can bypass this check.
ensure!(
to_account.total() >= ed || T::DustRemovalWhitelist::contains(to),
Error::<T>::ExistentialDeposit
);
Self::ensure_can_withdraw(currency_id, from, amount)?;
let allow_death = existence_requirement == ExistenceRequirement::AllowDeath;
let allow_death = allow_death && frame_system::Pallet::<T>::can_dec_provider(from);
let would_be_dead = if from_account.total() < ed {
if from_account.total().is_zero() {
true
} else {
// Note: if account is not in `T::DustRemovalWhitelist`, account will eventually
// be reaped due to the dust removal.
!T::DustRemovalWhitelist::contains(from)
}
} else {
false
};
ensure!(allow_death || !would_be_dead, Error::<T>::KeepAlive);
Ok(())
})?;
Ok(())
})?;