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, NamedReservableCurrency, OnUnbalanced, ReservableCurrency,
174 StoredMap,
175 },
176 BoundedSlice, WeakBoundedVec,
177};
178use frame_system as system;
179pub use impl_currency::{NegativeImbalance, PositiveImbalance};
180use scale_info::TypeInfo;
181use sp_core::{sr25519::Pair as SrPair, Pair};
182use sp_runtime::{
183 traits::{
184 AtLeast32BitUnsigned, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Saturating,
185 StaticLookup, Zero,
186 },
187 ArithmeticError, DispatchError, FixedPointOperand, Perbill, TokenError,
188};
189
190pub use types::{
191 AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData,
192};
193pub use weights::WeightInfo;
194
195pub use pallet::*;
196
197const LOG_TARGET: &str = "runtime::balances";
198
199const DEFAULT_ADDRESS_URI: &str = "//Sender//{}";
201
202type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
203
204#[frame_support::pallet]
205pub mod pallet {
206 use super::*;
207 use codec::HasCompact;
208 use frame_support::{
209 pallet_prelude::*,
210 traits::{fungible::Credit, tokens::Precision, VariantCount, VariantCountOf},
211 };
212 use frame_system::pallet_prelude::*;
213
214 pub type CreditOf<T, I> = Credit<<T as frame_system::Config>::AccountId, Pallet<T, I>>;
215
216 pub mod config_preludes {
218 use super::*;
219 use frame_support::derive_impl;
220
221 pub struct TestDefaultConfig;
222
223 #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
224 impl frame_system::DefaultConfig for TestDefaultConfig {}
225
226 #[frame_support::register_default_impl(TestDefaultConfig)]
227 impl DefaultConfig for TestDefaultConfig {
228 #[inject_runtime_type]
229 type RuntimeEvent = ();
230 #[inject_runtime_type]
231 type RuntimeHoldReason = ();
232 #[inject_runtime_type]
233 type RuntimeFreezeReason = ();
234
235 type Balance = u64;
236 type ExistentialDeposit = ConstUint<1>;
237
238 type ReserveIdentifier = ();
239
240 type DustRemoval = ();
241
242 type MaxLocks = ConstU32<100>;
243 type MaxReserves = ConstU32<100>;
244
245 type WeightInfo = ();
246 type DoneSlashHandler = ();
247 }
248 }
249
250 #[pallet::config(with_default)]
251 pub trait Config<I: 'static = ()>: frame_system::Config {
252 #[pallet::no_default_bounds]
254 #[allow(deprecated)]
255 type RuntimeEvent: From<Event<Self, I>>
256 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
257
258 #[pallet::no_default_bounds]
260 type RuntimeHoldReason: Parameter + Member + MaxEncodedLen + Copy + VariantCount;
261
262 #[pallet::no_default_bounds]
267 type RuntimeFreezeReason: Parameter + Member + MaxEncodedLen + Copy + VariantCount;
268
269 type WeightInfo: WeightInfo;
271
272 type Balance: Parameter
274 + Member
275 + AtLeast32BitUnsigned
276 + Codec
277 + HasCompact<Type: DecodeWithMemTracking>
278 + Default
279 + Copy
280 + MaybeSerializeDeserialize
281 + Debug
282 + MaxEncodedLen
283 + TypeInfo
284 + FixedPointOperand;
285
286 #[pallet::no_default_bounds]
288 type DustRemoval: OnUnbalanced<CreditOf<Self, I>>;
289
290 #[pallet::constant]
299 #[pallet::no_default_bounds]
300 type ExistentialDeposit: Get<Self::Balance>;
301
302 #[pallet::no_default]
304 type AccountStore: StoredMap<Self::AccountId, AccountData<Self::Balance>>;
305
306 type ReserveIdentifier: Parameter + Member + MaxEncodedLen + Ord + Copy;
310
311 #[pallet::constant]
316 type MaxLocks: Get<u32>;
317
318 #[pallet::constant]
322 type MaxReserves: Get<u32>;
323
324 type DoneSlashHandler: fungible::hold::DoneSlash<
327 Self::RuntimeHoldReason,
328 Self::AccountId,
329 Self::Balance,
330 >;
331 }
332
333 const STORAGE_VERSION: frame_support::traits::StorageVersion =
335 frame_support::traits::StorageVersion::new(1);
336
337 #[pallet::pallet]
338 #[pallet::storage_version(STORAGE_VERSION)]
339 pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
340
341 #[pallet::event]
342 #[pallet::generate_deposit(pub(super) fn deposit_event)]
343 pub enum Event<T: Config<I>, I: 'static = ()> {
344 Endowed { account: T::AccountId, free_balance: T::Balance },
346 DustLost { account: T::AccountId, amount: T::Balance },
349 Transfer { from: T::AccountId, to: T::AccountId, amount: T::Balance },
351 BalanceSet { who: T::AccountId, free: T::Balance },
353 Reserved { who: T::AccountId, amount: T::Balance },
355 Unreserved { who: T::AccountId, amount: T::Balance },
357 ReserveRepatriated {
360 from: T::AccountId,
361 to: T::AccountId,
362 amount: T::Balance,
363 destination_status: Status,
364 },
365 Deposit { who: T::AccountId, amount: T::Balance },
367 Withdraw { who: T::AccountId, amount: T::Balance },
369 Slashed { who: T::AccountId, amount: T::Balance },
371 Minted { who: T::AccountId, amount: T::Balance },
373 MintedCredit { amount: T::Balance },
375 Burned { who: T::AccountId, amount: T::Balance },
377 BurnedDebt { amount: T::Balance },
379 Suspended { who: T::AccountId, amount: T::Balance },
381 Restored { who: T::AccountId, amount: T::Balance },
383 Upgraded { who: T::AccountId },
385 Issued { amount: T::Balance },
387 Rescinded { amount: T::Balance },
389 Locked { who: T::AccountId, amount: T::Balance },
391 Unlocked { who: T::AccountId, amount: T::Balance },
393 Frozen { who: T::AccountId, amount: T::Balance },
395 Thawed { who: T::AccountId, amount: T::Balance },
397 TotalIssuanceForced { old: T::Balance, new: T::Balance },
399 Held { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
401 BurnedHeld { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
403 TransferOnHold {
405 reason: T::RuntimeHoldReason,
406 source: T::AccountId,
407 dest: T::AccountId,
408 amount: T::Balance,
409 },
410 TransferAndHold {
412 reason: T::RuntimeHoldReason,
413 source: T::AccountId,
414 dest: T::AccountId,
415 transferred: T::Balance,
416 },
417 Released { reason: T::RuntimeHoldReason, who: T::AccountId, amount: T::Balance },
419 Unexpected(UnexpectedKind),
421 }
422
423 #[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, Debug)]
427 pub enum UnexpectedKind {
428 BalanceUpdated,
430 FailedToMutateAccount,
433 }
434
435 #[pallet::error]
436 pub enum Error<T, I = ()> {
437 VestingBalance,
439 LiquidityRestrictions,
441 InsufficientBalance,
443 ExistentialDeposit,
445 Expendability,
447 ExistingVestingSchedule,
449 DeadAccount,
451 TooManyReserves,
453 TooManyHolds,
455 TooManyFreezes,
457 IssuanceDeactivated,
459 DeltaZero,
461 }
462
463 #[pallet::storage]
465 #[pallet::whitelist_storage]
466 pub type TotalIssuance<T: Config<I>, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery>;
467
468 #[pallet::storage]
474 #[pallet::whitelist_storage]
475 pub type InactiveIssuance<T: Config<I>, I: 'static = ()> =
476 StorageValue<_, T::Balance, ValueQuery>;
477
478 #[pallet::storage]
503 pub type Account<T: Config<I>, I: 'static = ()> =
504 StorageMap<_, Blake2_128Concat, T::AccountId, AccountData<T::Balance>, ValueQuery>;
505
506 #[pallet::storage]
511 pub type Locks<T: Config<I>, I: 'static = ()> = StorageMap<
512 _,
513 Blake2_128Concat,
514 T::AccountId,
515 WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks>,
516 ValueQuery,
517 >;
518
519 #[pallet::storage]
523 pub type Reserves<T: Config<I>, I: 'static = ()> = StorageMap<
524 _,
525 Blake2_128Concat,
526 T::AccountId,
527 BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves>,
528 ValueQuery,
529 >;
530
531 #[pallet::storage]
533 pub type Holds<T: Config<I>, I: 'static = ()> = StorageMap<
534 _,
535 Blake2_128Concat,
536 T::AccountId,
537 BoundedVec<
538 IdAmount<T::RuntimeHoldReason, T::Balance>,
539 VariantCountOf<T::RuntimeHoldReason>,
540 >,
541 ValueQuery,
542 >;
543
544 #[pallet::storage]
546 pub type Freezes<T: Config<I>, I: 'static = ()> = StorageMap<
547 _,
548 Blake2_128Concat,
549 T::AccountId,
550 BoundedVec<
551 IdAmount<T::RuntimeFreezeReason, T::Balance>,
552 VariantCountOf<T::RuntimeFreezeReason>,
553 >,
554 ValueQuery,
555 >;
556
557 #[pallet::genesis_config]
558 pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
559 pub balances: Vec<(T::AccountId, T::Balance)>,
560 pub dev_accounts: Option<(u32, T::Balance, Option<String>)>,
567 }
568
569 impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
570 fn default() -> Self {
571 Self { balances: Default::default(), dev_accounts: None }
572 }
573 }
574
575 #[pallet::genesis_build]
576 impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
577 fn build(&self) {
578 let total = self.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n);
579
580 <TotalIssuance<T, I>>::put(total);
581
582 for (_, balance) in &self.balances {
583 assert!(
584 *balance >= <T as Config<I>>::ExistentialDeposit::get(),
585 "the balance of any account should always be at least the existential deposit.",
586 )
587 }
588
589 let endowed_accounts = self
591 .balances
592 .iter()
593 .map(|(x, _)| x)
594 .cloned()
595 .collect::<alloc::collections::btree_set::BTreeSet<_>>();
596
597 assert!(
598 endowed_accounts.len() == self.balances.len(),
599 "duplicate balances in genesis."
600 );
601
602 if let Some((num_accounts, balance, ref derivation)) = self.dev_accounts {
604 Pallet::<T, I>::derive_dev_account(
606 num_accounts,
607 balance,
608 derivation.as_deref().unwrap_or(DEFAULT_ADDRESS_URI),
609 );
610 }
611 for &(ref who, free) in self.balances.iter() {
612 frame_system::Pallet::<T>::inc_providers(who);
613 assert!(T::AccountStore::insert(who, AccountData { free, ..Default::default() })
614 .is_ok());
615 }
616 }
617 }
618
619 #[pallet::hooks]
620 impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
621 fn integrity_test() {
622 #[cfg(not(feature = "insecure_zero_ed"))]
623 assert!(
624 !<T as Config<I>>::ExistentialDeposit::get().is_zero(),
625 "The existential deposit must be greater than zero!"
626 );
627 }
628
629 #[cfg(feature = "try-runtime")]
630 fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
631 Self::do_try_state(n)
632 }
633 }
634
635 #[pallet::call(weight(<T as Config<I>>::WeightInfo))]
636 impl<T: Config<I>, I: 'static> Pallet<T, I> {
637 #[pallet::call_index(0)]
645 pub fn transfer_allow_death(
646 origin: OriginFor<T>,
647 dest: AccountIdLookupOf<T>,
648 #[pallet::compact] value: T::Balance,
649 ) -> DispatchResult {
650 let source = ensure_signed(origin)?;
651 let dest = T::Lookup::lookup(dest)?;
652 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
653 Ok(())
654 }
655
656 #[pallet::call_index(2)]
659 pub fn force_transfer(
660 origin: OriginFor<T>,
661 source: AccountIdLookupOf<T>,
662 dest: AccountIdLookupOf<T>,
663 #[pallet::compact] value: T::Balance,
664 ) -> DispatchResult {
665 ensure_root(origin)?;
666 let source = T::Lookup::lookup(source)?;
667 let dest = T::Lookup::lookup(dest)?;
668 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Expendable)?;
669 Ok(())
670 }
671
672 #[pallet::call_index(3)]
679 pub fn transfer_keep_alive(
680 origin: OriginFor<T>,
681 dest: AccountIdLookupOf<T>,
682 #[pallet::compact] value: T::Balance,
683 ) -> DispatchResult {
684 let source = ensure_signed(origin)?;
685 let dest = T::Lookup::lookup(dest)?;
686 <Self as fungible::Mutate<_>>::transfer(&source, &dest, value, Preserve)?;
687 Ok(())
688 }
689
690 #[pallet::call_index(4)]
706 pub fn transfer_all(
707 origin: OriginFor<T>,
708 dest: AccountIdLookupOf<T>,
709 keep_alive: bool,
710 ) -> DispatchResult {
711 let transactor = ensure_signed(origin)?;
712 let keep_alive = if keep_alive { Preserve } else { Expendable };
713 let reducible_balance = <Self as fungible::Inspect<_>>::reducible_balance(
714 &transactor,
715 keep_alive,
716 Fortitude::Polite,
717 );
718 let dest = T::Lookup::lookup(dest)?;
719 <Self as fungible::Mutate<_>>::transfer(
720 &transactor,
721 &dest,
722 reducible_balance,
723 keep_alive,
724 )?;
725 Ok(())
726 }
727
728 #[pallet::call_index(5)]
735 pub fn force_unreserve(
736 origin: OriginFor<T>,
737 who: AccountIdLookupOf<T>,
738 amount: T::Balance,
739 ) -> DispatchResult {
740 ensure_root(origin)?;
741 let who = T::Lookup::lookup(who)?;
742 let _leftover = <Self as ReservableCurrency<_>>::unreserve(&who, amount);
743 Ok(())
744 }
745
746 #[pallet::call_index(11)]
753 #[pallet::weight(
754 <T as Config<I>>::WeightInfo::force_unreserve()
756 .saturating_add(T::DbWeight::get().reads_writes(1, 1))
757 )]
758 pub fn force_unreserve_named(
759 origin: OriginFor<T>,
760 id: T::ReserveIdentifier,
761 who: AccountIdLookupOf<T>,
762 amount: T::Balance,
763 ) -> DispatchResult {
764 ensure_root(origin)?;
765 let who = T::Lookup::lookup(who)?;
766 let _leftover =
767 <Self as NamedReservableCurrency<_>>::unreserve_named(&id, &who, amount);
768 Ok(())
769 }
770
771 #[pallet::call_index(6)]
780 #[pallet::weight(T::WeightInfo::upgrade_accounts(who.len() as u32))]
781 pub fn upgrade_accounts(
782 origin: OriginFor<T>,
783 who: Vec<T::AccountId>,
784 ) -> DispatchResultWithPostInfo {
785 ensure_signed(origin)?;
786 if who.is_empty() {
787 return Ok(Pays::Yes.into());
788 }
789 let mut upgrade_count = 0;
790 for i in &who {
791 let upgraded = Self::ensure_upgraded(i);
792 if upgraded {
793 upgrade_count.saturating_inc();
794 }
795 }
796 let proportion_upgraded = Perbill::from_rational(upgrade_count, who.len() as u32);
797 if proportion_upgraded >= Perbill::from_percent(90) {
798 Ok(Pays::No.into())
799 } else {
800 Ok(Pays::Yes.into())
801 }
802 }
803
804 #[pallet::call_index(8)]
808 #[pallet::weight(
809 T::WeightInfo::force_set_balance_creating() .max(T::WeightInfo::force_set_balance_killing()) )]
812 pub fn force_set_balance(
813 origin: OriginFor<T>,
814 who: AccountIdLookupOf<T>,
815 #[pallet::compact] new_free: T::Balance,
816 ) -> DispatchResult {
817 ensure_root(origin)?;
818 let who = T::Lookup::lookup(who)?;
819 let existential_deposit = Self::ed();
820
821 let wipeout = new_free < existential_deposit;
822 let new_free = if wipeout { Zero::zero() } else { new_free };
823
824 let old_free = Self::mutate_account_handling_dust(&who, false, |account| {
826 let old_free = account.free;
827 account.free = new_free;
828 old_free
829 })?;
830
831 if new_free > old_free {
834 mem::drop(PositiveImbalance::<T, I>::new(new_free - old_free));
835 } else if new_free < old_free {
836 mem::drop(NegativeImbalance::<T, I>::new(old_free - new_free));
837 }
838
839 Self::deposit_event(Event::BalanceSet { who, free: new_free });
840 Ok(())
841 }
842
843 #[doc = docify::embed!("./src/tests/dispatchable_tests.rs", force_adjust_total_issuance_example)]
849 #[pallet::call_index(9)]
850 #[pallet::weight(T::WeightInfo::force_adjust_total_issuance())]
851 pub fn force_adjust_total_issuance(
852 origin: OriginFor<T>,
853 direction: AdjustmentDirection,
854 #[pallet::compact] delta: T::Balance,
855 ) -> DispatchResult {
856 ensure_root(origin)?;
857
858 ensure!(delta > Zero::zero(), Error::<T, I>::DeltaZero);
859
860 let old = TotalIssuance::<T, I>::get();
861 let new = match direction {
862 AdjustmentDirection::Increase => old.saturating_add(delta),
863 AdjustmentDirection::Decrease => old.saturating_sub(delta),
864 };
865
866 ensure!(InactiveIssuance::<T, I>::get() <= new, Error::<T, I>::IssuanceDeactivated);
867 TotalIssuance::<T, I>::set(new);
868
869 Self::deposit_event(Event::<T, I>::TotalIssuanceForced { old, new });
870
871 Ok(())
872 }
873
874 #[pallet::call_index(10)]
882 #[pallet::weight(if *keep_alive {T::WeightInfo::burn_keep_alive()} else {T::WeightInfo::burn_allow_death()})]
883 pub fn burn(
884 origin: OriginFor<T>,
885 #[pallet::compact] value: T::Balance,
886 keep_alive: bool,
887 ) -> DispatchResult {
888 let source = ensure_signed(origin)?;
889 let preservation = if keep_alive { Preserve } else { Expendable };
890 <Self as fungible::Mutate<_>>::burn_from(
891 &source,
892 value,
893 preservation,
894 Precision::Exact,
895 Polite,
896 )?;
897 Ok(())
898 }
899 }
900
901 impl<T: Config<I>, I: 'static> Pallet<T, I> {
902 pub fn total_issuance() -> T::Balance {
904 TotalIssuance::<T, I>::get()
905 }
906
907 pub fn inactive_issuance() -> T::Balance {
909 InactiveIssuance::<T, I>::get()
910 }
911
912 pub fn locks(who: &T::AccountId) -> WeakBoundedVec<BalanceLock<T::Balance>, T::MaxLocks> {
914 Locks::<T, I>::get(who)
915 }
916
917 pub fn reserves(
919 who: &T::AccountId,
920 ) -> BoundedVec<ReserveData<T::ReserveIdentifier, T::Balance>, T::MaxReserves> {
921 Reserves::<T, I>::get(who)
922 }
923
924 pub(crate) fn max_reserved_touchable(
930 who: &T::AccountId,
931 id: Option<&T::ReserveIdentifier>,
932 ) -> T::Balance {
933 let held = Holds::<T, I>::get(who)
934 .iter()
935 .fold(T::Balance::zero(), |acc, hold| acc.saturating_add(hold.amount));
936 let not_held = Self::account(who).reserved.saturating_sub(held);
937 let reserves = Reserves::<T, I>::get(who);
938 match id {
939 None => reserves
942 .iter()
943 .fold(not_held, |acc, reserve| acc.saturating_sub(reserve.amount)),
944 Some(id) => reserves
949 .binary_search_by_key(id, |reserve| reserve.id)
950 .map_or(T::Balance::zero(), |index| reserves[index].amount)
951 .min(not_held),
952 }
953 }
954
955 fn ed() -> T::Balance {
956 T::ExistentialDeposit::get()
957 }
958 pub fn ensure_upgraded(who: &T::AccountId) -> bool {
962 let mut a = T::AccountStore::get(who);
963 if a.flags.is_new_logic() {
964 return false;
965 }
966 a.flags.set_new_logic();
967 if !a.reserved.is_zero() && a.frozen.is_zero() {
968 if system::Pallet::<T>::providers(who) == 0 {
969 log::warn!(
973 target: LOG_TARGET,
974 "account with a non-zero reserve balance has no provider refs, account_id: '{:?}'.",
975 who
976 );
977 a.free = a.free.max(Self::ed());
978 system::Pallet::<T>::inc_providers(who);
979 }
980 let _ = system::Pallet::<T>::inc_consumers_without_limit(who).defensive();
981 }
982 let _ = T::AccountStore::try_mutate_exists(who, |account| -> DispatchResult {
984 *account = Some(a);
985 Ok(())
986 });
987 Self::deposit_event(Event::Upgraded { who: who.clone() });
988 return true;
989 }
990
991 pub fn free_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
993 Self::account(who.borrow()).free
994 }
995
996 pub fn usable_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
999 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Expendable, Polite)
1000 }
1001
1002 pub fn usable_balance_for_fees(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
1007 <Self as fungible::Inspect<_>>::reducible_balance(who.borrow(), Protect, Polite)
1008 }
1009
1010 pub fn reserved_balance(who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
1012 Self::account(who.borrow()).reserved
1013 }
1014
1015 pub(crate) fn account(who: &T::AccountId) -> AccountData<T::Balance> {
1017 T::AccountStore::get(who)
1018 }
1019
1020 pub(crate) fn mutate_account_handling_dust<R>(
1032 who: &T::AccountId,
1033 force_consumer_bump: bool,
1034 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
1035 ) -> Result<R, DispatchError> {
1036 let (r, maybe_dust) = Self::mutate_account(who, force_consumer_bump, f)?;
1037 if let Some(dust) = maybe_dust {
1038 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1039 }
1040 Ok(r)
1041 }
1042
1043 pub(crate) fn try_mutate_account_handling_dust<R, E: From<DispatchError>>(
1055 who: &T::AccountId,
1056 force_consumer_bump: bool,
1057 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1058 ) -> Result<R, E> {
1059 let (r, maybe_dust) = Self::try_mutate_account(who, force_consumer_bump, f)?;
1060 if let Some(dust) = maybe_dust {
1061 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1062 }
1063 Ok(r)
1064 }
1065
1066 pub(crate) fn mutate_account<R>(
1083 who: &T::AccountId,
1084 force_consumer_bump: bool,
1085 f: impl FnOnce(&mut AccountData<T::Balance>) -> R,
1086 ) -> Result<(R, Option<T::Balance>), DispatchError> {
1087 Self::try_mutate_account(who, force_consumer_bump, |a, _| -> Result<R, DispatchError> {
1088 Ok(f(a))
1089 })
1090 }
1091
1092 #[cfg(not(feature = "insecure_zero_ed"))]
1095 fn have_providers_or_no_zero_ed(_: &T::AccountId) -> bool {
1096 true
1097 }
1098
1099 #[cfg(feature = "insecure_zero_ed")]
1102 fn have_providers_or_no_zero_ed(who: &T::AccountId) -> bool {
1103 frame_system::Pallet::<T>::providers(who) > 0
1104 }
1105
1106 pub(crate) fn try_mutate_account<R, E: From<DispatchError>>(
1120 who: &T::AccountId,
1121 force_consumer_bump: bool,
1122 f: impl FnOnce(&mut AccountData<T::Balance>, bool) -> Result<R, E>,
1123 ) -> Result<(R, Option<T::Balance>), E> {
1124 Self::ensure_upgraded(who);
1125 let result = T::AccountStore::try_mutate_exists(who, |maybe_account| {
1126 let is_new = maybe_account.is_none();
1127 let mut account = maybe_account.take().unwrap_or_default();
1128 let did_provide =
1129 account.free >= Self::ed() && Self::have_providers_or_no_zero_ed(who);
1130 let did_consume =
1131 !is_new && (!account.reserved.is_zero() || !account.frozen.is_zero());
1132
1133 let result = f(&mut account, is_new)?;
1134
1135 let does_provide = account.free >= Self::ed();
1136 let does_consume = !account.reserved.is_zero() || !account.frozen.is_zero();
1137
1138 if !did_provide && does_provide {
1139 frame_system::Pallet::<T>::inc_providers(who);
1140 }
1141 if did_consume && !does_consume {
1142 frame_system::Pallet::<T>::dec_consumers(who);
1143 }
1144 if !did_consume && does_consume {
1145 if force_consumer_bump {
1146 frame_system::Pallet::<T>::inc_consumers_without_limit(who)?;
1148 } else {
1149 frame_system::Pallet::<T>::inc_consumers(who)?;
1150 }
1151 }
1152 if does_consume && frame_system::Pallet::<T>::consumers(who) == 0 {
1153 log::error!(target: LOG_TARGET, "Defensively bumping a consumer ref.");
1157 frame_system::Pallet::<T>::inc_consumers(who)?;
1158 }
1159 if did_provide && !does_provide {
1160 frame_system::Pallet::<T>::dec_providers(who).inspect_err(|_| {
1162 if did_consume && !does_consume {
1164 let _ = frame_system::Pallet::<T>::inc_consumers(who).defensive();
1165 }
1166 if !did_consume && does_consume {
1167 let _ = frame_system::Pallet::<T>::dec_consumers(who);
1168 }
1169 })?;
1170 }
1171
1172 let maybe_endowed = if is_new { Some(account.free) } else { None };
1173
1174 let ed = Self::ed();
1186 let maybe_dust = if account.free < ed && !does_consume {
1187 if account.free.is_zero() {
1188 None
1189 } else {
1190 Some(account.free)
1191 }
1192 } else {
1193 *maybe_account = Some(account);
1194 None
1195 };
1196 Ok((maybe_endowed, maybe_dust, result))
1197 });
1198 result.map(|(maybe_endowed, maybe_dust, result)| {
1199 if let Some(endowed) = maybe_endowed {
1200 Self::deposit_event(Event::Endowed {
1201 account: who.clone(),
1202 free_balance: endowed,
1203 });
1204 }
1205 if let Some(amount) = maybe_dust {
1206 Pallet::<T, I>::deposit_event(Event::DustLost { account: who.clone(), amount });
1207 }
1208 (result, maybe_dust)
1209 })
1210 }
1211
1212 pub(crate) fn update_locks(who: &T::AccountId, locks: &[BalanceLock<T::Balance>]) {
1214 let bounded_locks = WeakBoundedVec::<_, T::MaxLocks>::force_from(
1215 locks.to_vec(),
1216 Some("Balances Update Locks"),
1217 );
1218
1219 if locks.len() as u32 > T::MaxLocks::get() {
1220 log::warn!(
1221 target: LOG_TARGET,
1222 "Warning: A user has more currency locks than expected. \
1223 A runtime configuration adjustment may be needed."
1224 );
1225 }
1226 let freezes = Freezes::<T, I>::get(who);
1227 let mut prev_frozen = Zero::zero();
1228 let mut after_frozen = Zero::zero();
1229 let res = Self::mutate_account(who, true, |b| {
1232 prev_frozen = b.frozen;
1233 b.frozen = Zero::zero();
1234 for l in locks.iter() {
1235 b.frozen = b.frozen.max(l.amount);
1236 }
1237 for l in freezes.iter() {
1238 b.frozen = b.frozen.max(l.amount);
1239 }
1240 after_frozen = b.frozen;
1241 });
1242 let maybe_dust = match res {
1243 Ok((_, maybe_dust)) => maybe_dust,
1244 Err(_) => {
1245 Self::deposit_event(Event::Unexpected(UnexpectedKind::FailedToMutateAccount));
1246 defensive!("errored in mutate_account");
1247 None
1248 },
1249 };
1250
1251 match locks.is_empty() {
1252 true => Locks::<T, I>::remove(who),
1253 false => Locks::<T, I>::insert(who, bounded_locks),
1254 }
1255
1256 if let Some(dust) = maybe_dust {
1257 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1258 }
1259
1260 if prev_frozen > after_frozen {
1261 let amount = prev_frozen.saturating_sub(after_frozen);
1262 Self::deposit_event(Event::Unlocked { who: who.clone(), amount });
1263 } else if after_frozen > prev_frozen {
1264 let amount = after_frozen.saturating_sub(prev_frozen);
1265 Self::deposit_event(Event::Locked { who: who.clone(), amount });
1266 }
1267 }
1268
1269 pub(crate) fn update_freezes(
1271 who: &T::AccountId,
1272 freezes: BoundedSlice<
1273 IdAmount<T::RuntimeFreezeReason, T::Balance>,
1274 VariantCountOf<T::RuntimeFreezeReason>,
1275 >,
1276 ) -> DispatchResult {
1277 let mut prev_frozen = Zero::zero();
1278 let mut after_frozen = Zero::zero();
1279 let (_, maybe_dust) = Self::mutate_account(who, false, |b| {
1280 prev_frozen = b.frozen;
1281 b.frozen = Zero::zero();
1282 for l in Locks::<T, I>::get(who).iter() {
1283 b.frozen = b.frozen.max(l.amount);
1284 }
1285 for l in freezes.iter() {
1286 b.frozen = b.frozen.max(l.amount);
1287 }
1288 after_frozen = b.frozen;
1289 })?;
1290
1291 if freezes.is_empty() {
1292 Freezes::<T, I>::remove(who);
1293 } else {
1294 Freezes::<T, I>::insert(who, freezes);
1295 }
1296
1297 if let Some(dust) = maybe_dust {
1298 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1299 }
1300
1301 if prev_frozen > after_frozen {
1302 let amount = prev_frozen.saturating_sub(after_frozen);
1303 Self::deposit_event(Event::Thawed { who: who.clone(), amount });
1304 } else if after_frozen > prev_frozen {
1305 let amount = after_frozen.saturating_sub(prev_frozen);
1306 Self::deposit_event(Event::Frozen { who: who.clone(), amount });
1307 }
1308 Ok(())
1309 }
1310
1311 pub(crate) fn do_transfer_reserved(
1320 slashed: &T::AccountId,
1321 beneficiary: &T::AccountId,
1322 value: T::Balance,
1323 precision: Precision,
1324 fortitude: Fortitude,
1325 status: Status,
1326 id: Option<&T::ReserveIdentifier>,
1327 ) -> Result<T::Balance, DispatchError> {
1328 if value.is_zero() {
1329 return Ok(Zero::zero());
1330 }
1331
1332 let max = <Self as fungible::InspectHold<_>>::reducible_total_balance_on_hold(
1333 slashed, fortitude,
1334 )
1335 .min(Self::max_reserved_touchable(slashed, id));
1336 let actual = match precision {
1337 Precision::BestEffort => value.min(max),
1338 Precision::Exact => value,
1339 };
1340 ensure!(actual <= max, TokenError::FundsUnavailable);
1341 if slashed == beneficiary {
1342 return match status {
1343 Status::Free => {
1344 Ok(actual.saturating_sub(Self::do_unreserve(slashed, actual, id)))
1345 },
1346 Status::Reserved => Ok(actual),
1347 };
1348 }
1349
1350 let ((_, maybe_dust_1), maybe_dust_2) = Self::try_mutate_account(
1351 beneficiary,
1352 false,
1353 |to_account, is_new| -> Result<((), Option<T::Balance>), DispatchError> {
1354 ensure!(!is_new, Error::<T, I>::DeadAccount);
1355 Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult {
1356 match status {
1357 Status::Free => {
1358 to_account.free = to_account
1359 .free
1360 .checked_add(&actual)
1361 .ok_or(ArithmeticError::Overflow)?
1362 },
1363 Status::Reserved => {
1364 to_account.reserved = to_account
1365 .reserved
1366 .checked_add(&actual)
1367 .ok_or(ArithmeticError::Overflow)?
1368 },
1369 }
1370 from_account.reserved.saturating_reduce(actual);
1371 Ok(())
1372 })
1373 },
1374 )?;
1375
1376 if let Some(dust) = maybe_dust_1 {
1377 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1378 }
1379 if let Some(dust) = maybe_dust_2 {
1380 <Self as fungible::Unbalanced<_>>::handle_raw_dust(dust);
1381 }
1382
1383 Self::deposit_event(Event::ReserveRepatriated {
1384 from: slashed.clone(),
1385 to: beneficiary.clone(),
1386 amount: actual,
1387 destination_status: status,
1388 });
1389 Ok(actual)
1390 }
1391
1392 pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &str) {
1394 assert!(num_accounts > 0, "num_accounts must be greater than zero");
1396
1397 assert!(
1398 balance >= <T as Config<I>>::ExistentialDeposit::get(),
1399 "the balance of any account should always be at least the existential deposit.",
1400 );
1401
1402 assert!(
1403 derivation.contains("{}"),
1404 "Invalid derivation, expected `{{}}` as part of the derivation"
1405 );
1406
1407 for index in 0..num_accounts {
1408 let derivation_string = derivation.replace("{}", &index.to_string());
1410
1411 let pair: SrPair = Pair::from_string(&derivation_string, None)
1413 .expect(&format!("Failed to parse derivation string: {derivation_string}"));
1414
1415 let who = T::AccountId::decode(&mut &pair.public().encode()[..])
1417 .expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
1418
1419 Self::mutate_account_handling_dust(&who, false, |account| {
1421 account.free = balance;
1422 })
1423 .expect(&format!("Failed to add account to keystore: {:?}", who));
1424 }
1425 }
1426 }
1427
1428 #[cfg(any(test, feature = "try-runtime"))]
1429 impl<T: Config<I>, I: 'static> Pallet<T, I> {
1430 pub(crate) fn do_try_state(
1431 _n: BlockNumberFor<T>,
1432 ) -> Result<(), sp_runtime::TryRuntimeError> {
1433 Self::hold_and_freeze_count()?;
1434 Self::account_frozen_greater_than_locks()?;
1435 Self::account_frozen_greater_than_freezes()?;
1436 Ok(())
1437 }
1438
1439 fn hold_and_freeze_count() -> Result<(), sp_runtime::TryRuntimeError> {
1440 Holds::<T, I>::iter_keys().try_for_each(|k| {
1441 if Holds::<T, I>::decode_len(k).unwrap_or(0) >
1442 T::RuntimeHoldReason::VARIANT_COUNT as usize
1443 {
1444 Err("Found `Hold` with too many elements")
1445 } else {
1446 Ok(())
1447 }
1448 })?;
1449
1450 Freezes::<T, I>::iter_keys().try_for_each(|k| {
1451 if Freezes::<T, I>::decode_len(k).unwrap_or(0) >
1452 T::RuntimeFreezeReason::VARIANT_COUNT as usize
1453 {
1454 Err("Found `Freeze` with too many elements")
1455 } else {
1456 Ok(())
1457 }
1458 })?;
1459
1460 Ok(())
1461 }
1462
1463 fn account_frozen_greater_than_locks() -> Result<(), sp_runtime::TryRuntimeError> {
1464 Locks::<T, I>::iter().try_for_each(|(who, locks)| {
1465 let max_locks = locks.iter().map(|l| l.amount).max().unwrap_or_default();
1466 let frozen = T::AccountStore::get(&who).frozen;
1467 if max_locks > frozen {
1468 log::warn!(
1469 target: crate::LOG_TARGET,
1470 "Maximum lock of {:?} ({:?}) is greater than the frozen balance {:?}",
1471 who,
1472 max_locks,
1473 frozen
1474 );
1475 Err("bad locks".into())
1476 } else {
1477 Ok(())
1478 }
1479 })
1480 }
1481
1482 fn account_frozen_greater_than_freezes() -> Result<(), sp_runtime::TryRuntimeError> {
1483 Freezes::<T, I>::iter().try_for_each(|(who, freezes)| {
1484 let max_locks = freezes.iter().map(|l| l.amount).max().unwrap_or_default();
1485 let frozen = T::AccountStore::get(&who).frozen;
1486 if max_locks > frozen {
1487 log::warn!(
1488 target: crate::LOG_TARGET,
1489 "Maximum freeze of {:?} ({:?}) is greater than the frozen balance {:?}",
1490 who,
1491 max_locks,
1492 frozen
1493 );
1494 Err("bad freezes".into())
1495 } else {
1496 Ok(())
1497 }
1498 })
1499 }
1500 }
1501}