1#![cfg_attr(not(feature = "std"), no_std)]
145mod benchmarking;
146mod impl_currency;
147mod impl_fungible;
148pub mod migration;
149mod tests;
150mod types;
151pub mod weights;
152
153extern crate alloc;
154
155use alloc::{
156 format,
157 string::{String, ToString},
158 vec::Vec,
159};
160use codec::{Codec, MaxEncodedLen};
161use core::{cmp, fmt::Debug, mem, result};
162use frame_support::{
163 ensure,
164 pallet_prelude::DispatchResult,
165 traits::{
166 tokens::{
167 fungible, BalanceStatus as Status, DepositConsequence,
168 Fortitude::{self, Force, Polite},
169 IdAmount,
170 Preservation::{Expendable, Preserve, Protect},
171 WithdrawConsequence,
172 },
173 Currency, Defensive, Get, OnUnbalanced, ReservableCurrency, StoredMap,
174 },
175 BoundedSlice, WeakBoundedVec,
176};
177use frame_system as system;
178pub use impl_currency::{NegativeImbalance, PositiveImbalance};
179use scale_info::TypeInfo;
180use sp_core::{sr25519::Pair as SrPair, Pair};
181use sp_runtime::{
182 traits::{
183 AtLeast32BitUnsigned, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Saturating,
184 StaticLookup, Zero,
185 },
186 ArithmeticError, DispatchError, FixedPointOperand, Perbill, TokenError,
187};
188
189pub use types::{
190 AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData,
191};
192pub use weights::WeightInfo;
193
194pub use pallet::*;
195
196const LOG_TARGET: &str = "runtime::balances";
197
198const DEFAULT_ADDRESS_URI: &str = "//Sender//{}";
200
201type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
202
203#[frame_support::pallet]
204pub mod pallet {
205 use super::*;
206 use codec::HasCompact;
207 use frame_support::{
208 pallet_prelude::*,
209 traits::{fungible::Credit, tokens::Precision, VariantCount, VariantCountOf},
210 };
211 use frame_system::pallet_prelude::*;
212
213 pub type CreditOf<T, I> = Credit<<T as frame_system::Config>::AccountId, Pallet<T, I>>;
214
215 pub mod config_preludes {
217 use super::*;
218 use frame_support::derive_impl;
219
220 pub struct TestDefaultConfig;
221
222 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
223 impl frame_system::DefaultConfig for TestDefaultConfig {}
224
225 #[frame_support::register_default_impl(TestDefaultConfig)]
226 impl DefaultConfig for TestDefaultConfig {
227 #[inject_runtime_type]
228 type RuntimeEvent = ();
229 #[inject_runtime_type]
230 type RuntimeHoldReason = ();
231 #[inject_runtime_type]
232 type RuntimeFreezeReason = ();
233
234 type Balance = u64;
235 type ExistentialDeposit = ConstUint<1>;
236
237 type ReserveIdentifier = ();
238 type FreezeIdentifier = Self::RuntimeFreezeReason;
239
240 type DustRemoval = ();
241
242 type MaxLocks = ConstU32<100>;
243 type MaxReserves = ConstU32<100>;
244 type MaxFreezes = VariantCountOf<Self::RuntimeFreezeReason>;
245
246 type WeightInfo = ();
247 type DoneSlashHandler = ();
248 }
249 }
250
251 #[pallet::config(with_default)]
252 pub trait Config<I: 'static = ()>: frame_system::Config {
253 #[pallet::no_default_bounds]
255 #[allow(deprecated)]
256 type RuntimeEvent: From<Event<Self, I>>
257 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
258
259 #[pallet::no_default_bounds]
261 type RuntimeHoldReason: Parameter + Member + MaxEncodedLen + Copy + VariantCount;
262
263 #[pallet::no_default_bounds]
265 type RuntimeFreezeReason: VariantCount;
266
267 type WeightInfo: WeightInfo;
269
270 type Balance: Parameter
272 + Member
273 + AtLeast32BitUnsigned
274 + Codec
275 + HasCompact<Type: DecodeWithMemTracking>
276 + Default
277 + Copy
278 + MaybeSerializeDeserialize
279 + Debug
280 + MaxEncodedLen
281 + TypeInfo
282 + FixedPointOperand;
283
284 #[pallet::no_default_bounds]
286 type DustRemoval: OnUnbalanced<CreditOf<Self, I>>;
287
288 #[pallet::constant]
297 #[pallet::no_default_bounds]
298 type ExistentialDeposit: Get<Self::Balance>;
299
300 #[pallet::no_default]
302 type AccountStore: StoredMap<Self::AccountId, AccountData<Self::Balance>>;
303
304 type ReserveIdentifier: Parameter + Member + MaxEncodedLen + Ord + Copy;
308
309 type FreezeIdentifier: Parameter + Member + MaxEncodedLen + Copy;
311
312 #[pallet::constant]
317 type MaxLocks: Get<u32>;
318
319 #[pallet::constant]
323 type MaxReserves: Get<u32>;
324
325 #[pallet::constant]
327 type MaxFreezes: Get<u32>;
328
329 type DoneSlashHandler: fungible::hold::DoneSlash<
332 Self::RuntimeHoldReason,
333 Self::AccountId,
334 Self::Balance,
335 >;
336 }
337
338 const STORAGE_VERSION: frame_support::traits::StorageVersion =
340 frame_support::traits::StorageVersion::new(1);
341
342 #[pallet::pallet]
343 #[pallet::storage_version(STORAGE_VERSION)]
344 pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
345
346 #[pallet::event]
347 #[pallet::generate_deposit(pub(super) fn deposit_event)]
348 pub enum Event<T: Config<I>, I: 'static = ()> {
349 Endowed { account: T::AccountId, free_balance: T::Balance },
351 DustLost { account: T::AccountId, amount: T::Balance },
354 Transfer { from: T::AccountId, to: T::AccountId, amount: T::Balance },
356 BalanceSet { who: T::AccountId, free: T::Balance },
358 Reserved { who: T::AccountId, amount: T::Balance },
360 Unreserved { who: T::AccountId, amount: T::Balance },
362 ReserveRepatriated {
365 from: T::AccountId,
366 to: T::AccountId,
367 amount: T::Balance,
368 destination_status: Status,
369 },
370 Deposit { who: T::AccountId, amount: T::Balance },
372 Withdraw { who: T::AccountId, amount: T::Balance },
374 Slashed { who: T::AccountId, amount: T::Balance },
376 Minted { who: T::AccountId, amount: T::Balance },
378 MintedCredit { amount: T::Balance },
380 Burned { who: T::AccountId, amount: T::Balance },
382 BurnedDebt { amount: T::Balance },
384 Suspended { who: T::AccountId, amount: T::Balance },
386 Restored { who: T::AccountId, amount: T::Balance },
388 Upgraded { who: T::AccountId },
390 Issued { amount: T::Balance },
392 Rescinded { amount: T::Balance },
394 Locked { who: T::AccountId, amount: T::Balance },
396 Unlocked { who: T::AccountId, amount: T::Balance },
398 Frozen { who: T::AccountId, amount: T::Balance },
400 Thawed { who: T::AccountId, amount: T::Balance },
402 TotalIssuanceForced { old: T::Balance, new: T::Balance },
404 Held { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
406 BurnedHeld { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
408 TransferOnHold {
410 reason: T::RuntimeHoldReason,
411 source: T::AccountId,
412 dest: T::AccountId,
413 amount: T::Balance,
414 },
415 TransferAndHold {
417 reason: T::RuntimeHoldReason,
418 source: T::AccountId,
419 dest: T::AccountId,
420 transferred: T::Balance,
421 },
422 Released { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
424 Unexpected(UnexpectedKind),
426 }
427
428 #[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, Debug)]
432 pub enum UnexpectedKind {
433 BalanceUpdated,
435 FailedToMutateAccount,
438 }
439
440 #[pallet::error]
441 pub enum Error<T, I = ()> {
442 VestingBalance,
444 LiquidityRestrictions,
446 InsufficientBalance,
448 ExistentialDeposit,
450 Expendability,
452 ExistingVestingSchedule,
454 DeadAccount,
456 TooManyReserves,
458 TooManyHolds,
460 TooManyFreezes,
462 IssuanceDeactivated,
464 DeltaZero,
466 }
467
468 #[pallet::storage]
470 #[pallet::whitelist_storage]
471 pub type TotalIssuance<T: Config<I>, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery>;
472
473 #[pallet::storage]
479 #[pallet::whitelist_storage]
480 pub type InactiveIssuance<T: Config<I>, I: 'static = ()> =
481 StorageValue<_, T::Balance, ValueQuery>;
482
483 #[pallet::storage]
508 pub type Account<T: Config<I>, I: 'static = ()> =
509 StorageMap<_, Blake2_128Concat, T::AccountId, AccountData<T::Balance>, ValueQuery>;
510
511 #[pallet::storage]
516 pub type Locks<T: Config<I>, I: 'static = ()> = StorageMap<
517 _,
518 Blake2_128Concat,
519 T::AccountId,
520 WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks>,
521 ValueQuery,
522 >;
523
524 #[pallet::storage]
528 pub type Reserves<T: Config<I>, I: 'static = ()> = StorageMap<
529 _,
530 Blake2_128Concat,
531 T::AccountId,
532 BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves>,
533 ValueQuery,
534 >;
535
536 #[pallet::storage]
538 pub type Holds<T: Config<I>, I: 'static = ()> = StorageMap<
539 _,
540 Blake2_128Concat,
541 T::AccountId,
542 BoundedVec<
543 IdAmount<T::RuntimeHoldReason, T::Balance>,
544 VariantCountOf<T::RuntimeHoldReason>,
545 >,
546 ValueQuery,
547 >;
548
549 #[pallet::storage]
551 pub type Freezes<T: Config<I>, I: 'static = ()> = StorageMap<
552 _,
553 Blake2_128Concat,
554 T::AccountId,
555 BoundedVec<IdAmount<T::FreezeIdentifier, T::Balance>, T::MaxFreezes>,
556 ValueQuery,
557 >;
558
559 #[pallet::genesis_config]
560 pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
561 pub balances: Vec<(T::AccountId, T::Balance)>,
562 pub dev_accounts: Option<(u32, T::Balance, Option<String>)>,
569 }
570
571 impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
572 fn default() -> Self {
573 Self { balances: Default::default(), dev_accounts: None }
574 }
575 }
576
577 #[pallet::genesis_build]
578 impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
579 fn build(&self) {
580 let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n);
581
582 <TotalIssuance<T, I>>::put(total);
583
584 for (_, balance) in &self.balances {
585 assert!(
586 *balance >= <T as Config<I>>::ExistentialDeposit::get(),
587 "the balance of any account should always be at least the existential deposit.",
588 )
589 }
590
591 let endowed_accounts = self
593 .balances
594 .iter()
595 .map(|(x, _)| x)
596 .cloned()
597 .collect::<alloc::collections::btree_set::BTreeSet<_>>();
598
599 assert!(
600 endowed_accounts.len() == self.balances.len(),
601 "duplicate balances in genesis."
602 );
603
604 if let Some((num_accounts, balance, ref derivation)) = self.dev_accounts {
606 Pallet::<T, I>::derive_dev_account(
608 num_accounts,
609 balance,
610 derivation.as_deref().unwrap_or(DEFAULT_ADDRESS_URI),
611 );
612 }
613 for &(ref who, free) in self.balances.iter() {
614 frame_system::Pallet::<T>::inc_providers(who);
615 assert!(T::AccountStore::insert(who, AccountData { free, ..Default::default() })
616 .is_ok());
617 }
618 }
619 }
620
621 #[pallet::hooks]
622 impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
623 fn integrity_test() {
624 #[cfg(not(feature = "insecure_zero_ed"))]
625 assert!(
626 !<T as Config<I>>::ExistentialDeposit::get().is_zero(),
627 "The existential deposit must be greater than zero!"
628 );
629
630 assert!(
631 T::MaxFreezes::get() >= <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
632 "MaxFreezes should be greater than or equal to the number of freeze reasons: {} < {}",
633 T::MaxFreezes::get(), <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
634 );
635 }
636
637 #[cfg(feature = "try-runtime")]
638 fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
639 Self::do_try_state(n)
640 }
641 }
642
643 #[pallet::call(weight(<T as Config<I>>::WeightInfo))]
644 impl<T: Config<I>, I: 'static> Pallet<T, I> {
645 #[pallet::call_index(0)]
653 pub fn transfer_allow_death(
654 origin: OriginFor<T>,
655 dest: AccountIdLookupOf<T>,
656 #[pallet::compact] value: T::Balance,
657 ) -> DispatchResult {
658 let source = ensure_signed(origin)?;
659 let dest = T::Lookup::lookup(dest)?;
660 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
661 Ok(())
662 }
663
664 #[pallet::call_index(2)]
667 pub fn force_transfer(
668 origin: OriginFor<T>,
669 source: AccountIdLookupOf<T>,
670 dest: AccountIdLookupOf<T>,
671 #[pallet::compact] value: T::Balance,
672 ) -> DispatchResult {
673 ensure_root(origin)?;
674 let source = T::Lookup::lookup(source)?;
675 let dest = T::Lookup::lookup(dest)?;
676 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
677 Ok(())
678 }
679
680 #[pallet::call_index(3)]
687 pub fn transfer_keep_alive(
688 origin: OriginFor<T>,
689 dest: AccountIdLookupOf<T>,
690 #[pallet::compact] value: T::Balance,
691 ) -> DispatchResult {
692 let source = ensure_signed(origin)?;
693 let dest = T::Lookup::lookup(dest)?;
694 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Preserve)?;
695 Ok(())
696 }
697
698 #[pallet::call_index(4)]
714 pub fn transfer_all(
715 origin: OriginFor<T>,
716 dest: AccountIdLookupOf<T>,
717 keep_alive: bool,
718 ) -> DispatchResult {
719 let transactor = ensure_signed(origin)?;
720 let keep_alive = if keep_alive { Preserve } else { Expendable };
721 let reducible_balance = <Self as fungible::Inspect<_>>::reducible_balance(
722 &transactor,
723 keep_alive,
724 Fortitude::Polite,
725 );
726 let dest = T::Lookup::lookup(dest)?;
727 <Self as fungible::Mutate<_>>::transfer(
728 &transactor,
729 &dest,
730 reducible_balance,
731 keep_alive,
732 )?;
733 Ok(())
734 }
735
736 #[pallet::call_index(5)]
740 pub fn force_unreserve(
741 origin: OriginFor<T>,
742 who: AccountIdLookupOf<T>,
743 amount: T::Balance,
744 ) -> DispatchResult {
745 ensure_root(origin)?;
746 let who = T::Lookup::lookup(who)?;
747 let _leftover = <Self as ReservableCurrency<_>>::unreserve(&who, amount);
748 Ok(())
749 }
750
751 #[pallet::call_index(6)]
760 #[pallet::weight(T::WeightInfo::upgrade_accounts(who.len() as u32))]
761 pub fn upgrade_accounts(
762 origin: OriginFor<T>,
763 who: Vec<T::AccountId>,
764 ) -> DispatchResultWithPostInfo {
765 ensure_signed(origin)?;
766 if who.is_empty() {
767 return Ok(Pays::Yes.into());
768 }
769 let mut upgrade_count = 0;
770 for i in &who {
771 let upgraded = Self::ensure_upgraded(i);
772 if upgraded {
773 upgrade_count.saturating_inc();
774 }
775 }
776 let proportion_upgraded = Perbill::from_rational(upgrade_count, who.len() as u32);
777 if proportion_upgraded >= Perbill::from_percent(90) {
778 Ok(Pays::No.into())
779 } else {
780 Ok(Pays::Yes.into())
781 }
782 }
783
784 #[pallet::call_index(8)]
788 #[pallet::weight(
789 T::WeightInfo::force_set_balance_creating() .max(T::WeightInfo::force_set_balance_killing()) )]
792 pub fn force_set_balance(
793 origin: OriginFor<T>,
794 who: AccountIdLookupOf<T>,
795 #[pallet::compact] new_free: T::Balance,
796 ) -> DispatchResult {
797 ensure_root(origin)?;
798 let who = T::Lookup::lookup(who)?;
799 let existential_deposit = Self::ed();
800
801 let wipeout = new_free < existential_deposit;
802 let new_free = if wipeout { Zero::zero() } else { new_free };
803
804 let old_free = Self::mutate_account_handling_dust(&who, false, |account| {
806 let old_free = account.free;
807 account.free = new_free;
808 old_free
809 })?;
810
811 if new_free > old_free {
814 mem::drop(PositiveImbalance::<T, I>::new(new_free - old_free));
815 } else if new_free < old_free {
816 mem::drop(NegativeImbalance::<T, I>::new(old_free - new_free));
817 }
818
819 Self::deposit_event(Event::BalanceSet { who, free: new_free });
820 Ok(())
821 }
822
823 #[doc = docify::embed!("./src/tests/dispatchable_tests.rs", force_adjust_total_issuance_example)]
829 #[pallet::call_index(9)]
830 #[pallet::weight(T::WeightInfo::force_adjust_total_issuance())]
831 pub fn force_adjust_total_issuance(
832 origin: OriginFor<T>,
833 direction: AdjustmentDirection,
834 #[pallet::compact] delta: T::Balance,
835 ) -> DispatchResult {
836 ensure_root(origin)?;
837
838 ensure!(delta > Zero::zero(), Error::<T, I>::DeltaZero);
839
840 let old = TotalIssuance::<T, I>::get();
841 let new = match direction {
842 AdjustmentDirection::Increase => old.saturating_add(delta),
843 AdjustmentDirection::Decrease => old.saturating_sub(delta),
844 };
845
846 ensure!(InactiveIssuance::<T, I>::get() <= new, Error::<T, I>::IssuanceDeactivated);
847 TotalIssuance::<T, I>::set(new);
848
849 Self::deposit_event(Event::<T, I>::TotalIssuanceForced { old, new });
850
851 Ok(())
852 }
853
854 #[pallet::call_index(10)]
862 #[pallet::weight(if *keep_alive {T::WeightInfo::burn_keep_alive()} else {T::WeightInfo::burn_allow_death()})]
863 pub fn burn(
864 origin: OriginFor<T>,
865 #[pallet::compact] value: T::Balance,
866 keep_alive: bool,
867 ) -> DispatchResult {
868 let source = ensure_signed(origin)?;
869 let preservation = if keep_alive { Preserve } else { Expendable };
870 <Self as fungible::Mutate<_>>::burn_from(
871 &source,
872 value,
873 preservation,
874 Precision::Exact,
875 Polite,
876 )?;
877 Ok(())
878 }
879 }
880
881 impl<T: Config<I>, I: 'static> Pallet<T, I> {
882 pub fn total_issuance() -> T::Balance {
884 TotalIssuance::<T, I>::get()
885 }
886
887 pub fn inactive_issuance() -> T::Balance {
889 InactiveIssuance::<T, I>::get()
890 }
891
892 pub fn locks(who: &T::AccountId) -> WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks> {
894 Locks::<T, I>::get(who)
895 }
896
897 pub fn reserves(
899 who: &T::AccountId,
900 ) -> BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves> {
901 Reserves::<T, I>::get(who)
902 }
903
904 fn ed() -> T::Balance {
905 T::ExistentialDeposit::get()
906 }
907 pub fn ensure_upgraded(who: &T::AccountId) -> bool {
911 let mut a = T::AccountStore::get(who);
912 if a.flags.is_new_logic() {
913 return false;
914 }
915 a.flags.set_new_logic();
916 if !a.reserved.is_zero() && a.frozen.is_zero() {
917 if system::Pallet::<T>::providers(who) == 0 {
918 log::warn!(
922 target: LOG_TARGET,
923 "account with a non-zero reserve balance has no provider refs, account_id: '{:?}'.",
924 who
925 );
926 a.free = a.free.max(Self::ed());
927 system::Pallet::<T>::inc_providers(who);
928 }
929 let _ = system::Pallet::<T>::inc_consumers_without_limit(who).defensive();
930 }
931 let _ = T::AccountStore::try_mutate_exists(who, |account| -> DispatchResult {
933 *account = Some(a);
934 Ok(())
935 });
936 Self::deposit_event(Event::Upgraded { who: who.clone() });
937 return true;
938 }
939
940 pub fn free_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
942 Self::account(who.borrow()).free
943 }
944
945 pub fn usable_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
948 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Expendable, Polite)
949 }
950
951 pub fn usable_balance_for_fees(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
956 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Protect, Polite)
957 }
958
959 pub fn reserved_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
961 Self::account(who.borrow()).reserved
962 }
963
964 pub(crate) fn account(who: &T::AccountId) -> AccountData<T::Balance> {
966 T::AccountStore::get(who)
967 }
968
969 pub(crate) fn mutate_account_handling_dust<R>(
981 who: &T::AccountId,
982 force_consumer_bump: bool,
983 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
984 ) -> Result<R, DispatchError> {
985 let (r, maybe_dust) = Self::mutate_account(who, force_consumer_bump, f)?;
986 if let Some(dust) = maybe_dust {
987 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
988 }
989 Ok(r)
990 }
991
992 pub(crate) fn try_mutate_account_handling_dust<R, E: From<DispatchError>>(
1004 who: &T::AccountId,
1005 force_consumer_bump: bool,
1006 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1007 ) -> Result<R, E> {
1008 let (r, maybe_dust) = Self::try_mutate_account(who, force_consumer_bump, f)?;
1009 if let Some(dust) = maybe_dust {
1010 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1011 }
1012 Ok(r)
1013 }
1014
1015 pub(crate) fn mutate_account<R>(
1032 who: &T::AccountId,
1033 force_consumer_bump: bool,
1034 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
1035 ) -> Result<(R, Option<T::Balance>), DispatchError> {
1036 Self::try_mutate_account(who, force_consumer_bump, |a, _| -> Result<R, DispatchError> {
1037 Ok(f(a))
1038 })
1039 }
1040
1041 #[cfg(not(feature = "insecure_zero_ed"))]
1044 fn have_providers_or_no_zero_ed(_: &T::AccountId) -> bool {
1045 true
1046 }
1047
1048 #[cfg(feature = "insecure_zero_ed")]
1051 fn have_providers_or_no_zero_ed(who: &T::AccountId) -> bool {
1052 frame_system::Pallet::<T>::providers(who) > 0
1053 }
1054
1055 pub(crate) fn try_mutate_account<R, E: From<DispatchError>>(
1069 who: &T::AccountId,
1070 force_consumer_bump: bool,
1071 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1072 ) -> Result<(R, Option<T::Balance>), E> {
1073 Self::ensure_upgraded(who);
1074 let result = T::AccountStore::try_mutate_exists(who, |maybe_account| {
1075 let is_new = maybe_account.is_none();
1076 let mut account = maybe_account.take().unwrap_or_default();
1077 let did_provide =
1078 account.free >= Self::ed() && Self::have_providers_or_no_zero_ed(who);
1079 let did_consume =
1080 !is_new && (!account.reserved.is_zero() || !account.frozen.is_zero());
1081
1082 let result = f(&mut account, is_new)?;
1083
1084 let does_provide = account.free >= Self::ed();
1085 let does_consume = !account.reserved.is_zero() || !account.frozen.is_zero();
1086
1087 if !did_provide && does_provide {
1088 frame_system::Pallet::<T>::inc_providers(who);
1089 }
1090 if did_consume && !does_consume {
1091 frame_system::Pallet::<T>::dec_consumers(who);
1092 }
1093 if !did_consume && does_consume {
1094 if force_consumer_bump {
1095 frame_system::Pallet::<T>::inc_consumers_without_limit(who)?;
1097 } else {
1098 frame_system::Pallet::<T>::inc_consumers(who)?;
1099 }
1100 }
1101 if does_consume && frame_system::Pallet::<T>::consumers(who) == 0 {
1102 log::error!(target: LOG_TARGET, "Defensively bumping a consumer ref.");
1106 frame_system::Pallet::<T>::inc_consumers(who)?;
1107 }
1108 if did_provide && !does_provide {
1109 frame_system::Pallet::<T>::dec_providers(who).inspect_err(|_| {
1111 if did_consume && !does_consume {
1113 let _ = frame_system::Pallet::<T>::inc_consumers(who).defensive();
1114 }
1115 if !did_consume && does_consume {
1116 let _ = frame_system::Pallet::<T>::dec_consumers(who);
1117 }
1118 })?;
1119 }
1120
1121 let maybe_endowed = if is_new { Some(account.free) } else { None };
1122
1123 let ed = Self::ed();
1135 let maybe_dust = if account.free < ed && !does_consume {
1136 if account.free.is_zero() {
1137 None
1138 } else {
1139 Some(account.free)
1140 }
1141 } else {
1142 *maybe_account = Some(account);
1143 None
1144 };
1145 Ok((maybe_endowed, maybe_dust, result))
1146 });
1147 result.map(|(maybe_endowed, maybe_dust, result)| {
1148 if let Some(endowed) = maybe_endowed {
1149 Self::deposit_event(Event::Endowed {
1150 account: who.clone(),
1151 free_balance: endowed,
1152 });
1153 }
1154 if let Some(amount) = maybe_dust {
1155 Pallet::<T, I>::deposit_event(Event::DustLost { account: who.clone(), amount });
1156 }
1157 (result, maybe_dust)
1158 })
1159 }
1160
1161 pub(crate) fn update_locks(who: &T::AccountId, locks: &[BalanceLock<T::Balance>]) {
1163 let bounded_locks = WeakBoundedVec::<_, T::MaxLocks>::force_from(
1164 locks.to_vec(),
1165 Some("Balances Update Locks"),
1166 );
1167
1168 if locks.len() as u32 > T::MaxLocks::get() {
1169 log::warn!(
1170 target: LOG_TARGET,
1171 "Warning: A user has more currency locks than expected. \
1172 A runtime configuration adjustment may be needed."
1173 );
1174 }
1175 let freezes = Freezes::<T, I>::get(who);
1176 let mut prev_frozen = Zero::zero();
1177 let mut after_frozen = Zero::zero();
1178 let res = Self::mutate_account(who, true, |b| {
1181 prev_frozen = b.frozen;
1182 b.frozen = Zero::zero();
1183 for l in locks.iter() {
1184 b.frozen = b.frozen.max(l.amount);
1185 }
1186 for l in freezes.iter() {
1187 b.frozen = b.frozen.max(l.amount);
1188 }
1189 after_frozen = b.frozen;
1190 });
1191 let maybe_dust = match res {
1192 Ok((_, maybe_dust)) => maybe_dust,
1193 Err(_) => {
1194 Self::deposit_event(Event::Unexpected(UnexpectedKind::FailedToMutateAccount));
1195 defensive!("errored in mutate_account");
1196 None
1197 },
1198 };
1199
1200 match locks.is_empty() {
1201 true => Locks::<T, I>::remove(who),
1202 false => Locks::<T, I>::insert(who, bounded_locks),
1203 }
1204
1205 if let Some(dust) = maybe_dust {
1206 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1207 }
1208
1209 if prev_frozen > after_frozen {
1210 let amount = prev_frozen.saturating_sub(after_frozen);
1211 Self::deposit_event(Event::Unlocked { who: who.clone(), amount });
1212 } else if after_frozen > prev_frozen {
1213 let amount = after_frozen.saturating_sub(prev_frozen);
1214 Self::deposit_event(Event::Locked { who: who.clone(), amount });
1215 }
1216 }
1217
1218 pub(crate) fn update_freezes(
1220 who: &T::AccountId,
1221 freezes: BoundedSlice<IdAmount<T::FreezeIdentifier, T::Balance>, T::MaxFreezes>,
1222 ) -> DispatchResult {
1223 let mut prev_frozen = Zero::zero();
1224 let mut after_frozen = Zero::zero();
1225 let (_, maybe_dust) = Self::mutate_account(who, false, |b| {
1226 prev_frozen = b.frozen;
1227 b.frozen = Zero::zero();
1228 for l in Locks::<T, I>::get(who).iter() {
1229 b.frozen = b.frozen.max(l.amount);
1230 }
1231 for l in freezes.iter() {
1232 b.frozen = b.frozen.max(l.amount);
1233 }
1234 after_frozen = b.frozen;
1235 })?;
1236
1237 if freezes.is_empty() {
1238 Freezes::<T, I>::remove(who);
1239 } else {
1240 Freezes::<T, I>::insert(who, freezes);
1241 }
1242
1243 if let Some(dust) = maybe_dust {
1244 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1245 }
1246
1247 if prev_frozen > after_frozen {
1248 let amount = prev_frozen.saturating_sub(after_frozen);
1249 Self::deposit_event(Event::Thawed { who: who.clone(), amount });
1250 } else if after_frozen > prev_frozen {
1251 let amount = after_frozen.saturating_sub(prev_frozen);
1252 Self::deposit_event(Event::Frozen { who: who.clone(), amount });
1253 }
1254 Ok(())
1255 }
1256
1257 pub(crate) fn do_transfer_reserved(
1264 slashed: &T::AccountId,
1265 beneficiary: &T::AccountId,
1266 value: T::Balance,
1267 precision: Precision,
1268 fortitude: Fortitude,
1269 status: Status,
1270 ) -> Result<T::Balance, DispatchError> {
1271 if value.is_zero() {
1272 return Ok(Zero::zero());
1273 }
1274
1275 let max = <Self as fungible::InspectHold<_>>::reducible_total_balance_on_hold(
1276 slashed, fortitude,
1277 );
1278 let actual = match precision {
1279 Precision::BestEffort => value.min(max),
1280 Precision::Exact => value,
1281 };
1282 ensure!(actual <= max, TokenError::FundsUnavailable);
1283 if slashed == beneficiary {
1284 return match status {
1285 Status::Free => Ok(actual.saturating_sub(Self::unreserve(slashed, actual))),
1286 Status::Reserved => Ok(actual),
1287 };
1288 }
1289
1290 let ((_, maybe_dust_1), maybe_dust_2) = Self::try_mutate_account(
1291 beneficiary,
1292 false,
1293 |to_account, is_new| -> Result<((), Option<T::Balance>), DispatchError> {
1294 ensure!(!is_new, Error::<T, I>::DeadAccount);
1295 Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult {
1296 match status {
1297 Status::Free => {
1298 to_account.free = to_account
1299 .free
1300 .checked_add(&actual)
1301 .ok_or(ArithmeticError::Overflow)?
1302 },
1303 Status::Reserved => {
1304 to_account.reserved = to_account
1305 .reserved
1306 .checked_add(&actual)
1307 .ok_or(ArithmeticError::Overflow)?
1308 },
1309 }
1310 from_account.reserved.saturating_reduce(actual);
1311 Ok(())
1312 })
1313 },
1314 )?;
1315
1316 if let Some(dust) = maybe_dust_1 {
1317 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1318 }
1319 if let Some(dust) = maybe_dust_2 {
1320 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1321 }
1322
1323 Self::deposit_event(Event::ReserveRepatriated {
1324 from: slashed.clone(),
1325 to: beneficiary.clone(),
1326 amount: actual,
1327 destination_status: status,
1328 });
1329 Ok(actual)
1330 }
1331
1332 pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &str) {
1334 assert!(num_accounts > 0, "num_accounts must be greater than zero");
1336
1337 assert!(
1338 balance >= <T as Config<I>>::ExistentialDeposit::get(),
1339 "the balance of any account should always be at least the existential deposit.",
1340 );
1341
1342 assert!(
1343 derivation.contains("{}"),
1344 "Invalid derivation, expected `{{}}` as part of the derivation"
1345 );
1346
1347 for index in 0..num_accounts {
1348 let derivation_string = derivation.replace("{}", &index.to_string());
1350
1351 let pair: SrPair = Pair::from_string(&derivation_string, None)
1353 .expect(&format!("Failed to parse derivation string: {derivation_string}"));
1354
1355 let who = T::AccountId::decode(&mut &pair.public().encode()[..])
1357 .expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
1358
1359 Self::mutate_account_handling_dust(&who, false, |account| {
1361 account.free = balance;
1362 })
1363 .expect(&format!("Failed to add account to keystore: {:?}", who));
1364 }
1365 }
1366 }
1367
1368 #[cfg(any(test, feature = "try-runtime"))]
1369 impl<T: Config<I>, I: 'static> Pallet<T, I> {
1370 pub(crate) fn do_try_state(
1371 _n: BlockNumberFor<T>,
1372 ) -> Result<(), sp_runtime::TryRuntimeError> {
1373 Self::hold_and_freeze_count()?;
1374 Self::account_frozen_greater_than_locks()?;
1375 Self::account_frozen_greater_than_freezes()?;
1376 Ok(())
1377 }
1378
1379 fn hold_and_freeze_count() -> Result<(), sp_runtime::TryRuntimeError> {
1380 Holds::<T, I>::iter_keys().try_for_each(|k| {
1381 if Holds::<T, I>::decode_len(k).unwrap_or(0) >
1382 T::RuntimeHoldReason::VARIANT_COUNT as usize
1383 {
1384 Err("Found `Hold` with too many elements")
1385 } else {
1386 Ok(())
1387 }
1388 })?;
1389
1390 Freezes::<T, I>::iter_keys().try_for_each(|k| {
1391 if Freezes::<T, I>::decode_len(k).unwrap_or(0) > T::MaxFreezes::get() as usize {
1392 Err("Found `Freeze` with too many elements")
1393 } else {
1394 Ok(())
1395 }
1396 })?;
1397
1398 Ok(())
1399 }
1400
1401 fn account_frozen_greater_than_locks() -> Result<(), sp_runtime::TryRuntimeError> {
1402 Locks::<T, I>::iter().try_for_each(|(who, locks)| {
1403 let max_locks = locks.iter().map(|l| l.amount).max().unwrap_or_default();
1404 let frozen = T::AccountStore::get(&who).frozen;
1405 if max_locks > frozen {
1406 log::warn!(
1407 target: crate::LOG_TARGET,
1408 "Maximum lock of {:?} ({:?}) is greater than the frozen balance {:?}",
1409 who,
1410 max_locks,
1411 frozen
1412 );
1413 Err("bad locks".into())
1414 } else {
1415 Ok(())
1416 }
1417 })
1418 }
1419
1420 fn account_frozen_greater_than_freezes() -> Result<(), sp_runtime::TryRuntimeError> {
1421 Freezes::<T, I>::iter().try_for_each(|(who, freezes)| {
1422 let max_locks = freezes.iter().map(|l| l.amount).max().unwrap_or_default();
1423 let frozen = T::AccountStore::get(&who).frozen;
1424 if max_locks > frozen {
1425 log::warn!(
1426 target: crate::LOG_TARGET,
1427 "Maximum freeze of {:?} ({:?}) is greater than the frozen balance {:?}",
1428 who,
1429 max_locks,
1430 frozen
1431 );
1432 Err("bad freezes".into())
1433 } else {
1434 Ok(())
1435 }
1436 })
1437 }
1438 }
1439}