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, RuntimeDebug, 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, RuntimeDebug)]
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]
475 #[pallet::whitelist_storage]
476 pub type InactiveIssuance<T: Config<I>, I: 'static = ()> =
477 StorageValue<_, T::Balance, ValueQuery>;
478
479 #[pallet::storage]
504 pub type Account<T: Config<I>, I: 'static = ()> =
505 StorageMap<_, Blake2_128Concat, T::AccountId, AccountData<T::Balance>, ValueQuery>;
506
507 #[pallet::storage]
512 pub type Locks<T: Config<I>, I: 'static = ()> = StorageMap<
513 _,
514 Blake2_128Concat,
515 T::AccountId,
516 WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks>,
517 ValueQuery,
518 >;
519
520 #[pallet::storage]
524 pub type Reserves<T: Config<I>, I: 'static = ()> = StorageMap<
525 _,
526 Blake2_128Concat,
527 T::AccountId,
528 BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves>,
529 ValueQuery,
530 >;
531
532 #[pallet::storage]
534 pub type Holds<T: Config<I>, I: 'static = ()> = StorageMap<
535 _,
536 Blake2_128Concat,
537 T::AccountId,
538 BoundedVec<
539 IdAmount<T::RuntimeHoldReason, T::Balance>,
540 VariantCountOf<T::RuntimeHoldReason>,
541 >,
542 ValueQuery,
543 >;
544
545 #[pallet::storage]
547 pub type Freezes<T: Config<I>, I: 'static = ()> = StorageMap<
548 _,
549 Blake2_128Concat,
550 T::AccountId,
551 BoundedVec<IdAmount<T::FreezeIdentifier, T::Balance>, T::MaxFreezes>,
552 ValueQuery,
553 >;
554
555 #[pallet::genesis_config]
556 pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
557 pub balances: Vec<(T::AccountId, T::Balance)>,
558 pub dev_accounts: Option<(u32, T::Balance, Option<String>)>,
565 }
566
567 impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
568 fn default() -> Self {
569 Self { balances: Default::default(), dev_accounts: None }
570 }
571 }
572
573 #[pallet::genesis_build]
574 impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
575 fn build(&self) {
576 let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n);
577
578 <TotalIssuance<T, I>>::put(total);
579
580 for (_, balance) in &self.balances {
581 assert!(
582 *balance >= <T as Config<I>>::ExistentialDeposit::get(),
583 "the balance of any account should always be at least the existential deposit.",
584 )
585 }
586
587 let endowed_accounts = self
589 .balances
590 .iter()
591 .map(|(x, _)| x)
592 .cloned()
593 .collect::<alloc::collections::btree_set::BTreeSet<_>>();
594
595 assert!(
596 endowed_accounts.len() == self.balances.len(),
597 "duplicate balances in genesis."
598 );
599
600 if let Some((num_accounts, balance, ref derivation)) = self.dev_accounts {
602 Pallet::<T, I>::derive_dev_account(
604 num_accounts,
605 balance,
606 derivation.as_deref().unwrap_or(DEFAULT_ADDRESS_URI),
607 );
608 }
609 for &(ref who, free) in self.balances.iter() {
610 frame_system::Pallet::<T>::inc_providers(who);
611 assert!(T::AccountStore::insert(who, AccountData { free, ..Default::default() })
612 .is_ok());
613 }
614 }
615 }
616
617 #[pallet::hooks]
618 impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
619 fn integrity_test() {
620 #[cfg(not(feature = "insecure_zero_ed"))]
621 assert!(
622 !<T as Config<I>>::ExistentialDeposit::get().is_zero(),
623 "The existential deposit must be greater than zero!"
624 );
625
626 assert!(
627 T::MaxFreezes::get() >= <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
628 "MaxFreezes should be greater than or equal to the number of freeze reasons: {} < {}",
629 T::MaxFreezes::get(), <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
630 );
631 }
632
633 #[cfg(feature = "try-runtime")]
634 fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
635 Self::do_try_state(n)
636 }
637 }
638
639 #[pallet::call(weight(<T as Config<I>>::WeightInfo))]
640 impl<T: Config<I>, I: 'static> Pallet<T, I> {
641 #[pallet::call_index(0)]
649 pub fn transfer_allow_death(
650 origin: OriginFor<T>,
651 dest: AccountIdLookupOf<T>,
652 #[pallet::compact] value: T::Balance,
653 ) -> DispatchResult {
654 let source = ensure_signed(origin)?;
655 let dest = T::Lookup::lookup(dest)?;
656 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
657 Ok(())
658 }
659
660 #[pallet::call_index(2)]
663 pub fn force_transfer(
664 origin: OriginFor<T>,
665 source: AccountIdLookupOf<T>,
666 dest: AccountIdLookupOf<T>,
667 #[pallet::compact] value: T::Balance,
668 ) -> DispatchResult {
669 ensure_root(origin)?;
670 let source = T::Lookup::lookup(source)?;
671 let dest = T::Lookup::lookup(dest)?;
672 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
673 Ok(())
674 }
675
676 #[pallet::call_index(3)]
683 pub fn transfer_keep_alive(
684 origin: OriginFor<T>,
685 dest: AccountIdLookupOf<T>,
686 #[pallet::compact] value: T::Balance,
687 ) -> DispatchResult {
688 let source = ensure_signed(origin)?;
689 let dest = T::Lookup::lookup(dest)?;
690 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Preserve)?;
691 Ok(())
692 }
693
694 #[pallet::call_index(4)]
710 pub fn transfer_all(
711 origin: OriginFor<T>,
712 dest: AccountIdLookupOf<T>,
713 keep_alive: bool,
714 ) -> DispatchResult {
715 let transactor = ensure_signed(origin)?;
716 let keep_alive = if keep_alive { Preserve } else { Expendable };
717 let reducible_balance = <Self as fungible::Inspect<_>>::reducible_balance(
718 &transactor,
719 keep_alive,
720 Fortitude::Polite,
721 );
722 let dest = T::Lookup::lookup(dest)?;
723 <Self as fungible::Mutate<_>>::transfer(
724 &transactor,
725 &dest,
726 reducible_balance,
727 keep_alive,
728 )?;
729 Ok(())
730 }
731
732 #[pallet::call_index(5)]
736 pub fn force_unreserve(
737 origin: OriginFor<T>,
738 who: AccountIdLookupOf<T>,
739 amount: T::Balance,
740 ) -> DispatchResult {
741 ensure_root(origin)?;
742 let who = T::Lookup::lookup(who)?;
743 let _leftover = <Self as ReservableCurrency<_>>::unreserve(&who, amount);
744 Ok(())
745 }
746
747 #[pallet::call_index(6)]
756 #[pallet::weight(T::WeightInfo::upgrade_accounts(who.len() as u32))]
757 pub fn upgrade_accounts(
758 origin: OriginFor<T>,
759 who: Vec<T::AccountId>,
760 ) -> DispatchResultWithPostInfo {
761 ensure_signed(origin)?;
762 if who.is_empty() {
763 return Ok(Pays::Yes.into())
764 }
765 let mut upgrade_count = 0;
766 for i in &who {
767 let upgraded = Self::ensure_upgraded(i);
768 if upgraded {
769 upgrade_count.saturating_inc();
770 }
771 }
772 let proportion_upgraded = Perbill::from_rational(upgrade_count, who.len() as u32);
773 if proportion_upgraded >= Perbill::from_percent(90) {
774 Ok(Pays::No.into())
775 } else {
776 Ok(Pays::Yes.into())
777 }
778 }
779
780 #[pallet::call_index(8)]
784 #[pallet::weight(
785 T::WeightInfo::force_set_balance_creating() .max(T::WeightInfo::force_set_balance_killing()) )]
788 pub fn force_set_balance(
789 origin: OriginFor<T>,
790 who: AccountIdLookupOf<T>,
791 #[pallet::compact] new_free: T::Balance,
792 ) -> DispatchResult {
793 ensure_root(origin)?;
794 let who = T::Lookup::lookup(who)?;
795 let existential_deposit = Self::ed();
796
797 let wipeout = new_free < existential_deposit;
798 let new_free = if wipeout { Zero::zero() } else { new_free };
799
800 let old_free = Self::mutate_account_handling_dust(&who, false, |account| {
802 let old_free = account.free;
803 account.free = new_free;
804 old_free
805 })?;
806
807 if new_free > old_free {
810 mem::drop(PositiveImbalance::<T, I>::new(new_free - old_free));
811 } else if new_free < old_free {
812 mem::drop(NegativeImbalance::<T, I>::new(old_free - new_free));
813 }
814
815 Self::deposit_event(Event::BalanceSet { who, free: new_free });
816 Ok(())
817 }
818
819 #[doc = docify::embed!("./src/tests/dispatchable_tests.rs", force_adjust_total_issuance_example)]
825 #[pallet::call_index(9)]
826 #[pallet::weight(T::WeightInfo::force_adjust_total_issuance())]
827 pub fn force_adjust_total_issuance(
828 origin: OriginFor<T>,
829 direction: AdjustmentDirection,
830 #[pallet::compact] delta: T::Balance,
831 ) -> DispatchResult {
832 ensure_root(origin)?;
833
834 ensure!(delta > Zero::zero(), Error::<T, I>::DeltaZero);
835
836 let old = TotalIssuance::<T, I>::get();
837 let new = match direction {
838 AdjustmentDirection::Increase => old.saturating_add(delta),
839 AdjustmentDirection::Decrease => old.saturating_sub(delta),
840 };
841
842 ensure!(InactiveIssuance::<T, I>::get() <= new, Error::<T, I>::IssuanceDeactivated);
843 TotalIssuance::<T, I>::set(new);
844
845 Self::deposit_event(Event::<T, I>::TotalIssuanceForced { old, new });
846
847 Ok(())
848 }
849
850 #[pallet::call_index(10)]
858 #[pallet::weight(if *keep_alive {T::WeightInfo::burn_allow_death() } else {T::WeightInfo::burn_keep_alive()})]
859 pub fn burn(
860 origin: OriginFor<T>,
861 #[pallet::compact] value: T::Balance,
862 keep_alive: bool,
863 ) -> DispatchResult {
864 let source = ensure_signed(origin)?;
865 let preservation = if keep_alive { Preserve } else { Expendable };
866 <Self as fungible::Mutate<_>>::burn_from(
867 &source,
868 value,
869 preservation,
870 Precision::Exact,
871 Polite,
872 )?;
873 Ok(())
874 }
875 }
876
877 impl<T: Config<I>, I: 'static> Pallet<T, I> {
878 pub fn total_issuance() -> T::Balance {
880 TotalIssuance::<T, I>::get()
881 }
882
883 pub fn inactive_issuance() -> T::Balance {
885 InactiveIssuance::<T, I>::get()
886 }
887
888 pub fn locks(who: &T::AccountId) -> WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks> {
890 Locks::<T, I>::get(who)
891 }
892
893 pub fn reserves(
895 who: &T::AccountId,
896 ) -> BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves> {
897 Reserves::<T, I>::get(who)
898 }
899
900 fn ed() -> T::Balance {
901 T::ExistentialDeposit::get()
902 }
903 pub fn ensure_upgraded(who: &T::AccountId) -> bool {
907 let mut a = T::AccountStore::get(who);
908 if a.flags.is_new_logic() {
909 return false
910 }
911 a.flags.set_new_logic();
912 if !a.reserved.is_zero() && a.frozen.is_zero() {
913 if system::Pallet::<T>::providers(who) == 0 {
914 log::warn!(
918 target: LOG_TARGET,
919 "account with a non-zero reserve balance has no provider refs, account_id: '{:?}'.",
920 who
921 );
922 a.free = a.free.max(Self::ed());
923 system::Pallet::<T>::inc_providers(who);
924 }
925 let _ = system::Pallet::<T>::inc_consumers_without_limit(who).defensive();
926 }
927 let _ = T::AccountStore::try_mutate_exists(who, |account| -> DispatchResult {
929 *account = Some(a);
930 Ok(())
931 });
932 Self::deposit_event(Event::Upgraded { who: who.clone() });
933 return true
934 }
935
936 pub fn free_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
938 Self::account(who.borrow()).free
939 }
940
941 pub fn usable_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
944 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Expendable, Polite)
945 }
946
947 pub fn usable_balance_for_fees(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
952 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Protect, Polite)
953 }
954
955 pub fn reserved_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
957 Self::account(who.borrow()).reserved
958 }
959
960 pub(crate) fn account(who: &T::AccountId) -> AccountData<T::Balance> {
962 T::AccountStore::get(who)
963 }
964
965 pub(crate) fn mutate_account_handling_dust<R>(
977 who: &T::AccountId,
978 force_consumer_bump: bool,
979 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
980 ) -> Result<R, DispatchError> {
981 let (r, maybe_dust) = Self::mutate_account(who, force_consumer_bump, f)?;
982 if let Some(dust) = maybe_dust {
983 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
984 }
985 Ok(r)
986 }
987
988 pub(crate) fn try_mutate_account_handling_dust<R, E: From<DispatchError>>(
1000 who: &T::AccountId,
1001 force_consumer_bump: bool,
1002 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1003 ) -> Result<R, E> {
1004 let (r, maybe_dust) = Self::try_mutate_account(who, force_consumer_bump, f)?;
1005 if let Some(dust) = maybe_dust {
1006 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1007 }
1008 Ok(r)
1009 }
1010
1011 pub(crate) fn mutate_account<R>(
1028 who: &T::AccountId,
1029 force_consumer_bump: bool,
1030 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
1031 ) -> Result<(R, Option<T::Balance>), DispatchError> {
1032 Self::try_mutate_account(who, force_consumer_bump, |a, _| -> Result<R, DispatchError> {
1033 Ok(f(a))
1034 })
1035 }
1036
1037 #[cfg(not(feature = "insecure_zero_ed"))]
1040 fn have_providers_or_no_zero_ed(_: &T::AccountId) -> bool {
1041 true
1042 }
1043
1044 #[cfg(feature = "insecure_zero_ed")]
1047 fn have_providers_or_no_zero_ed(who: &T::AccountId) -> bool {
1048 frame_system::Pallet::<T>::providers(who) > 0
1049 }
1050
1051 pub(crate) fn try_mutate_account<R, E: From<DispatchError>>(
1065 who: &T::AccountId,
1066 force_consumer_bump: bool,
1067 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1068 ) -> Result<(R, Option<T::Balance>), E> {
1069 Self::ensure_upgraded(who);
1070 let result = T::AccountStore::try_mutate_exists(who, |maybe_account| {
1071 let is_new = maybe_account.is_none();
1072 let mut account = maybe_account.take().unwrap_or_default();
1073 let did_provide =
1074 account.free >= Self::ed() && Self::have_providers_or_no_zero_ed(who);
1075 let did_consume =
1076 !is_new && (!account.reserved.is_zero() || !account.frozen.is_zero());
1077
1078 let result = f(&mut account, is_new)?;
1079
1080 let does_provide = account.free >= Self::ed();
1081 let does_consume = !account.reserved.is_zero() || !account.frozen.is_zero();
1082
1083 if !did_provide && does_provide {
1084 frame_system::Pallet::<T>::inc_providers(who);
1085 }
1086 if did_consume && !does_consume {
1087 frame_system::Pallet::<T>::dec_consumers(who);
1088 }
1089 if !did_consume && does_consume {
1090 if force_consumer_bump {
1091 frame_system::Pallet::<T>::inc_consumers_without_limit(who)?;
1093 } else {
1094 frame_system::Pallet::<T>::inc_consumers(who)?;
1095 }
1096 }
1097 if does_consume && frame_system::Pallet::<T>::consumers(who) == 0 {
1098 log::error!(target: LOG_TARGET, "Defensively bumping a consumer ref.");
1102 frame_system::Pallet::<T>::inc_consumers(who)?;
1103 }
1104 if did_provide && !does_provide {
1105 frame_system::Pallet::<T>::dec_providers(who).inspect_err(|_| {
1107 if did_consume && !does_consume {
1109 let _ = frame_system::Pallet::<T>::inc_consumers(who).defensive();
1110 }
1111 if !did_consume && does_consume {
1112 let _ = frame_system::Pallet::<T>::dec_consumers(who);
1113 }
1114 })?;
1115 }
1116
1117 let maybe_endowed = if is_new { Some(account.free) } else { None };
1118
1119 let ed = Self::ed();
1131 let maybe_dust = if account.free < ed && account.reserved.is_zero() {
1132 if account.free.is_zero() {
1133 None
1134 } else {
1135 Some(account.free)
1136 }
1137 } else {
1138 assert!(
1139 account.free.is_zero() || account.free >= ed || !account.reserved.is_zero()
1140 );
1141 *maybe_account = Some(account);
1142 None
1143 };
1144 Ok((maybe_endowed, maybe_dust, result))
1145 });
1146 result.map(|(maybe_endowed, maybe_dust, result)| {
1147 if let Some(endowed) = maybe_endowed {
1148 Self::deposit_event(Event::Endowed {
1149 account: who.clone(),
1150 free_balance: endowed,
1151 });
1152 }
1153 if let Some(amount) = maybe_dust {
1154 Pallet::<T, I>::deposit_event(Event::DustLost { account: who.clone(), amount });
1155 }
1156 (result, maybe_dust)
1157 })
1158 }
1159
1160 pub(crate) fn update_locks(who: &T::AccountId, locks: &[BalanceLock<T::Balance>]) {
1162 let bounded_locks = WeakBoundedVec::<_, T::MaxLocks>::force_from(
1163 locks.to_vec(),
1164 Some("Balances Update Locks"),
1165 );
1166
1167 if locks.len() as u32 > T::MaxLocks::get() {
1168 log::warn!(
1169 target: LOG_TARGET,
1170 "Warning: A user has more currency locks than expected. \
1171 A runtime configuration adjustment may be needed."
1172 );
1173 }
1174 let freezes = Freezes::<T, I>::get(who);
1175 let mut prev_frozen = Zero::zero();
1176 let mut after_frozen = Zero::zero();
1177 let res = Self::mutate_account(who, true, |b| {
1180 prev_frozen = b.frozen;
1181 b.frozen = Zero::zero();
1182 for l in locks.iter() {
1183 b.frozen = b.frozen.max(l.amount);
1184 }
1185 for l in freezes.iter() {
1186 b.frozen = b.frozen.max(l.amount);
1187 }
1188 after_frozen = b.frozen;
1189 });
1190 match res {
1191 Ok((_, None)) => {
1192 },
1194 Ok((_, Some(_dust))) => {
1195 Self::deposit_event(Event::Unexpected(UnexpectedKind::BalanceUpdated));
1196 defensive!("caused unexpected dusting/balance update.");
1197 },
1198 _ => {
1199 Self::deposit_event(Event::Unexpected(UnexpectedKind::FailedToMutateAccount));
1200 defensive!("errored in mutate_account");
1201 },
1202 }
1203
1204 match locks.is_empty() {
1205 true => Locks::<T, I>::remove(who),
1206 false => Locks::<T, I>::insert(who, bounded_locks),
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 if maybe_dust.is_some() {
1237 Self::deposit_event(Event::Unexpected(UnexpectedKind::BalanceUpdated));
1238 defensive!("caused unexpected dusting/balance update.");
1239 }
1240 if freezes.is_empty() {
1241 Freezes::<T, I>::remove(who);
1242 } else {
1243 Freezes::<T, I>::insert(who, freezes);
1244 }
1245 if prev_frozen > after_frozen {
1246 let amount = prev_frozen.saturating_sub(after_frozen);
1247 Self::deposit_event(Event::Thawed { who: who.clone(), amount });
1248 } else if after_frozen > prev_frozen {
1249 let amount = after_frozen.saturating_sub(prev_frozen);
1250 Self::deposit_event(Event::Frozen { who: who.clone(), amount });
1251 }
1252 Ok(())
1253 }
1254
1255 pub(crate) fn do_transfer_reserved(
1262 slashed: &T::AccountId,
1263 beneficiary: &T::AccountId,
1264 value: T::Balance,
1265 precision: Precision,
1266 fortitude: Fortitude,
1267 status: Status,
1268 ) -> Result<T::Balance, DispatchError> {
1269 if value.is_zero() {
1270 return Ok(Zero::zero())
1271 }
1272
1273 let max = <Self as fungible::InspectHold<_>>::reducible_total_balance_on_hold(
1274 slashed, fortitude,
1275 );
1276 let actual = match precision {
1277 Precision::BestEffort => value.min(max),
1278 Precision::Exact => value,
1279 };
1280 ensure!(actual <= max, TokenError::FundsUnavailable);
1281 if slashed == beneficiary {
1282 return match status {
1283 Status::Free => Ok(actual.saturating_sub(Self::unreserve(slashed, actual))),
1284 Status::Reserved => Ok(actual),
1285 }
1286 }
1287
1288 let ((_, maybe_dust_1), maybe_dust_2) = Self::try_mutate_account(
1289 beneficiary,
1290 false,
1291 |to_account, is_new| -> Result<((), Option<T::Balance>), DispatchError> {
1292 ensure!(!is_new, Error::<T, I>::DeadAccount);
1293 Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult {
1294 match status {
1295 Status::Free =>
1296 to_account.free = to_account
1297 .free
1298 .checked_add(&actual)
1299 .ok_or(ArithmeticError::Overflow)?,
1300 Status::Reserved =>
1301 to_account.reserved = to_account
1302 .reserved
1303 .checked_add(&actual)
1304 .ok_or(ArithmeticError::Overflow)?,
1305 }
1306 from_account.reserved.saturating_reduce(actual);
1307 Ok(())
1308 })
1309 },
1310 )?;
1311
1312 if let Some(dust) = maybe_dust_1 {
1313 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1314 }
1315 if let Some(dust) = maybe_dust_2 {
1316 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1317 }
1318
1319 Self::deposit_event(Event::ReserveRepatriated {
1320 from: slashed.clone(),
1321 to: beneficiary.clone(),
1322 amount: actual,
1323 destination_status: status,
1324 });
1325 Ok(actual)
1326 }
1327
1328 pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &str) {
1330 assert!(num_accounts > 0, "num_accounts must be greater than zero");
1332
1333 assert!(
1334 balance >= <T as Config<I>>::ExistentialDeposit::get(),
1335 "the balance of any account should always be at least the existential deposit.",
1336 );
1337
1338 assert!(
1339 derivation.contains("{}"),
1340 "Invalid derivation, expected `{{}}` as part of the derivation"
1341 );
1342
1343 for index in 0..num_accounts {
1344 let derivation_string = derivation.replace("{}", &index.to_string());
1346
1347 let pair: SrPair = Pair::from_string(&derivation_string, None)
1349 .expect(&format!("Failed to parse derivation string: {derivation_string}"));
1350
1351 let who = T::AccountId::decode(&mut &pair.public().encode()[..])
1353 .expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
1354
1355 Self::mutate_account_handling_dust(&who, false, |account| {
1357 account.free = balance;
1358 })
1359 .expect(&format!("Failed to add account to keystore: {:?}", who));
1360 }
1361 }
1362 }
1363
1364 #[cfg(any(test, feature = "try-runtime"))]
1365 impl<T: Config<I>, I: 'static> Pallet<T, I> {
1366 pub(crate) fn do_try_state(
1367 _n: BlockNumberFor<T>,
1368 ) -> Result<(), sp_runtime::TryRuntimeError> {
1369 Self::hold_and_freeze_count()?;
1370 Self::account_frozen_greater_than_locks()?;
1371 Self::account_frozen_greater_than_freezes()?;
1372 Ok(())
1373 }
1374
1375 fn hold_and_freeze_count() -> Result<(), sp_runtime::TryRuntimeError> {
1376 Holds::<T, I>::iter_keys().try_for_each(|k| {
1377 if Holds::<T, I>::decode_len(k).unwrap_or(0) >
1378 T::RuntimeHoldReason::VARIANT_COUNT as usize
1379 {
1380 Err("Found `Hold` with too many elements")
1381 } else {
1382 Ok(())
1383 }
1384 })?;
1385
1386 Freezes::<T, I>::iter_keys().try_for_each(|k| {
1387 if Freezes::<T, I>::decode_len(k).unwrap_or(0) > T::MaxFreezes::get() as usize {
1388 Err("Found `Freeze` with too many elements")
1389 } else {
1390 Ok(())
1391 }
1392 })?;
1393
1394 Ok(())
1395 }
1396
1397 fn account_frozen_greater_than_locks() -> Result<(), sp_runtime::TryRuntimeError> {
1398 Locks::<T, I>::iter().try_for_each(|(who, locks)| {
1399 let max_locks = locks.iter().map(|l| l.amount).max().unwrap_or_default();
1400 let frozen = T::AccountStore::get(&who).frozen;
1401 if max_locks > frozen {
1402 log::warn!(
1403 target: crate::LOG_TARGET,
1404 "Maximum lock of {:?} ({:?}) is greater than the frozen balance {:?}",
1405 who,
1406 max_locks,
1407 frozen
1408 );
1409 Err("bad locks".into())
1410 } else {
1411 Ok(())
1412 }
1413 })
1414 }
1415
1416 fn account_frozen_greater_than_freezes() -> Result<(), sp_runtime::TryRuntimeError> {
1417 Freezes::<T, I>::iter().try_for_each(|(who, freezes)| {
1418 let max_locks = freezes.iter().map(|l| l.amount).max().unwrap_or_default();
1419 let frozen = T::AccountStore::get(&who).frozen;
1420 if max_locks > frozen {
1421 log::warn!(
1422 target: crate::LOG_TARGET,
1423 "Maximum freeze of {:?} ({:?}) is greater than the frozen balance {:?}",
1424 who,
1425 max_locks,
1426 frozen
1427 );
1428 Err("bad freezes".into())
1429 } else {
1430 Ok(())
1431 }
1432 })
1433 }
1434 }
1435}