Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Add BalanceToAssetBalance Conversion Type #8776

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions frame/assets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ use sp_runtime::{
}
};
use codec::HasCompact;
use frame_support::{ensure, dispatch::{DispatchError, DispatchResult}};
use frame_support::pallet_prelude::*;
use frame_support::traits::{Currency, ReservableCurrency, BalanceStatus::Reserved, StoredMap};
use frame_support::traits::tokens::{WithdrawConsequence, DepositConsequence, fungibles};
use frame_system::Config as SystemConfig;
Expand All @@ -157,10 +157,6 @@ pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
use frame_support::{
dispatch::DispatchResult,
pallet_prelude::*,
};
use frame_system::pallet_prelude::*;
use super::*;

Expand Down
17 changes: 16 additions & 1 deletion frame/assets/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

use super::*;
use crate::{Error, mock::*};
use sp_runtime::TokenError;
use sp_runtime::{TokenError, traits::ConvertInto};
use frame_support::{assert_ok, assert_noop, traits::Currency};
use pallet_balances::Error as BalancesError;

Expand Down Expand Up @@ -625,3 +625,18 @@ fn force_asset_status_should_work(){
assert_eq!(Assets::total_supply(0), 200);
});
}

#[test]
fn balance_conversion_should_work() {
new_test_ext().execute_with(|| {
let id = 42;
assert_ok!(Assets::force_create(Origin::root(), id, 1, true, 10));
let not_sufficient = 23;
assert_ok!(Assets::force_create(Origin::root(), not_sufficient, 1, false, 10));

assert_eq!(BalanceToAssetBalance::<Balances, Test, ConvertInto>::to_asset_balance(100, 1234), Err(ConversionError::AssetMissing));
assert_eq!(BalanceToAssetBalance::<Balances, Test, ConvertInto>::to_asset_balance(100, not_sufficient), Err(ConversionError::AssetNotSufficient));
// 10 / 1 == 10 -> the conversion should 10x the value
assert_eq!(BalanceToAssetBalance::<Balances, Test, ConvertInto>::to_asset_balance(100, id), Ok(100 * 10));
});
}
55 changes: 55 additions & 0 deletions frame/assets/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
use super::*;
use frame_support::pallet_prelude::*;

use frame_support::traits::fungible;
use sp_runtime::{FixedPointNumber, FixedPointOperand, FixedU128};
use sp_runtime::traits::Convert;

pub(super) type DepositBalanceOf<T, I = ()> =
<<T as Config<I>>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;

Expand Down Expand Up @@ -177,3 +181,54 @@ impl From<TransferFlags> for DebitFlags {
}
}
}

/// Converts a balance value into an asset balance.
pub trait BalanceConversion<InBalance, AssetId, OutBalance> {
fn to_asset_balance(balance: InBalance, asset_id: AssetId) -> Result<OutBalance, ConversionError>;
}

/// Possible errors when converting between external and asset balances.
#[derive(Eq, PartialEq, Copy, Clone, RuntimeDebug, Encode, Decode)]
pub enum ConversionError {
/// The external minimum balance must not be zero.
MinBalanceZero,
/// The asset is not present in storage.
AssetMissing,
/// The asset is not sufficient and thus does not have a reliable `min_balance` so it cannot be converted.
AssetNotSufficient,
}

type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
type AssetIdOf<T, I> = <T as Config<I>>::AssetId;
type AssetBalanceOf<T, I> = <T as Config<I>>::Balance;
type BalanceOf<F, T> = <F as fungible::Inspect<AccountIdOf<T>>>::Balance;

/// Converts a balance value into an asset balance based on the ratio between the fungible's
/// minimum balance and the minimum asset balance.
pub struct BalanceToAssetBalance<F, T, CON, I = ()>(PhantomData<(F, T, CON, I)>);
impl<F, T, CON, I> BalanceConversion<BalanceOf<F, T>, AssetIdOf<T, I>, AssetBalanceOf<T, I>> for BalanceToAssetBalance<F, T, CON, I>
where
F: fungible::Inspect<AccountIdOf<T>>,
T: Config<I>,
I: 'static,
CON: Convert<BalanceOf<F, T>, AssetBalanceOf<T, I>>,
BalanceOf<F, T>: FixedPointOperand + Zero,
AssetBalanceOf<T, I>: FixedPointOperand + Zero,
{
/// Convert the given balance value into an asset balance based on the ratio between the fungible's
/// minimum balance and the minimum asset balance.
///
/// Will return `Err` if the asset is not found, not sufficient or the fungible's minimum balance is zero.
fn to_asset_balance(balance: BalanceOf<F, T>, asset_id: AssetIdOf<T, I>) -> Result<AssetBalanceOf<T, I>, ConversionError> {
let asset = Asset::<T, I>::get(asset_id).ok_or(ConversionError::AssetMissing)?;
// only sufficient assets have a min balance with reliable value
ensure!(asset.is_sufficient, ConversionError::AssetNotSufficient);
let min_balance = CON::convert(F::minimum_balance());
// make sure we don't divide by zero
ensure!(!min_balance.is_zero(), ConversionError::MinBalanceZero);
let balance = CON::convert(balance);
// balance * asset.min_balance / min_balance
Ok(FixedU128::saturating_from_rational(asset.min_balance, min_balance)
.saturating_mul_int(balance))
}
}