Remove the Copy bound on AssetId (#14158)

* Remove the `Copy` bound on `AssetId`

* Also relax the `Copy` bound in the assets pallet

* Fix warnings on the newest nightly Rust

* Remove some unnecessary `clone()`s

* Try to satisfy clippy

* Remove some more unnecessary `clone()`s

* Add more `.clone()`s for newly merged code

* Also add `clone()`s in the benchmarks

---------

Co-authored-by: parity-processbot <>
This commit is contained in:
Koute
2023-05-23 20:34:04 +09:00
committed by GitHub
parent 06865d4c08
commit 194c9edd4a
13 changed files with 223 additions and 187 deletions
@@ -38,7 +38,7 @@ mod benchmarks {
fn create() -> Result<(), BenchmarkError> {
let asset_id: T::AssetId = ASSET_ID.into();
#[extrinsic_call]
_(RawOrigin::Root, asset_id, default_conversion_rate());
_(RawOrigin::Root, asset_id.clone(), default_conversion_rate());
assert_eq!(
pallet_asset_rate::ConversionRateToNative::<T>::get(asset_id),
@@ -52,12 +52,12 @@ mod benchmarks {
let asset_id: T::AssetId = ASSET_ID.into();
assert_ok!(AssetRate::<T>::create(
RawOrigin::Root.into(),
asset_id,
asset_id.clone(),
default_conversion_rate()
));
#[extrinsic_call]
_(RawOrigin::Root, asset_id, FixedU128::from_u32(2));
_(RawOrigin::Root, asset_id.clone(), FixedU128::from_u32(2));
assert_eq!(
pallet_asset_rate::ConversionRateToNative::<T>::get(asset_id),
@@ -76,7 +76,7 @@ mod benchmarks {
));
#[extrinsic_call]
_(RawOrigin::Root, asset_id);
_(RawOrigin::Root, asset_id.clone());
assert!(pallet_asset_rate::ConversionRateToNative::<T>::get(asset_id).is_none());
Ok(())
+5 -5
View File
@@ -161,10 +161,10 @@ pub mod pallet {
T::CreateOrigin::ensure_origin(origin)?;
ensure!(
!ConversionRateToNative::<T>::contains_key(asset_id),
!ConversionRateToNative::<T>::contains_key(asset_id.clone()),
Error::<T>::AlreadyExists
);
ConversionRateToNative::<T>::set(asset_id, Some(rate));
ConversionRateToNative::<T>::set(asset_id.clone(), Some(rate));
Self::deposit_event(Event::AssetRateCreated { asset_id, rate });
Ok(())
@@ -184,7 +184,7 @@ pub mod pallet {
T::UpdateOrigin::ensure_origin(origin)?;
let mut old = FixedU128::zero();
ConversionRateToNative::<T>::mutate(asset_id, |maybe_rate| {
ConversionRateToNative::<T>::mutate(asset_id.clone(), |maybe_rate| {
if let Some(r) = maybe_rate {
old = *r;
*r = rate;
@@ -209,10 +209,10 @@ pub mod pallet {
T::RemoveOrigin::ensure_origin(origin)?;
ensure!(
ConversionRateToNative::<T>::contains_key(asset_id),
ConversionRateToNative::<T>::contains_key(asset_id.clone()),
Error::<T>::UnknownAssetId
);
ConversionRateToNative::<T>::remove(asset_id);
ConversionRateToNative::<T>::remove(asset_id.clone());
Self::deposit_event(Event::AssetRateRemoved { asset_id });
Ok(())
+1 -1
View File
@@ -144,7 +144,7 @@ benchmarks_instance_pallet! {
let caller = T::CreateOrigin::ensure_origin(origin, &asset_id.into()).unwrap();
let caller_lookup = T::Lookup::unlookup(caller.clone());
T::Currency::make_free_balance_be(&caller, DepositBalanceOf::<T, I>::max_value());
}: _(SystemOrigin::Signed(caller.clone()), asset_id, caller_lookup, 1u32.into())
}: _(SystemOrigin::Signed(caller.clone()), asset_id.clone(), caller_lookup, 1u32.into())
verify {
assert_last_event::<T, I>(Event::Created { asset_id: asset_id.into(), creator: caller.clone(), owner: caller }.into());
}
+3 -3
View File
@@ -62,7 +62,7 @@ impl<T: Config<I>, I: 'static> ExtraMutator<T, I> {
id: T::AssetId,
who: impl sp_std::borrow::Borrow<T::AccountId>,
) -> Option<ExtraMutator<T, I>> {
if let Some(a) = Account::<T, I>::get(id, who.borrow()) {
if let Some(a) = Account::<T, I>::get(&id, who.borrow()) {
Some(ExtraMutator::<T, I> {
id,
who: who.borrow().clone(),
@@ -77,7 +77,7 @@ impl<T: Config<I>, I: 'static> ExtraMutator<T, I> {
/// Commit any changes to storage.
pub fn commit(&mut self) -> Result<(), ()> {
if let Some(extra) = self.pending.take() {
Account::<T, I>::try_mutate(self.id, self.who.borrow(), |maybe_account| {
Account::<T, I>::try_mutate(&self.id, &self.who, |maybe_account| {
maybe_account.as_mut().ok_or(()).map(|account| account.extra = extra)
})
} else {
@@ -88,7 +88,7 @@ impl<T: Config<I>, I: 'static> ExtraMutator<T, I> {
/// Revert any changes, even those already committed by `self` and drop self.
pub fn revert(mut self) -> Result<(), ()> {
self.pending = None;
Account::<T, I>::try_mutate(self.id, self.who.borrow(), |maybe_account| {
Account::<T, I>::try_mutate(&self.id, &self.who, |maybe_account| {
maybe_account
.as_mut()
.ok_or(())
+63 -57
View File
@@ -128,7 +128,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
amount: T::Balance,
increase_supply: bool,
) -> DepositConsequence {
let details = match Asset::<T, I>::get(id) {
let details = match Asset::<T, I>::get(&id) {
Some(details) => details,
None => return DepositConsequence::UnknownAsset,
};
@@ -165,7 +165,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
keep_alive: bool,
) -> WithdrawConsequence<T::Balance> {
use WithdrawConsequence::*;
let details = match Asset::<T, I>::get(id) {
let details = match Asset::<T, I>::get(&id) {
Some(details) => details,
None => return UnknownAsset,
};
@@ -178,7 +178,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
if amount.is_zero() {
return Success
}
let account = match Account::<T, I>::get(id, who) {
let account = match Account::<T, I>::get(&id, who) {
Some(a) => a,
None => return BalanceLow,
};
@@ -186,7 +186,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
return Frozen
}
if let Some(rest) = account.balance.checked_sub(&amount) {
if let Some(frozen) = T::Freezer::frozen_balance(id, who) {
if let Some(frozen) = T::Freezer::frozen_balance(id.clone(), who) {
match frozen.checked_add(&details.min_balance) {
Some(required) if rest < required => return Frozen,
None => return Overflow,
@@ -219,10 +219,10 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
who: &T::AccountId,
keep_alive: bool,
) -> Result<T::Balance, DispatchError> {
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
let account = Account::<T, I>::get(id, who).ok_or(Error::<T, I>::NoAccount)?;
let account = Account::<T, I>::get(&id, who).ok_or(Error::<T, I>::NoAccount)?;
ensure!(!account.status.is_frozen(), Error::<T, I>::Frozen);
let amount = if let Some(frozen) = T::Freezer::frozen_balance(id, who) {
@@ -265,7 +265,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
amount: T::Balance,
f: DebitFlags,
) -> Result<T::Balance, DispatchError> {
let actual = Self::reducible_balance(id, target, f.keep_alive)?.min(amount);
let actual = Self::reducible_balance(id.clone(), target, f.keep_alive)?.min(amount);
ensure!(f.best_effort || actual >= amount, Error::<T, I>::BalanceLow);
let conseq = Self::can_decrease(id, target, actual, f.keep_alive);
@@ -320,7 +320,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
depositor: T::AccountId,
check_depositor: bool,
) -> DispatchResult {
ensure!(!Account::<T, I>::contains_key(id, &who), Error::<T, I>::AlreadyExists);
ensure!(!Account::<T, I>::contains_key(&id, &who), Error::<T, I>::AlreadyExists);
let deposit = T::AssetAccountDeposit::get();
let mut details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
@@ -332,7 +332,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
T::Currency::reserve(&depositor, deposit)?;
Asset::<T, I>::insert(&id, details);
Account::<T, I>::insert(
id,
&id,
&who,
AssetAccountOf::<T, I> {
balance: Zero::zero(),
@@ -350,7 +350,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub(super) fn do_refund(id: T::AssetId, who: T::AccountId, allow_burn: bool) -> DispatchResult {
use AssetStatus::*;
use ExistenceReason::*;
let mut account = Account::<T, I>::get(id, &who).ok_or(Error::<T, I>::NoDeposit)?;
let mut account = Account::<T, I>::get(&id, &who).ok_or(Error::<T, I>::NoDeposit)?;
ensure!(matches!(account.reason, Consumer | DepositHeld(..)), Error::<T, I>::NoDeposit);
let mut details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(matches!(details.status, Live | Frozen), Error::<T, I>::IncorrectStatus);
@@ -361,7 +361,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
}
if let Remove = Self::dead_account(&who, &mut details, &account.reason, false) {
Account::<T, I>::remove(id, &who);
Account::<T, I>::remove(&id, &who);
} else {
debug_assert!(false, "refund did not result in dead account?!");
// deposit may have been refunded, need to update `Account`
@@ -380,7 +380,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
who: &T::AccountId,
caller: &T::AccountId,
) -> DispatchResult {
let mut account = Account::<T, I>::get(id, &who).ok_or(Error::<T, I>::NoDeposit)?;
let mut account = Account::<T, I>::get(&id, &who).ok_or(Error::<T, I>::NoDeposit)?;
let (depositor, deposit) =
account.reason.take_deposit_from().ok_or(Error::<T, I>::NoDeposit)?;
let mut details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
@@ -392,11 +392,11 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
T::Currency::unreserve(&depositor, deposit);
if let Remove = Self::dead_account(&who, &mut details, &account.reason, false) {
Account::<T, I>::remove(id, &who);
Account::<T, I>::remove(&id, &who);
} else {
debug_assert!(false, "refund did not result in dead account?!");
// deposit may have been refunded, need to update `Account`
Account::<T, I>::insert(id, &who, account);
Account::<T, I>::insert(&id, &who, account);
return Ok(())
}
Asset::<T, I>::insert(&id, details);
@@ -416,7 +416,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
amount: T::Balance,
maybe_check_issuer: Option<T::AccountId>,
) -> DispatchResult {
Self::increase_balance(id, beneficiary, amount, |details| -> DispatchResult {
Self::increase_balance(id.clone(), beneficiary, amount, |details| -> DispatchResult {
if let Some(check_issuer) = maybe_check_issuer {
ensure!(check_issuer == details.issuer, Error::<T, I>::NoPermission);
}
@@ -450,19 +450,20 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
return Ok(())
}
Self::can_increase(id, beneficiary, amount, true).into_result()?;
Asset::<T, I>::try_mutate(id, |maybe_details| -> DispatchResult {
Self::can_increase(id.clone(), beneficiary, amount, true).into_result()?;
Asset::<T, I>::try_mutate(&id, |maybe_details| -> DispatchResult {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
check(details)?;
Account::<T, I>::try_mutate(id, beneficiary, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, beneficiary, |maybe_account| -> DispatchResult {
match maybe_account {
Some(ref mut account) => {
account.balance.saturating_accrue(amount);
},
maybe_account @ None => {
// Note this should never fail as it's already checked by `can_increase`.
// Note this should never fail as it's already checked by
// `can_increase`.
ensure!(amount >= details.min_balance, TokenError::BelowMinimum);
*maybe_account = Some(AssetAccountOf::<T, I> {
balance: amount,
@@ -493,13 +494,13 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
maybe_check_admin: Option<T::AccountId>,
f: DebitFlags,
) -> Result<T::Balance, DispatchError> {
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(
d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
Error::<T, I>::AssetNotLive
);
let actual = Self::decrease_balance(id, target, amount, f, |actual, details| {
let actual = Self::decrease_balance(id.clone(), target, amount, f, |actual, details| {
// Check admin rights.
if let Some(check_admin) = maybe_check_admin {
ensure!(check_admin == details.admin, Error::<T, I>::NoPermission);
@@ -536,17 +537,17 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
return Ok(amount)
}
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
let actual = Self::prep_debit(id, target, amount, f)?;
let actual = Self::prep_debit(id.clone(), target, amount, f)?;
let mut target_died: Option<DeadConsequence> = None;
Asset::<T, I>::try_mutate(id, |maybe_details| -> DispatchResult {
Asset::<T, I>::try_mutate(&id, |maybe_details| -> DispatchResult {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
check(actual, details)?;
Account::<T, I>::try_mutate(id, target, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, target, |maybe_account| -> DispatchResult {
let mut account = maybe_account.take().ok_or(Error::<T, I>::NoAccount)?;
debug_assert!(account.balance >= actual, "checked in prep; qed");
@@ -590,7 +591,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
f: TransferFlags,
) -> Result<T::Balance, DispatchError> {
let (balance, died) =
Self::transfer_and_die(id, source, dest, amount, maybe_need_admin, f)?;
Self::transfer_and_die(id.clone(), source, dest, amount, maybe_need_admin, f)?;
if let Some(Remove) = died {
T::Freezer::died(id, source);
}
@@ -611,18 +612,18 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
if amount.is_zero() {
return Ok((amount, None))
}
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
// Figure out the debit and credit, together with side-effects.
let debit = Self::prep_debit(id, source, amount, f.into())?;
let (credit, maybe_burn) = Self::prep_credit(id, dest, amount, debit, f.burn_dust)?;
let debit = Self::prep_debit(id.clone(), source, amount, f.into())?;
let (credit, maybe_burn) = Self::prep_credit(id.clone(), dest, amount, debit, f.burn_dust)?;
let mut source_account =
Account::<T, I>::get(id, &source).ok_or(Error::<T, I>::NoAccount)?;
Account::<T, I>::get(&id, &source).ok_or(Error::<T, I>::NoAccount)?;
let mut source_died: Option<DeadConsequence> = None;
Asset::<T, I>::try_mutate(id, |maybe_details| -> DispatchResult {
Asset::<T, I>::try_mutate(&id, |maybe_details| -> DispatchResult {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
// Check admin rights.
@@ -647,7 +648,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
debug_assert!(source_account.balance >= debit, "checked in prep; qed");
source_account.balance = source_account.balance.saturating_sub(debit);
Account::<T, I>::try_mutate(id, &dest, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, &dest, |maybe_account| -> DispatchResult {
match maybe_account {
Some(ref mut account) => {
// Calculate new balance; this will not saturate since it's already checked
@@ -676,11 +677,11 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
source_died =
Some(Self::dead_account(source, details, &source_account.reason, false));
if let Some(Remove) = source_died {
Account::<T, I>::remove(id, &source);
Account::<T, I>::remove(&id, &source);
return Ok(())
}
}
Account::<T, I>::insert(id, &source, &source_account);
Account::<T, I>::insert(&id, &source, &source_account);
Ok(())
})?;
@@ -707,11 +708,11 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
is_sufficient: bool,
min_balance: T::Balance,
) -> DispatchResult {
ensure!(!Asset::<T, I>::contains_key(id), Error::<T, I>::InUse);
ensure!(!Asset::<T, I>::contains_key(&id), Error::<T, I>::InUse);
ensure!(!min_balance.is_zero(), Error::<T, I>::MinBalanceZero);
Asset::<T, I>::insert(
id,
&id,
AssetDetails {
owner: owner.clone(),
issuer: owner.clone(),
@@ -738,8 +739,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
id: T::AssetId,
maybe_check_owner: Option<T::AccountId>,
) -> DispatchResult {
Asset::<T, I>::try_mutate_exists(id, |maybe_details| -> Result<(), DispatchError> {
let mut details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
Asset::<T, I>::try_mutate_exists(id.clone(), |maybe_details| -> Result<(), DispatchError> {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
if let Some(check_owner) = maybe_check_owner {
ensure!(details.owner == check_owner, Error::<T, I>::NoPermission);
}
@@ -761,12 +762,12 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
let mut dead_accounts: Vec<T::AccountId> = vec![];
let mut remaining_accounts = 0;
let _ =
Asset::<T, I>::try_mutate_exists(id, |maybe_details| -> Result<(), DispatchError> {
Asset::<T, I>::try_mutate_exists(&id, |maybe_details| -> Result<(), DispatchError> {
let mut details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
// Should only destroy accounts while the asset is in a destroying state
ensure!(details.status == AssetStatus::Destroying, Error::<T, I>::IncorrectStatus);
for (who, v) in Account::<T, I>::drain_prefix(id) {
for (who, v) in Account::<T, I>::drain_prefix(&id) {
let _ = Self::dead_account(&who, &mut details, &v.reason, true);
dead_accounts.push(who);
if dead_accounts.len() >= (max_items as usize) {
@@ -778,7 +779,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
})?;
for who in &dead_accounts {
T::Freezer::died(id, &who);
T::Freezer::died(id.clone(), &who);
}
Self::deposit_event(Event::AccountsDestroyed {
@@ -798,14 +799,15 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
max_items: u32,
) -> Result<u32, DispatchError> {
let mut removed_approvals = 0;
let _ =
Asset::<T, I>::try_mutate_exists(id, |maybe_details| -> Result<(), DispatchError> {
let mut details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
let _ = Asset::<T, I>::try_mutate_exists(
id.clone(),
|maybe_details| -> Result<(), DispatchError> {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
// Should only destroy accounts while the asset is in a destroying state.
ensure!(details.status == AssetStatus::Destroying, Error::<T, I>::IncorrectStatus);
for ((owner, _), approval) in Approvals::<T, I>::drain_prefix((id,)) {
for ((owner, _), approval) in Approvals::<T, I>::drain_prefix((id.clone(),)) {
T::Currency::unreserve(&owner, approval.deposit);
removed_approvals = removed_approvals.saturating_add(1);
details.approvals = details.approvals.saturating_sub(1);
@@ -819,7 +821,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
approvals_remaining: details.approvals as u32,
});
Ok(())
})?;
},
)?;
Ok(removed_approvals)
}
@@ -827,7 +830,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
///
/// On success, the `Event::Destroyed` event is emitted.
pub(super) fn do_finish_destroy(id: T::AssetId) -> DispatchResult {
Asset::<T, I>::try_mutate_exists(id, |maybe_details| -> Result<(), DispatchError> {
Asset::<T, I>::try_mutate_exists(id.clone(), |maybe_details| -> Result<(), DispatchError> {
let details = maybe_details.take().ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Destroying, Error::<T, I>::IncorrectStatus);
ensure!(details.accounts == 0, Error::<T, I>::InUse);
@@ -855,10 +858,10 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
delegate: &T::AccountId,
amount: T::Balance,
) -> DispatchResult {
let mut d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
Approvals::<T, I>::try_mutate(
(id, &owner, &delegate),
(id.clone(), &owner, &delegate),
|maybe_approved| -> DispatchResult {
let mut approved = match maybe_approved.take() {
// an approval already exists and is being updated
@@ -879,7 +882,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
Ok(())
},
)?;
Asset::<T, I>::insert(id, d);
Asset::<T, I>::insert(&id, d);
Self::deposit_event(Event::ApprovedTransfer {
asset_id: id,
source: owner.clone(),
@@ -906,22 +909,23 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
) -> DispatchResult {
let mut owner_died: Option<DeadConsequence> = None;
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
Approvals::<T, I>::try_mutate_exists(
(id, &owner, delegate),
(id.clone(), &owner, delegate),
|maybe_approved| -> DispatchResult {
let mut approved = maybe_approved.take().ok_or(Error::<T, I>::Unapproved)?;
let remaining =
approved.amount.checked_sub(&amount).ok_or(Error::<T, I>::Unapproved)?;
let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false };
owner_died = Self::transfer_and_die(id, owner, destination, amount, None, f)?.1;
owner_died =
Self::transfer_and_die(id.clone(), owner, destination, amount, None, f)?.1;
if remaining.is_zero() {
T::Currency::unreserve(owner, approved.deposit);
Asset::<T, I>::mutate(id, |maybe_details| {
Asset::<T, I>::mutate(id.clone(), |maybe_details| {
if let Some(details) = maybe_details {
details.approvals.saturating_dec();
}
@@ -954,11 +958,11 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
let bounded_symbol: BoundedVec<u8, T::StringLimit> =
symbol.clone().try_into().map_err(|_| Error::<T, I>::BadMetadata)?;
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(from == &d.owner, Error::<T, I>::NoPermission);
Metadata::<T, I>::try_mutate_exists(id, |metadata| {
Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
ensure!(metadata.as_ref().map_or(true, |m| !m.is_frozen), Error::<T, I>::NoPermission);
let old_deposit = metadata.take().map_or(Zero::zero(), |m| m.deposit);
@@ -999,7 +1003,9 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Returns all the non-zero balances for all assets of the given `account`.
pub fn account_balances(account: T::AccountId) -> Vec<(T::AssetId, T::Balance)> {
Asset::<T, I>::iter_keys()
.filter_map(|id| Self::maybe_balance(id, account.clone()).map(|balance| (id, balance)))
.filter_map(|id| {
Self::maybe_balance(id.clone(), account.clone()).map(|balance| (id, balance))
})
.collect::<Vec<_>>()
}
}
@@ -21,7 +21,7 @@ use super::*;
impl<T: Config<I>, I: 'static> StoredMap<(T::AssetId, T::AccountId), T::Extra> for Pallet<T, I> {
fn get(id_who: &(T::AssetId, T::AccountId)) -> T::Extra {
let &(id, ref who) = id_who;
let (id, who) = id_who;
Account::<T, I>::get(id, who).map(|a| a.extra).unwrap_or_default()
}
@@ -29,7 +29,7 @@ impl<T: Config<I>, I: 'static> StoredMap<(T::AssetId, T::AccountId), T::Extra> f
id_who: &(T::AssetId, T::AccountId),
f: impl FnOnce(&mut Option<T::Extra>) -> Result<R, E>,
) -> Result<R, E> {
let &(id, ref who) = id_who;
let (id, who) = id_who;
let mut maybe_extra = Account::<T, I>::get(id, who).map(|a| a.extra);
let r = f(&mut maybe_extra)?;
// They want to write some value or delete it.
+32 -32
View File
@@ -162,7 +162,7 @@ use sp_runtime::{
traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedSub, Saturating, StaticLookup, Zero},
ArithmeticError, TokenError,
};
use sp_std::{borrow::Borrow, prelude::*};
use sp_std::prelude::*;
use frame_support::{
dispatch::{DispatchError, DispatchResult},
@@ -250,7 +250,7 @@ pub mod pallet {
type RemoveItemsLimit: Get<u32>;
/// Identifier for the class of asset.
type AssetId: Member + Parameter + Copy + MaybeSerializeDeserialize + MaxEncodedLen;
type AssetId: Member + Parameter + Clone + MaybeSerializeDeserialize + MaxEncodedLen;
/// Wrapper around `Self::AssetId` to use in dispatchable call signatures. Allows the use
/// of compact encoding in instances of the pallet, which will prevent breaking changes
@@ -424,7 +424,7 @@ pub mod pallet {
for (id, account_id, amount) in &self.accounts {
let result = <Pallet<T, I>>::increase_balance(
*id,
id.clone(),
account_id,
*amount,
|details| -> DispatchResult {
@@ -605,14 +605,14 @@ pub mod pallet {
let owner = T::CreateOrigin::ensure_origin(origin, &id)?;
let admin = T::Lookup::lookup(admin)?;
ensure!(!Asset::<T, I>::contains_key(id), Error::<T, I>::InUse);
ensure!(!Asset::<T, I>::contains_key(&id), Error::<T, I>::InUse);
ensure!(!min_balance.is_zero(), Error::<T, I>::MinBalanceZero);
let deposit = T::AssetDeposit::get();
T::Currency::reserve(&owner, deposit)?;
Asset::<T, I>::insert(
id,
id.clone(),
AssetDetails {
owner: owner.clone(),
issuer: admin.clone(),
@@ -937,7 +937,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(
d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
Error::<T, I>::AssetNotLive
@@ -945,7 +945,7 @@ pub mod pallet {
ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
let who = T::Lookup::lookup(who)?;
Account::<T, I>::try_mutate(id, &who, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
AccountStatus::Frozen;
Ok(())
@@ -974,7 +974,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(
details.status == AssetStatus::Live || details.status == AssetStatus::Frozen,
Error::<T, I>::AssetNotLive
@@ -982,7 +982,7 @@ pub mod pallet {
ensure!(origin == details.admin, Error::<T, I>::NoPermission);
let who = T::Lookup::lookup(who)?;
Account::<T, I>::try_mutate(id, &who, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
AccountStatus::Liquid;
Ok(())
@@ -1006,7 +1006,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
Asset::<T, I>::try_mutate(id, |maybe_details| {
Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
@@ -1032,7 +1032,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
Asset::<T, I>::try_mutate(id, |maybe_details| {
Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(origin == d.admin, Error::<T, I>::NoPermission);
ensure!(d.status == AssetStatus::Frozen, Error::<T, I>::NotFrozen);
@@ -1064,7 +1064,7 @@ pub mod pallet {
let owner = T::Lookup::lookup(owner)?;
let id: T::AssetId = id.into();
Asset::<T, I>::try_mutate(id, |maybe_details| {
Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::LiveAsset);
ensure!(origin == details.owner, Error::<T, I>::NoPermission);
@@ -1072,7 +1072,7 @@ pub mod pallet {
return Ok(())
}
let metadata_deposit = Metadata::<T, I>::get(id).deposit;
let metadata_deposit = Metadata::<T, I>::get(&id).deposit;
let deposit = details.deposit + metadata_deposit;
// Move the deposit to the new owner.
@@ -1111,7 +1111,7 @@ pub mod pallet {
let freezer = T::Lookup::lookup(freezer)?;
let id: T::AssetId = id.into();
Asset::<T, I>::try_mutate(id, |maybe_details| {
Asset::<T, I>::try_mutate(id.clone(), |maybe_details| {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(origin == details.owner, Error::<T, I>::NoPermission);
@@ -1171,11 +1171,11 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(origin == d.owner, Error::<T, I>::NoPermission);
Metadata::<T, I>::try_mutate_exists(id, |metadata| {
Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
let deposit = metadata.take().ok_or(Error::<T, I>::Unknown)?.deposit;
T::Currency::unreserve(&d.owner, deposit);
Self::deposit_event(Event::MetadataCleared { asset_id: id });
@@ -1216,8 +1216,8 @@ pub mod pallet {
let bounded_symbol: BoundedVec<u8, T::StringLimit> =
symbol.clone().try_into().map_err(|_| Error::<T, I>::BadMetadata)?;
ensure!(Asset::<T, I>::contains_key(id), Error::<T, I>::Unknown);
Metadata::<T, I>::try_mutate_exists(id, |metadata| {
ensure!(Asset::<T, I>::contains_key(&id), Error::<T, I>::Unknown);
Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
let deposit = metadata.take().map_or(Zero::zero(), |m| m.deposit);
*metadata = Some(AssetMetadata {
deposit,
@@ -1257,8 +1257,8 @@ pub mod pallet {
T::ForceOrigin::ensure_origin(origin)?;
let id: T::AssetId = id.into();
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
Metadata::<T, I>::try_mutate_exists(id, |metadata| {
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
Metadata::<T, I>::try_mutate_exists(id.clone(), |metadata| {
let deposit = metadata.take().ok_or(Error::<T, I>::Unknown)?.deposit;
T::Currency::unreserve(&d.owner, deposit);
Self::deposit_event(Event::MetadataCleared { asset_id: id });
@@ -1303,7 +1303,7 @@ pub mod pallet {
T::ForceOrigin::ensure_origin(origin)?;
let id: T::AssetId = id.into();
Asset::<T, I>::try_mutate(id, |maybe_asset| {
Asset::<T, I>::try_mutate(id.clone(), |maybe_asset| {
let mut asset = maybe_asset.take().ok_or(Error::<T, I>::Unknown)?;
ensure!(asset.status != AssetStatus::Destroying, Error::<T, I>::AssetNotLive);
asset.owner = T::Lookup::lookup(owner)?;
@@ -1379,15 +1379,15 @@ pub mod pallet {
let owner = ensure_signed(origin)?;
let delegate = T::Lookup::lookup(delegate)?;
let id: T::AssetId = id.into();
let mut d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
let approval =
Approvals::<T, I>::take((id, &owner, &delegate)).ok_or(Error::<T, I>::Unknown)?;
let approval = Approvals::<T, I>::take((id.clone(), &owner, &delegate))
.ok_or(Error::<T, I>::Unknown)?;
T::Currency::unreserve(&owner, approval.deposit);
d.approvals.saturating_dec();
Asset::<T, I>::insert(id, d);
Asset::<T, I>::insert(id.clone(), d);
Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate });
Ok(())
@@ -1414,7 +1414,7 @@ pub mod pallet {
delegate: AccountIdLookupOf<T>,
) -> DispatchResult {
let id: T::AssetId = id.into();
let mut d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
T::ForceOrigin::try_origin(origin)
.map(|_| ())
@@ -1427,11 +1427,11 @@ pub mod pallet {
let owner = T::Lookup::lookup(owner)?;
let delegate = T::Lookup::lookup(delegate)?;
let approval =
Approvals::<T, I>::take((id, &owner, &delegate)).ok_or(Error::<T, I>::Unknown)?;
let approval = Approvals::<T, I>::take((id.clone(), &owner, &delegate))
.ok_or(Error::<T, I>::Unknown)?;
T::Currency::unreserve(&owner, approval.deposit);
d.approvals.saturating_dec();
Asset::<T, I>::insert(id, d);
Asset::<T, I>::insert(id.clone(), d);
Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate });
Ok(())
@@ -1529,7 +1529,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
let mut details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let mut details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(origin == details.owner, Error::<T, I>::NoPermission);
let old_min_balance = details.min_balance;
@@ -1619,7 +1619,7 @@ pub mod pallet {
let origin = ensure_signed(origin)?;
let id: T::AssetId = id.into();
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
let d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(
d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
Error::<T, I>::AssetNotLive
@@ -1627,7 +1627,7 @@ pub mod pallet {
ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
let who = T::Lookup::lookup(who)?;
Account::<T, I>::try_mutate(id, &who, |maybe_account| -> DispatchResult {
Account::<T, I>::try_mutate(&id, &who, |maybe_account| -> DispatchResult {
maybe_account.as_mut().ok_or(Error::<T, I>::NoAccount)?.status =
AccountStatus::Blocked;
Ok(())
@@ -93,7 +93,7 @@ benchmarks! {
let collection = T::BenchmarkHelper::collection(0);
let nft = T::BenchmarkHelper::nft(0);
let (caller, caller_lookup) = mint_nft::<T>(nft);
}: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset, caller_lookup, 1000u32.into())
}: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset.clone(), caller_lookup, 1000u32.into())
verify {
assert_last_event::<T>(
Event::NftFractionalized {
@@ -115,11 +115,11 @@ benchmarks! {
SystemOrigin::Signed(caller.clone()).into(),
collection,
nft,
asset,
asset.clone(),
caller_lookup.clone(),
1000u32.into(),
)?;
}: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset, caller_lookup)
}: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset.clone(), caller_lookup)
verify {
assert_last_event::<T>(
Event::NftUnified {
@@ -241,13 +241,19 @@ pub mod pallet {
let deposit = T::Deposit::get();
T::Currency::hold(&T::HoldReason::get(), &nft_owner, deposit)?;
Self::do_lock_nft(nft_collection_id, nft_id)?;
Self::do_create_asset(asset_id, pallet_account.clone())?;
Self::do_mint_asset(asset_id, &beneficiary, fractions)?;
Self::do_set_metadata(asset_id, &who, &pallet_account, &nft_collection_id, &nft_id)?;
Self::do_create_asset(asset_id.clone(), pallet_account.clone())?;
Self::do_mint_asset(asset_id.clone(), &beneficiary, fractions)?;
Self::do_set_metadata(
asset_id.clone(),
&who,
&pallet_account,
&nft_collection_id,
&nft_id,
)?;
NftToAsset::<T>::insert(
(nft_collection_id, nft_id),
Details { asset: asset_id, fractions, asset_creator: nft_owner, deposit },
Details { asset: asset_id.clone(), fractions, asset_creator: nft_owner, deposit },
);
Self::deposit_event(Event::NftFractionalized {
@@ -295,7 +301,7 @@ pub mod pallet {
let deposit = details.deposit;
let asset_creator = details.asset_creator;
Self::do_burn_asset(asset_id, &who, details.fractions)?;
Self::do_burn_asset(asset_id.clone(), &who, details.fractions)?;
Self::do_unlock_nft(nft_collection_id, nft_id, &beneficiary)?;
T::Currency::release(&T::HoldReason::get(), &asset_creator, deposit, BestEffort)?;
@@ -356,7 +362,7 @@ pub mod pallet {
account: &T::AccountId,
amount: AssetBalanceOf<T>,
) -> DispatchResult {
T::Assets::burn_from(asset_id, account, amount, Exact, Polite)?;
T::Assets::burn_from(asset_id.clone(), account, amount, Exact, Polite)?;
T::Assets::start_destroy(asset_id, None)
}
@@ -98,7 +98,7 @@ pub trait Inspect<AccountId>: super::Inspect<AccountId> {
who: &AccountId,
amount: Self::Balance,
) -> DispatchResult {
ensure!(Self::hold_available(asset, reason, who), TokenError::CannotCreateHold);
ensure!(Self::hold_available(asset.clone(), reason, who), TokenError::CannotCreateHold);
ensure!(
amount <= Self::reducible_balance(asset, who, Protect, Force),
TokenError::FundsUnavailable
@@ -173,7 +173,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
mut amount: Self::Balance,
precision: Precision,
) -> Result<Self::Balance, DispatchError> {
let old_balance = Self::balance_on_hold(asset, reason, who);
let old_balance = Self::balance_on_hold(asset.clone(), reason, who);
if let BestEffort = precision {
amount = amount.min(old_balance);
}
@@ -193,7 +193,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
amount: Self::Balance,
precision: Precision,
) -> Result<Self::Balance, DispatchError> {
let old_balance = Self::balance_on_hold(asset, reason, who);
let old_balance = Self::balance_on_hold(asset.clone(), reason, who);
let new_balance = if let BestEffort = precision {
old_balance.saturating_add(amount)
} else {
@@ -221,11 +221,13 @@ pub trait Balanced<AccountId>: super::Balanced<AccountId> + Unbalanced<AccountId
who: &AccountId,
amount: Self::Balance,
) -> (Credit<AccountId, Self>, Self::Balance) {
let decrease = Self::decrease_balance_on_hold(asset, reason, who, amount, BestEffort)
.unwrap_or(Default::default());
let decrease =
Self::decrease_balance_on_hold(asset.clone(), reason, who, amount, BestEffort)
.unwrap_or(Default::default());
let credit =
Imbalance::<Self::AssetId, Self::Balance, Self::OnDropCredit, Self::OnDropDebt>::new(
asset, decrease,
asset.clone(),
decrease,
);
Self::done_slash(asset, reason, who, decrease);
(credit, amount.saturating_sub(decrease))
@@ -255,10 +257,10 @@ pub trait Mutate<AccountId>:
// NOTE: This doesn't change the total balance of the account so there's no need to
// check liquidity.
Self::ensure_can_hold(asset, reason, who, amount)?;
Self::ensure_can_hold(asset.clone(), reason, who, amount)?;
// Should be infallible now, but we proceed softly anyway.
Self::decrease_balance(asset, who, amount, Exact, Protect, Force)?;
Self::increase_balance_on_hold(asset, reason, who, amount, BestEffort)?;
Self::decrease_balance(asset.clone(), who, amount, Exact, Protect, Force)?;
Self::increase_balance_on_hold(asset.clone(), reason, who, amount, BestEffort)?;
Self::done_hold(asset, reason, who, amount);
Ok(())
}
@@ -281,13 +283,16 @@ pub trait Mutate<AccountId>:
// We want to make sure we can deposit the amount in advance. If we can't then something is
// very wrong.
ensure!(Self::can_deposit(asset, who, amount, Extant) == Success, TokenError::CannotCreate);
ensure!(
Self::can_deposit(asset.clone(), who, amount, Extant) == Success,
TokenError::CannotCreate
);
// Get the amount we can actually take from the hold. This might be less than what we want
// if we're only doing a best-effort.
let amount = Self::decrease_balance_on_hold(asset, reason, who, amount, precision)?;
let amount = Self::decrease_balance_on_hold(asset.clone(), reason, who, amount, precision)?;
// Increase the main balance by what we took. We always do a best-effort here because we
// already checked that we can deposit before.
let actual = Self::increase_balance(asset, who, amount, BestEffort)?;
let actual = Self::increase_balance(asset.clone(), who, amount, BestEffort)?;
Self::done_release(asset, reason, who, actual);
Ok(actual)
}
@@ -310,14 +315,17 @@ pub trait Mutate<AccountId>:
force: Fortitude,
) -> Result<Self::Balance, DispatchError> {
// We must check total-balance requirements if `!force`.
let liquid = Self::reducible_total_balance_on_hold(asset, who, force);
let liquid = Self::reducible_total_balance_on_hold(asset.clone(), who, force);
if let BestEffort = precision {
amount = amount.min(liquid);
} else {
ensure!(amount <= liquid, TokenError::Frozen);
}
let amount = Self::decrease_balance_on_hold(asset, reason, who, amount, precision)?;
Self::set_total_issuance(asset, Self::total_issuance(asset).saturating_sub(amount));
let amount = Self::decrease_balance_on_hold(asset.clone(), reason, who, amount, precision)?;
Self::set_total_issuance(
asset.clone(),
Self::total_issuance(asset.clone()).saturating_sub(amount),
);
Self::done_burn_held(asset, reason, who, amount);
Ok(amount)
}
@@ -348,8 +356,8 @@ pub trait Mutate<AccountId>:
force: Fortitude,
) -> Result<Self::Balance, DispatchError> {
// We must check total-balance requirements if `!force`.
let have = Self::balance_on_hold(asset, reason, source);
let liquid = Self::reducible_total_balance_on_hold(asset, source, force);
let have = Self::balance_on_hold(asset.clone(), reason, source);
let liquid = Self::reducible_total_balance_on_hold(asset.clone(), source, force);
if let BestEffort = precision {
amount = amount.min(liquid).min(have);
} else {
@@ -360,19 +368,20 @@ pub trait Mutate<AccountId>:
// We want to make sure we can deposit the amount in advance. If we can't then something is
// very wrong.
ensure!(
Self::can_deposit(asset, dest, amount, Extant) == Success,
Self::can_deposit(asset.clone(), dest, amount, Extant) == Success,
TokenError::CannotCreate
);
ensure!(
mode == Free || Self::hold_available(asset, reason, dest),
mode == Free || Self::hold_available(asset.clone(), reason, dest),
TokenError::CannotCreateHold
);
let amount = Self::decrease_balance_on_hold(asset, reason, source, amount, precision)?;
let amount =
Self::decrease_balance_on_hold(asset.clone(), reason, source, amount, precision)?;
let actual = if mode == OnHold {
Self::increase_balance_on_hold(asset, reason, dest, amount, precision)?
Self::increase_balance_on_hold(asset.clone(), reason, dest, amount, precision)?
} else {
Self::increase_balance(asset, dest, amount, precision)?
Self::increase_balance(asset.clone(), dest, amount, precision)?
};
Self::done_transfer_on_hold(asset, reason, source, dest, actual);
Ok(actual)
@@ -405,14 +414,14 @@ pub trait Mutate<AccountId>:
expendability: Preservation,
force: Fortitude,
) -> Result<Self::Balance, DispatchError> {
ensure!(Self::hold_available(asset, reason, dest), TokenError::CannotCreateHold);
ensure!(Self::hold_available(asset.clone(), reason, dest), TokenError::CannotCreateHold);
ensure!(
Self::can_deposit(asset, dest, amount, Extant) == Success,
Self::can_deposit(asset.clone(), dest, amount, Extant) == Success,
TokenError::CannotCreate
);
let actual =
Self::decrease_balance(asset, source, amount, precision, expendability, force)?;
Self::increase_balance_on_hold(asset, reason, dest, actual, precision)?;
Self::decrease_balance(asset.clone(), source, amount, precision, expendability, force)?;
Self::increase_balance_on_hold(asset.clone(), reason, dest, actual, precision)?;
Self::done_transfer_on_hold(asset, reason, source, dest, actual);
Ok(actual)
}
@@ -59,7 +59,7 @@ impl<
{
fn drop(&mut self) {
if !self.amount.is_zero() {
OnDrop::handle(self.asset, self.amount)
OnDrop::handle(self.asset.clone(), self.amount)
}
}
}
@@ -104,9 +104,9 @@ impl<
pub fn split(self, amount: B) -> (Self, Self) {
let first = self.amount.min(amount);
let second = self.amount - first;
let asset = self.asset;
let asset = self.asset.clone();
sp_std::mem::forget(self);
(Imbalance::new(asset, first), Imbalance::new(asset, second))
(Imbalance::new(asset.clone(), first), Imbalance::new(asset, second))
}
pub fn merge(mut self, other: Self) -> Result<Self, (Self, Self)> {
if self.asset == other.asset {
@@ -135,7 +135,7 @@ impl<
> {
if self.asset == other.asset {
let (a, b) = (self.amount, other.amount);
let asset = self.asset;
let asset = self.asset.clone();
sp_std::mem::forget((self, other));
if a == b {
@@ -154,7 +154,7 @@ impl<
}
pub fn asset(&self) -> A {
self.asset
self.asset.clone()
}
}
@@ -146,7 +146,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
/// This should not be reimplemented.
fn handle_raw_dust(asset: Self::AssetId, amount: Self::Balance) {
Self::handle_dust(Dust(
asset,
asset.clone(),
amount.min(Self::minimum_balance(asset).saturating_sub(One::one())),
))
}
@@ -193,13 +193,13 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
preservation: Preservation,
force: Fortitude,
) -> Result<Self::Balance, DispatchError> {
let old_balance = Self::balance(asset, who);
let free = Self::reducible_balance(asset, who, preservation, force);
let old_balance = Self::balance(asset.clone(), who);
let free = Self::reducible_balance(asset.clone(), who, preservation, force);
if let BestEffort = precision {
amount = amount.min(free);
}
let new_balance = old_balance.checked_sub(&amount).ok_or(TokenError::FundsUnavailable)?;
if let Some(dust) = Self::write_balance(asset, who, new_balance)? {
if let Some(dust) = Self::write_balance(asset.clone(), who, new_balance)? {
Self::handle_dust(Dust(asset, dust));
}
Ok(old_balance.saturating_sub(new_balance))
@@ -217,13 +217,13 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
amount: Self::Balance,
precision: Precision,
) -> Result<Self::Balance, DispatchError> {
let old_balance = Self::balance(asset, who);
let old_balance = Self::balance(asset.clone(), who);
let new_balance = if let BestEffort = precision {
old_balance.saturating_add(amount)
} else {
old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?
};
if new_balance < Self::minimum_balance(asset) {
if new_balance < Self::minimum_balance(asset.clone()) {
// Attempt to increase from 0 to below minimum -> stays at zero.
if let BestEffort = precision {
Ok(Self::Balance::default())
@@ -234,7 +234,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
if new_balance == old_balance {
Ok(Self::Balance::default())
} else {
if let Some(dust) = Self::write_balance(asset, who, new_balance)? {
if let Some(dust) = Self::write_balance(asset.clone(), who, new_balance)? {
Self::handle_dust(Dust(asset, dust));
}
Ok(new_balance.saturating_sub(old_balance))
@@ -258,11 +258,14 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
who: &AccountId,
amount: Self::Balance,
) -> Result<Self::Balance, DispatchError> {
Self::total_issuance(asset)
Self::total_issuance(asset.clone())
.checked_add(&amount)
.ok_or(ArithmeticError::Overflow)?;
let actual = Self::increase_balance(asset, who, amount, Exact)?;
Self::set_total_issuance(asset, Self::total_issuance(asset).saturating_add(actual));
let actual = Self::increase_balance(asset.clone(), who, amount, Exact)?;
Self::set_total_issuance(
asset.clone(),
Self::total_issuance(asset.clone()).saturating_add(actual),
);
Self::done_mint_into(asset, who, amount);
Ok(actual)
}
@@ -277,13 +280,17 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
precision: Precision,
force: Fortitude,
) -> Result<Self::Balance, DispatchError> {
let actual = Self::reducible_balance(asset, who, Expendable, force).min(amount);
let actual = Self::reducible_balance(asset.clone(), who, Expendable, force).min(amount);
ensure!(actual == amount || precision == BestEffort, TokenError::FundsUnavailable);
Self::total_issuance(asset)
Self::total_issuance(asset.clone())
.checked_sub(&actual)
.ok_or(ArithmeticError::Overflow)?;
let actual = Self::decrease_balance(asset, who, actual, BestEffort, Expendable, force)?;
Self::set_total_issuance(asset, Self::total_issuance(asset).saturating_sub(actual));
let actual =
Self::decrease_balance(asset.clone(), who, actual, BestEffort, Expendable, force)?;
Self::set_total_issuance(
asset.clone(),
Self::total_issuance(asset.clone()).saturating_sub(actual),
);
Self::done_burn_from(asset, who, actual);
Ok(actual)
}
@@ -303,13 +310,17 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
who: &AccountId,
amount: Self::Balance,
) -> Result<Self::Balance, DispatchError> {
let actual = Self::reducible_balance(asset, who, Expendable, Polite).min(amount);
let actual = Self::reducible_balance(asset.clone(), who, Expendable, Polite).min(amount);
ensure!(actual == amount, TokenError::FundsUnavailable);
Self::total_issuance(asset)
Self::total_issuance(asset.clone())
.checked_sub(&actual)
.ok_or(ArithmeticError::Overflow)?;
let actual = Self::decrease_balance(asset, who, actual, BestEffort, Expendable, Polite)?;
Self::set_total_issuance(asset, Self::total_issuance(asset).saturating_sub(actual));
let actual =
Self::decrease_balance(asset.clone(), who, actual, BestEffort, Expendable, Polite)?;
Self::set_total_issuance(
asset.clone(),
Self::total_issuance(asset.clone()).saturating_sub(actual),
);
Self::done_shelve(asset, who, actual);
Ok(actual)
}
@@ -329,11 +340,14 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
who: &AccountId,
amount: Self::Balance,
) -> Result<Self::Balance, DispatchError> {
Self::total_issuance(asset)
Self::total_issuance(asset.clone())
.checked_add(&amount)
.ok_or(ArithmeticError::Overflow)?;
let actual = Self::increase_balance(asset, who, amount, Exact)?;
Self::set_total_issuance(asset, Self::total_issuance(asset).saturating_add(actual));
let actual = Self::increase_balance(asset.clone(), who, amount, Exact)?;
Self::set_total_issuance(
asset.clone(),
Self::total_issuance(asset.clone()).saturating_add(actual),
);
Self::done_restore(asset, who, amount);
Ok(actual)
}
@@ -346,13 +360,13 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
amount: Self::Balance,
preservation: Preservation,
) -> Result<Self::Balance, DispatchError> {
let _extra =
Self::can_withdraw(asset, source, amount).into_result(preservation != Expendable)?;
Self::can_deposit(asset, dest, amount, Extant).into_result()?;
Self::decrease_balance(asset, source, amount, BestEffort, preservation, Polite)?;
let _extra = Self::can_withdraw(asset.clone(), source, amount)
.into_result(preservation != Expendable)?;
Self::can_deposit(asset.clone(), dest, amount, Extant).into_result()?;
Self::decrease_balance(asset.clone(), source, amount, BestEffort, preservation, Polite)?;
// This should never fail as we checked `can_deposit` earlier. But we do a best-effort
// anyway.
let _ = Self::increase_balance(asset, dest, amount, BestEffort);
let _ = Self::increase_balance(asset.clone(), dest, amount, BestEffort);
Self::done_transfer(asset, source, dest, amount);
Ok(amount)
}
@@ -363,7 +377,7 @@ pub trait Mutate<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
///
/// Returns the new balance.
fn set_balance(asset: Self::AssetId, who: &AccountId, amount: Self::Balance) -> Self::Balance {
let b = Self::balance(asset, who);
let b = Self::balance(asset.clone(), who);
if b > amount {
Self::burn_from(asset, who, b - amount, BestEffort, Force).map(|d| b.saturating_sub(d))
} else {
@@ -391,7 +405,7 @@ impl<AccountId, U: Unbalanced<AccountId>> HandleImbalanceDrop<U::AssetId, U::Bal
for IncreaseIssuance<AccountId, U>
{
fn handle(asset: U::AssetId, amount: U::Balance) {
U::set_total_issuance(asset, U::total_issuance(asset).saturating_add(amount))
U::set_total_issuance(asset.clone(), U::total_issuance(asset).saturating_add(amount))
}
}
@@ -402,7 +416,7 @@ impl<AccountId, U: Unbalanced<AccountId>> HandleImbalanceDrop<U::AssetId, U::Bal
for DecreaseIssuance<AccountId, U>
{
fn handle(asset: U::AssetId, amount: U::Balance) {
U::set_total_issuance(asset, U::total_issuance(asset).saturating_sub(amount))
U::set_total_issuance(asset.clone(), U::total_issuance(asset).saturating_sub(amount))
}
}
@@ -423,11 +437,11 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
/// This is infallible, but doesn't guarantee that the entire `amount` is burnt, for example
/// in the case of underflow.
fn rescind(asset: Self::AssetId, amount: Self::Balance) -> Debt<AccountId, Self> {
let old = Self::total_issuance(asset);
let old = Self::total_issuance(asset.clone());
let new = old.saturating_sub(amount);
Self::set_total_issuance(asset, new);
Self::set_total_issuance(asset.clone(), new);
let delta = old - new;
Self::done_rescind(asset, delta);
Self::done_rescind(asset.clone(), delta);
Imbalance::<Self::AssetId, Self::Balance, Self::OnDropDebt, Self::OnDropCredit>::new(
asset, delta,
)
@@ -440,11 +454,11 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
/// This is infallible, but doesn't guarantee that the entire `amount` is issued, for example
/// in the case of overflow.
fn issue(asset: Self::AssetId, amount: Self::Balance) -> Credit<AccountId, Self> {
let old = Self::total_issuance(asset);
let old = Self::total_issuance(asset.clone());
let new = old.saturating_add(amount);
Self::set_total_issuance(asset, new);
Self::set_total_issuance(asset.clone(), new);
let delta = new - old;
Self::done_issue(asset, delta);
Self::done_issue(asset.clone(), delta);
Imbalance::<Self::AssetId, Self::Balance, Self::OnDropCredit, Self::OnDropDebt>::new(
asset, delta,
)
@@ -458,7 +472,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
asset: Self::AssetId,
amount: Self::Balance,
) -> (Debt<AccountId, Self>, Credit<AccountId, Self>) {
(Self::rescind(asset, amount), Self::issue(asset, amount))
(Self::rescind(asset.clone(), amount), Self::issue(asset, amount))
}
/// Mints `value` into the account of `who`, creating it as needed.
@@ -476,8 +490,8 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
value: Self::Balance,
precision: Precision,
) -> Result<Debt<AccountId, Self>, DispatchError> {
let increase = Self::increase_balance(asset, who, value, precision)?;
Self::done_deposit(asset, who, increase);
let increase = Self::increase_balance(asset.clone(), who, value, precision)?;
Self::done_deposit(asset.clone(), who, increase);
Ok(Imbalance::<Self::AssetId, Self::Balance, Self::OnDropDebt, Self::OnDropCredit>::new(
asset, increase,
))
@@ -504,8 +518,9 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
preservation: Preservation,
force: Fortitude,
) -> Result<Credit<AccountId, Self>, DispatchError> {
let decrease = Self::decrease_balance(asset, who, value, precision, preservation, force)?;
Self::done_withdraw(asset, who, decrease);
let decrease =
Self::decrease_balance(asset.clone(), who, value, precision, preservation, force)?;
Self::done_withdraw(asset.clone(), who, decrease);
Ok(Imbalance::<Self::AssetId, Self::Balance, Self::OnDropCredit, Self::OnDropDebt>::new(
asset, decrease,
))
@@ -545,7 +560,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> + Unbalanced<AccountId> {
) -> Result<Credit<AccountId, Self>, Debt<AccountId, Self>> {
let amount = debt.peek();
let asset = debt.asset();
let credit = match Self::withdraw(asset, who, amount, Exact, preservation, Polite) {
let credit = match Self::withdraw(asset.clone(), who, amount, Exact, preservation, Polite) {
Err(_) => return Err(debt),
Ok(d) => d,
};
@@ -221,10 +221,10 @@ impl WithdrawReasons {
/// Simple amalgamation trait to collect together properties for an AssetId under one roof.
pub trait AssetId:
FullCodec + Copy + Eq + PartialEq + Debug + scale_info::TypeInfo + MaxEncodedLen
FullCodec + Clone + Eq + PartialEq + Debug + scale_info::TypeInfo + MaxEncodedLen
{
}
impl<T: FullCodec + Copy + Eq + PartialEq + Debug + scale_info::TypeInfo + MaxEncodedLen> AssetId
impl<T: FullCodec + Clone + Eq + PartialEq + Debug + scale_info::TypeInfo + MaxEncodedLen> AssetId
for T
{
}