use super::*;
use alloc::vec;
use frame_support::{defensive, traits::Get, BoundedVec};
#[must_use]
pub(super) enum DeadConsequence {
Remove,
Keep,
}
use DeadConsequence::*;
impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub fn adjust_extra(
id: T::AssetId,
who: impl core::borrow::Borrow<T::AccountId>,
) -> Option<ExtraMutator<T, I>> {
ExtraMutator::maybe_new(id, who)
}
pub fn balance(id: T::AssetId, who: impl core::borrow::Borrow<T::AccountId>) -> T::Balance {
Self::maybe_balance(id, who).unwrap_or_default()
}
pub fn maybe_balance(
id: T::AssetId,
who: impl core::borrow::Borrow<T::AccountId>,
) -> Option<T::Balance> {
Account::<T, I>::get(id, who.borrow()).map(|a| a.balance)
}
pub fn total_supply(id: T::AssetId) -> T::Balance {
Self::maybe_total_supply(id).unwrap_or_default()
}
pub fn maybe_total_supply(id: T::AssetId) -> Option<T::Balance> {
Asset::<T, I>::get(id).map(|x| x.supply)
}
pub(super) fn new_account(
who: &T::AccountId,
d: &mut AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>,
maybe_deposit: Option<(&T::AccountId, DepositBalanceOf<T, I>)>,
) -> Result<ExistenceReasonOf<T, I>, DispatchError> {
let accounts = d.accounts.checked_add(1).ok_or(ArithmeticError::Overflow)?;
let reason = if let Some((depositor, deposit)) = maybe_deposit {
if depositor == who {
ExistenceReason::DepositHeld(deposit)
} else {
ExistenceReason::DepositFrom(depositor.clone(), deposit)
}
} else if d.is_sufficient {
frame_system::Pallet::<T>::inc_sufficients(who);
d.sufficients.saturating_inc();
ExistenceReason::Sufficient
} else {
frame_system::Pallet::<T>::inc_consumers(who)
.map_err(|_| Error::<T, I>::UnavailableConsumer)?;
if !frame_system::Pallet::<T>::can_inc_consumer(who) {
frame_system::Pallet::<T>::dec_consumers(who);
return Err(Error::<T, I>::UnavailableConsumer.into())
}
ExistenceReason::Consumer
};
d.accounts = accounts;
Ok(reason)
}
pub(super) fn dead_account(
who: &T::AccountId,
d: &mut AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>,
reason: &ExistenceReasonOf<T, I>,
force: bool,
) -> DeadConsequence {
use ExistenceReason::*;
match *reason {
Consumer => frame_system::Pallet::<T>::dec_consumers(who),
Sufficient => {
d.sufficients = d.sufficients.saturating_sub(1);
frame_system::Pallet::<T>::dec_sufficients(who);
},
DepositRefunded => {},
DepositHeld(_) | DepositFrom(..) if !force => return Keep,
DepositHeld(_) | DepositFrom(..) => {},
}
d.accounts = d.accounts.saturating_sub(1);
Remove
}
pub(super) fn can_increase(
id: T::AssetId,
who: &T::AccountId,
amount: T::Balance,
increase_supply: bool,
) -> DepositConsequence {
let details = match Asset::<T, I>::get(&id) {
Some(details) => details,
None => return DepositConsequence::UnknownAsset,
};
if details.status == AssetStatus::Destroying {
return DepositConsequence::UnknownAsset
}
if increase_supply && details.supply.checked_add(&amount).is_none() {
return DepositConsequence::Overflow
}
if let Some(account) = Account::<T, I>::get(id, who) {
if account.status.is_blocked() {
return DepositConsequence::Blocked
}
if account.balance.checked_add(&amount).is_none() {
return DepositConsequence::Overflow
}
} else {
if amount < details.min_balance {
return DepositConsequence::BelowMinimum
}
if !details.is_sufficient && !frame_system::Pallet::<T>::can_accrue_consumers(who, 2) {
return DepositConsequence::CannotCreate
}
if details.is_sufficient && details.sufficients.checked_add(1).is_none() {
return DepositConsequence::Overflow
}
}
DepositConsequence::Success
}
pub(super) fn can_decrease(
id: T::AssetId,
who: &T::AccountId,
amount: T::Balance,
keep_alive: bool,
) -> WithdrawConsequence<T::Balance> {
use WithdrawConsequence::*;
let details = match Asset::<T, I>::get(&id) {
Some(details) => details,
None => return UnknownAsset,
};
if details.supply.checked_sub(&amount).is_none() {
return Underflow
}
if details.status == AssetStatus::Frozen {
return Frozen
}
if details.status == AssetStatus::Destroying {
return UnknownAsset
}
if amount.is_zero() {
return Success
}
let account = match Account::<T, I>::get(&id, who) {
Some(a) => a,
None => return BalanceLow,
};
if account.status.is_frozen() {
return Frozen
}
if let Some(rest) = account.balance.checked_sub(&amount) {
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,
_ => {},
}
}
if rest < details.min_balance {
if keep_alive {
WouldDie
} else {
ReducedToZero(rest)
}
} else {
Success
}
} else {
BalanceLow
}
}
pub(super) fn reducible_balance(
id: T::AssetId,
who: &T::AccountId,
keep_alive: bool,
) -> Result<T::Balance, DispatchError> {
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)?;
ensure!(!account.status.is_frozen(), Error::<T, I>::Frozen);
let amount = if let Some(frozen) = T::Freezer::frozen_balance(id, who) {
let required =
frozen.checked_add(&details.min_balance).ok_or(ArithmeticError::Overflow)?;
account.balance.saturating_sub(required)
} else {
if keep_alive {
account.balance.saturating_sub(details.min_balance)
} else {
account.balance
}
};
Ok(amount.min(details.supply))
}
pub(super) fn prep_debit(
id: T::AssetId,
target: &T::AccountId,
amount: T::Balance,
f: DebitFlags,
) -> Result<T::Balance, DispatchError> {
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);
let actual = match conseq.into_result(f.keep_alive) {
Ok(dust) => actual.saturating_add(dust), Err(e) => {
debug_assert!(false, "passed from reducible_balance; qed");
return Err(e)
},
};
Ok(actual)
}
pub(super) fn prep_credit(
id: T::AssetId,
dest: &T::AccountId,
amount: T::Balance,
debit: T::Balance,
burn_dust: bool,
) -> Result<(T::Balance, Option<T::Balance>), DispatchError> {
let (credit, maybe_burn) = match (burn_dust, debit.checked_sub(&amount)) {
(true, Some(dust)) => (amount, Some(dust)),
_ => (debit, None),
};
Self::can_increase(id, dest, credit, false).into_result()?;
Ok((credit, maybe_burn))
}
pub(super) fn do_touch(
id: T::AssetId,
who: T::AccountId,
depositor: T::AccountId,
check_depositor: bool,
) -> DispatchResult {
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);
ensure!(
!check_depositor || &depositor == &details.admin || &depositor == &details.freezer,
Error::<T, I>::NoPermission
);
let reason = Self::new_account(&who, &mut details, Some((&depositor, deposit)))?;
T::Currency::reserve(&depositor, deposit)?;
Asset::<T, I>::insert(&id, details);
Account::<T, I>::insert(
&id,
&who,
AssetAccountOf::<T, I> {
balance: Zero::zero(),
status: AccountStatus::Liquid,
reason,
extra: T::Extra::default(),
},
);
Self::deposit_event(Event::Touched { asset_id: id, who, depositor });
Ok(())
}
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)?;
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);
ensure!(account.balance.is_zero() || allow_burn, Error::<T, I>::WouldBurn);
if let Some(deposit) = account.reason.take_deposit() {
T::Currency::unreserve(&who, deposit);
}
if let Remove = Self::dead_account(&who, &mut details, &account.reason, false) {
Account::<T, I>::remove(&id, &who);
} else {
debug_assert!(false, "refund did not result in dead account?!");
Account::<T, I>::insert(id, &who, account);
return Ok(())
}
Asset::<T, I>::insert(&id, details);
T::Freezer::died(id, &who);
Ok(())
}
pub(super) fn do_refund_other(
id: T::AssetId,
who: &T::AccountId,
maybe_check_caller: Option<T::AccountId>,
) -> DispatchResult {
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)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(!account.status.is_frozen(), Error::<T, I>::Frozen);
if let Some(caller) = maybe_check_caller {
ensure!(caller == depositor || caller == details.admin, Error::<T, I>::NoPermission);
}
ensure!(account.balance.is_zero(), Error::<T, I>::WouldBurn);
T::Currency::unreserve(&depositor, deposit);
if let Remove = Self::dead_account(&who, &mut details, &account.reason, false) {
Account::<T, I>::remove(&id, &who);
} else {
debug_assert!(false, "refund did not result in dead account?!");
Account::<T, I>::insert(&id, &who, account);
return Ok(())
}
Asset::<T, I>::insert(&id, details);
T::Freezer::died(id, &who);
return Ok(())
}
pub(super) fn do_mint(
id: T::AssetId,
beneficiary: &T::AccountId,
amount: T::Balance,
maybe_check_issuer: Option<T::AccountId>,
) -> 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);
}
debug_assert!(details.supply.checked_add(&amount).is_some(), "checked in prep; qed");
details.supply = details.supply.saturating_add(amount);
Ok(())
})?;
Self::deposit_event(Event::Issued { asset_id: id, owner: beneficiary.clone(), amount });
Ok(())
}
pub(super) fn increase_balance(
id: T::AssetId,
beneficiary: &T::AccountId,
amount: T::Balance,
check: impl FnOnce(
&mut AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>,
) -> DispatchResult,
) -> DispatchResult {
if amount.is_zero() {
return Ok(())
}
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 {
match maybe_account {
Some(ref mut account) => {
account.balance.saturating_accrue(amount);
},
maybe_account @ None => {
ensure!(amount >= details.min_balance, TokenError::BelowMinimum);
*maybe_account = Some(AssetAccountOf::<T, I> {
balance: amount,
reason: Self::new_account(beneficiary, details, None)?,
status: AccountStatus::Liquid,
extra: T::Extra::default(),
});
},
}
Ok(())
})?;
Ok(())
})?;
Ok(())
}
pub(super) fn do_burn(
id: T::AssetId,
target: &T::AccountId,
amount: T::Balance,
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)?;
ensure!(
d.status == AssetStatus::Live || d.status == AssetStatus::Frozen,
Error::<T, I>::IncorrectStatus
);
let actual = Self::decrease_balance(id.clone(), target, amount, f, |actual, details| {
if let Some(check_admin) = maybe_check_admin {
ensure!(check_admin == details.admin, Error::<T, I>::NoPermission);
}
debug_assert!(details.supply >= actual, "checked in prep; qed");
details.supply = details.supply.saturating_sub(actual);
Ok(())
})?;
Self::deposit_event(Event::Burned { asset_id: id, owner: target.clone(), balance: actual });
Ok(actual)
}
pub(super) fn decrease_balance(
id: T::AssetId,
target: &T::AccountId,
amount: T::Balance,
f: DebitFlags,
check: impl FnOnce(
T::Balance,
&mut AssetDetails<T::Balance, T::AccountId, DepositBalanceOf<T, I>>,
) -> DispatchResult,
) -> Result<T::Balance, DispatchError> {
if amount.is_zero() {
return Ok(amount)
}
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.clone(), target, amount, f)?;
let mut target_died: Option<DeadConsequence> = None;
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 {
let mut account = maybe_account.take().ok_or(Error::<T, I>::NoAccount)?;
debug_assert!(account.balance >= actual, "checked in prep; qed");
account.balance = account.balance.saturating_sub(actual);
if account.balance < details.min_balance {
debug_assert!(account.balance.is_zero(), "checked in prep; qed");
target_died = Some(Self::dead_account(target, details, &account.reason, false));
if let Some(Remove) = target_died {
return Ok(())
}
};
*maybe_account = Some(account);
Ok(())
})?;
Ok(())
})?;
if let Some(Remove) = target_died {
T::Freezer::died(id, target);
}
Ok(actual)
}
pub(super) fn do_transfer(
id: T::AssetId,
source: &T::AccountId,
dest: &T::AccountId,
amount: T::Balance,
maybe_need_admin: Option<T::AccountId>,
f: TransferFlags,
) -> Result<T::Balance, DispatchError> {
let (balance, died) =
Self::transfer_and_die(id.clone(), source, dest, amount, maybe_need_admin, f)?;
if let Some(Remove) = died {
T::Freezer::died(id, source);
}
Ok(balance)
}
fn transfer_and_die(
id: T::AssetId,
source: &T::AccountId,
dest: &T::AccountId,
amount: T::Balance,
maybe_need_admin: Option<T::AccountId>,
f: TransferFlags,
) -> Result<(T::Balance, Option<DeadConsequence>), DispatchError> {
if amount.is_zero() {
return Ok((amount, None))
}
let details = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
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)?;
let mut source_died: Option<DeadConsequence> = None;
Asset::<T, I>::try_mutate(&id, |maybe_details| -> DispatchResult {
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
if let Some(need_admin) = maybe_need_admin {
ensure!(need_admin == details.admin, Error::<T, I>::NoPermission);
}
if source == dest {
return Ok(())
}
if let Some(burn) = maybe_burn {
debug_assert!(details.supply >= burn, "checked in prep; qed");
details.supply = details.supply.saturating_sub(burn);
}
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 {
match maybe_account {
Some(ref mut account) => {
debug_assert!(
account.balance.checked_add(&credit).is_some(),
"checked in prep; qed"
);
account.balance.saturating_accrue(credit);
},
maybe_account @ None => {
*maybe_account = Some(AssetAccountOf::<T, I> {
balance: credit,
status: AccountStatus::Liquid,
reason: Self::new_account(dest, details, None)?,
extra: T::Extra::default(),
});
},
}
Ok(())
})?;
if source_account.balance < details.min_balance {
debug_assert!(source_account.balance.is_zero(), "checked in prep; qed");
source_died =
Some(Self::dead_account(source, details, &source_account.reason, false));
if let Some(Remove) = source_died {
Account::<T, I>::remove(&id, &source);
return Ok(())
}
}
Account::<T, I>::insert(&id, &source, &source_account);
Ok(())
})?;
Self::deposit_event(Event::Transferred {
asset_id: id,
from: source.clone(),
to: dest.clone(),
amount: credit,
});
Ok((credit, source_died))
}
pub(super) fn do_force_create(
id: T::AssetId,
owner: T::AccountId,
is_sufficient: bool,
min_balance: T::Balance,
) -> DispatchResult {
ensure!(!Asset::<T, I>::contains_key(&id), Error::<T, I>::InUse);
ensure!(!min_balance.is_zero(), Error::<T, I>::MinBalanceZero);
if let Some(next_id) = NextAssetId::<T, I>::get() {
ensure!(id == next_id, Error::<T, I>::BadAssetId);
}
Asset::<T, I>::insert(
&id,
AssetDetails {
owner: owner.clone(),
issuer: owner.clone(),
admin: owner.clone(),
freezer: owner.clone(),
supply: Zero::zero(),
deposit: Zero::zero(),
min_balance,
is_sufficient,
accounts: 0,
sufficients: 0,
approvals: 0,
status: AssetStatus::Live,
},
);
ensure!(T::CallbackHandle::created(&id, &owner).is_ok(), Error::<T, I>::CallbackFailed);
Self::deposit_event(Event::ForceCreated { asset_id: id, owner: owner.clone() });
Ok(())
}
pub(super) fn do_start_destroy(
id: T::AssetId,
maybe_check_owner: Option<T::AccountId>,
) -> DispatchResult {
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);
}
details.status = AssetStatus::Destroying;
Self::deposit_event(Event::DestructionStarted { asset_id: id });
Ok(())
})
}
pub(super) fn do_destroy_accounts(
id: T::AssetId,
max_items: u32,
) -> Result<u32, DispatchError> {
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> {
let mut details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
ensure!(details.status == AssetStatus::Destroying, Error::<T, I>::IncorrectStatus);
for (i, (who, mut v)) in Account::<T, I>::iter_prefix(&id).enumerate() {
if let Some((depositor, deposit)) = v.reason.take_deposit_from() {
T::Currency::unreserve(&depositor, deposit);
} else if let Some(deposit) = v.reason.take_deposit() {
T::Currency::unreserve(&who, deposit);
}
if let Remove = Self::dead_account(&who, &mut details, &v.reason, false) {
Account::<T, I>::remove(&id, &who);
dead_accounts.push(who);
} else {
Account::<T, I>::insert(&id, &who, v);
defensive!("destroy did not result in dead account?!");
}
if i + 1 >= (max_items as usize) {
break
}
}
remaining_accounts = details.accounts;
Ok(())
})?;
for who in &dead_accounts {
T::Freezer::died(id.clone(), &who);
}
Self::deposit_event(Event::AccountsDestroyed {
asset_id: id,
accounts_destroyed: dead_accounts.len() as u32,
accounts_remaining: remaining_accounts as u32,
});
Ok(dead_accounts.len() as u32)
}
pub(super) fn do_destroy_approvals(
id: T::AssetId,
max_items: u32,
) -> Result<u32, DispatchError> {
let mut removed_approvals = 0;
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)?;
ensure!(details.status == AssetStatus::Destroying, Error::<T, I>::IncorrectStatus);
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);
if removed_approvals >= max_items {
break
}
}
Self::deposit_event(Event::ApprovalsDestroyed {
asset_id: id,
approvals_destroyed: removed_approvals as u32,
approvals_remaining: details.approvals as u32,
});
Ok(())
},
)?;
Ok(removed_approvals)
}
pub(super) fn do_finish_destroy(id: T::AssetId) -> DispatchResult {
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);
ensure!(details.approvals == 0, Error::<T, I>::InUse);
ensure!(T::CallbackHandle::destroyed(&id).is_ok(), Error::<T, I>::CallbackFailed);
let metadata = Metadata::<T, I>::take(&id);
T::Currency::unreserve(
&details.owner,
details.deposit.saturating_add(metadata.deposit),
);
Self::deposit_event(Event::Destroyed { asset_id: id });
Ok(())
})
}
pub(super) fn do_approve_transfer(
id: T::AssetId,
owner: &T::AccountId,
delegate: &T::AccountId,
amount: T::Balance,
) -> DispatchResult {
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.clone(), &owner, &delegate),
|maybe_approved| -> DispatchResult {
let mut approved = match maybe_approved.take() {
Some(a) => a,
None => {
d.approvals.saturating_inc();
Default::default()
},
};
let deposit_required = T::ApprovalDeposit::get();
if approved.deposit < deposit_required {
T::Currency::reserve(owner, deposit_required - approved.deposit)?;
approved.deposit = deposit_required;
}
approved.amount = approved.amount.saturating_add(amount);
*maybe_approved = Some(approved);
Ok(())
},
)?;
Asset::<T, I>::insert(&id, d);
Self::deposit_event(Event::ApprovedTransfer {
asset_id: id,
source: owner.clone(),
delegate: delegate.clone(),
amount,
});
Ok(())
}
pub(super) fn do_transfer_approved(
id: T::AssetId,
owner: &T::AccountId,
delegate: &T::AccountId,
destination: &T::AccountId,
amount: T::Balance,
) -> DispatchResult {
let mut owner_died: Option<DeadConsequence> = None;
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.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.clone(), owner, destination, amount, None, f)?.1;
if remaining.is_zero() {
T::Currency::unreserve(owner, approved.deposit);
Asset::<T, I>::mutate(id.clone(), |maybe_details| {
if let Some(details) = maybe_details {
details.approvals.saturating_dec();
}
});
} else {
approved.amount = remaining;
*maybe_approved = Some(approved);
}
Ok(())
},
)?;
if let Some(Remove) = owner_died {
T::Freezer::died(id, owner);
}
Ok(())
}
pub(super) fn do_set_metadata(
id: T::AssetId,
from: &T::AccountId,
name: Vec<u8>,
symbol: Vec<u8>,
decimals: u8,
) -> DispatchResult {
let bounded_name: BoundedVec<u8, T::StringLimit> =
name.clone().try_into().map_err(|_| Error::<T, I>::BadMetadata)?;
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)?;
ensure!(d.status == AssetStatus::Live, Error::<T, I>::AssetNotLive);
ensure!(from == &d.owner, Error::<T, I>::NoPermission);
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);
let new_deposit = Self::calc_metadata_deposit(&name, &symbol);
if new_deposit > old_deposit {
T::Currency::reserve(from, new_deposit - old_deposit)?;
} else {
T::Currency::unreserve(from, old_deposit - new_deposit);
}
*metadata = Some(AssetMetadata {
deposit: new_deposit,
name: bounded_name,
symbol: bounded_symbol,
decimals,
is_frozen: false,
});
Self::deposit_event(Event::MetadataSet {
asset_id: id,
name,
symbol,
decimals,
is_frozen: false,
});
Ok(())
})
}
pub(super) fn calc_metadata_deposit(name: &[u8], symbol: &[u8]) -> DepositBalanceOf<T, I> {
T::MetadataDepositPerByte::get()
.saturating_mul(((name.len() + symbol.len()) as u32).into())
.saturating_add(T::MetadataDepositBase::get())
}
pub fn account_balances(account: T::AccountId) -> Vec<(T::AssetId, T::Balance)> {
Asset::<T, I>::iter_keys()
.filter_map(|id| {
Self::maybe_balance(id.clone(), account.clone()).map(|balance| (id, balance))
})
.collect::<Vec<_>>()
}
pub(crate) fn do_reset_team(
id: T::AssetId,
owner: T::AccountId,
admin: T::AccountId,
issuer: T::AccountId,
freezer: T::AccountId,
) -> DispatchResult {
let mut d = Asset::<T, I>::get(&id).ok_or(Error::<T, I>::Unknown)?;
d.owner = owner;
d.admin = admin;
d.issuer = issuer;
d.freezer = freezer;
Asset::<T, I>::insert(&id, d);
Ok(())
}
}