Skip to content

fungible helpers #619

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 5, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
209 changes: 209 additions & 0 deletions tokens/src/impls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
use codec::FullCodec;
use frame_support::dispatch::{DispatchError, DispatchResult};
use frame_support::traits::{
fungible, fungibles,
tokens::{DepositConsequence, WithdrawConsequence},
Contains, Get,
};
use sp_runtime::traits::AtLeast32BitUnsigned;
use sp_std::fmt::Debug;

pub struct Combiner<AccountId, TestKey, A, B>(sp_std::marker::PhantomData<(AccountId, TestKey, A, B)>);

impl<AccountId, TestKey, A, B> fungibles::Inspect<AccountId> for Combiner<AccountId, TestKey, A, B>
where
TestKey: Contains<<B as fungibles::Inspect<AccountId>>::AssetId>,
A: fungible::Inspect<AccountId, Balance = <B as fungibles::Inspect<AccountId>>::Balance>,
B: fungibles::Inspect<AccountId>,
{
type AssetId = <B as fungibles::Inspect<AccountId>>::AssetId;
type Balance = <B as fungibles::Inspect<AccountId>>::Balance;

fn total_issuance(asset: Self::AssetId) -> Self::Balance {
if TestKey::contains(&asset) {
A::total_issuance()
} else {
B::total_issuance(asset)
}
}

fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
if TestKey::contains(&asset) {
A::minimum_balance()
} else {
B::minimum_balance(asset)
}
}

fn balance(asset: Self::AssetId, who: &AccountId) -> Self::Balance {
if TestKey::contains(&asset) {
A::balance(who)
} else {
B::balance(asset, who)
}
}

fn reducible_balance(asset: Self::AssetId, who: &AccountId, keep_alive: bool) -> Self::Balance {
if TestKey::contains(&asset) {
A::reducible_balance(who, keep_alive)
} else {
B::reducible_balance(asset, who, keep_alive)
}
}

fn can_deposit(asset: Self::AssetId, who: &AccountId, amount: Self::Balance) -> DepositConsequence {
if TestKey::contains(&asset) {
A::can_deposit(who, amount)
} else {
B::can_deposit(asset, who, amount)
}
}

fn can_withdraw(
asset: Self::AssetId,
who: &AccountId,
amount: Self::Balance,
) -> WithdrawConsequence<Self::Balance> {
if TestKey::contains(&asset) {
A::can_withdraw(who, amount)
} else {
B::can_withdraw(asset, who, amount)
}
}
}

impl<AccountId, TestKey, A, B> fungibles::Transfer<AccountId> for Combiner<AccountId, TestKey, A, B>
where
TestKey: Contains<<B as fungibles::Inspect<AccountId>>::AssetId>,
A: fungible::Transfer<AccountId, Balance = <B as fungibles::Inspect<AccountId>>::Balance>,
B: fungibles::Transfer<AccountId>,
{
fn transfer(
asset: Self::AssetId,
source: &AccountId,
dest: &AccountId,
amount: Self::Balance,
keep_alive: bool,
) -> Result<Self::Balance, DispatchError> {
if TestKey::contains(&asset) {
A::transfer(source, dest, amount, keep_alive)
} else {
B::transfer(asset, source, dest, amount, keep_alive)
}
}
}

impl<AccountId, TestKey, A, B> fungibles::Mutate<AccountId> for Combiner<AccountId, TestKey, A, B>
where
TestKey: Contains<<B as fungibles::Inspect<AccountId>>::AssetId>,
A: fungible::Mutate<AccountId, Balance = <B as fungibles::Inspect<AccountId>>::Balance>,
B: fungibles::Mutate<AccountId>,
{
fn mint_into(asset: Self::AssetId, dest: &AccountId, amount: Self::Balance) -> DispatchResult {
if TestKey::contains(&asset) {
A::mint_into(dest, amount)
} else {
B::mint_into(asset, dest, amount)
}
}

fn burn_from(
asset: Self::AssetId,
dest: &AccountId,
amount: Self::Balance,
) -> Result<Self::Balance, DispatchError> {
if TestKey::contains(&asset) {
A::burn_from(dest, amount)
} else {
B::burn_from(asset, dest, amount)
}
}
}

pub trait ConvertBalance<A, B> {
fn convert_balance(amount: A) -> B;
fn convert_balance_back(amount: B) -> A;
}

pub struct Mapper<AccountId, T, C, B, GetCurrencyId>(sp_std::marker::PhantomData<(AccountId, T, C, B, GetCurrencyId)>);
impl<AccountId, T, C, B, GetCurrencyId> fungible::Inspect<AccountId> for Mapper<AccountId, T, C, B, GetCurrencyId>
where
T: fungibles::Inspect<AccountId>,
C: ConvertBalance<<T as fungibles::Inspect<AccountId>>::Balance, B>,
// TOOD: use trait Balance after https://github.com/paritytech/substrate/pull/9863 is available
B: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug,
GetCurrencyId: Get<<T as fungibles::Inspect<AccountId>>::AssetId>,
{
type Balance = B;

fn total_issuance() -> Self::Balance {
C::convert_balance(T::total_issuance(GetCurrencyId::get()))
}

fn minimum_balance() -> Self::Balance {
C::convert_balance(T::minimum_balance(GetCurrencyId::get()))
}

fn balance(who: &AccountId) -> Self::Balance {
C::convert_balance(T::balance(GetCurrencyId::get(), who))
}

fn reducible_balance(who: &AccountId, keep_alive: bool) -> Self::Balance {
C::convert_balance(T::reducible_balance(GetCurrencyId::get(), who, keep_alive))
}

fn can_deposit(who: &AccountId, amount: Self::Balance) -> DepositConsequence {
T::can_deposit(GetCurrencyId::get(), who, C::convert_balance_back(amount))
}

fn can_withdraw(who: &AccountId, amount: Self::Balance) -> WithdrawConsequence<Self::Balance> {
use WithdrawConsequence::*;
let res = T::can_withdraw(GetCurrencyId::get(), who, C::convert_balance_back(amount));
match res {
WithdrawConsequence::ReducedToZero(b) => WithdrawConsequence::ReducedToZero(C::convert_balance(b)),
NoFunds => NoFunds,
WouldDie => WouldDie,
UnknownAsset => UnknownAsset,
Underflow => Underflow,
Overflow => Overflow,
Frozen => Frozen,
Success => Success,
}
}
}

impl<AccountId, T, C, B, GetCurrencyId> fungible::Transfer<AccountId> for Mapper<AccountId, T, C, B, GetCurrencyId>
where
T: fungibles::Transfer<AccountId, Balance = B>,
C: ConvertBalance<<T as fungibles::Inspect<AccountId>>::Balance, B>,
// TOOD: use trait Balance after https://github.com/paritytech/substrate/pull/9863 is available
B: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug,
GetCurrencyId: Get<<T as fungibles::Inspect<AccountId>>::AssetId>,
{
fn transfer(source: &AccountId, dest: &AccountId, amount: B, keep_alive: bool) -> Result<B, DispatchError> {
T::transfer(
GetCurrencyId::get(),
source,
dest,
C::convert_balance_back(amount),
keep_alive,
)
}
}

impl<AccountId, T, C, B, GetCurrencyId> fungible::Mutate<AccountId> for Mapper<AccountId, T, C, B, GetCurrencyId>
where
T: fungibles::Mutate<AccountId, Balance = B>,
C: ConvertBalance<<T as fungibles::Inspect<AccountId>>::Balance, B>,
// TOOD: use trait Balance after https://github.com/paritytech/substrate/pull/9863 is available
B: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug,
GetCurrencyId: Get<<T as fungibles::Inspect<AccountId>>::AssetId>,
{
fn mint_into(dest: &AccountId, amount: Self::Balance) -> DispatchResult {
T::mint_into(GetCurrencyId::get(), dest, C::convert_balance_back(amount))
}

fn burn_from(dest: &AccountId, amount: Self::Balance) -> Result<Self::Balance, DispatchError> {
T::burn_from(GetCurrencyId::get(), dest, C::convert_balance_back(amount))
}
}
2 changes: 2 additions & 0 deletions tokens/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ use orml_traits::{
};

mod imbalances;
mod impls;
mod mock;
mod tests;
mod weights;

pub use impls::*;
pub use weights::WeightInfo;

pub struct TransferDust<T, GetAccountId>(marker::PhantomData<(T, GetAccountId)>);
Expand Down
156 changes: 156 additions & 0 deletions tokens/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2079,3 +2079,159 @@ fn fungibles_mutate_hold_trait_should_work() {
);
});
}

#[test]
fn fungibles_inspect_convert_should_work() {
pub struct ConvertBalanceTest;
impl ConvertBalance<Balance, Balance> for ConvertBalanceTest {
fn convert_balance(balance: Balance) -> Balance {
balance * 100
}

fn convert_balance_back(balance: Balance) -> Balance {
balance / 100
}
}

pub struct IsLiquidToken;
impl Contains<CurrencyId> for IsLiquidToken {
fn contains(currency_id: &CurrencyId) -> bool {
matches!(currency_id, &DOT)
}
}

pub struct GetCurrencyId;
impl Get<CurrencyId> for GetCurrencyId {
fn get() -> CurrencyId {
DOT
}
}

type RebaseTokens = Combiner<
AccountId,
IsLiquidToken,
Mapper<AccountId, Tokens, ConvertBalanceTest, Balance, GetCurrencyId>,
Tokens,
>;

ExtBuilder::default()
.balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)])
.build()
.execute_with(|| {
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::balance(DOT, &ALICE),
10000
);
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::total_issuance(DOT),
20000
);
});
}

#[test]
fn fungibles_transfers_convert_should_work() {
pub struct ConvertBalanceTest;
impl ConvertBalance<Balance, Balance> for ConvertBalanceTest {
fn convert_balance(balance: Balance) -> Balance {
balance * 100
}

fn convert_balance_back(balance: Balance) -> Balance {
balance / 100
}
}

pub struct IsLiquidToken;
impl Contains<CurrencyId> for IsLiquidToken {
fn contains(currency_id: &CurrencyId) -> bool {
matches!(currency_id, &DOT)
}
}

pub struct GetCurrencyId;
impl Get<CurrencyId> for GetCurrencyId {
fn get() -> CurrencyId {
DOT
}
}

type RebaseTokens = Combiner<
AccountId,
IsLiquidToken,
Mapper<AccountId, Tokens, ConvertBalanceTest, Balance, GetCurrencyId>,
Tokens,
>;

ExtBuilder::default()
.balances(vec![(ALICE, DOT, 300), (BOB, DOT, 200)])
.build()
.execute_with(|| {
assert_ok!(<RebaseTokens as fungibles::Transfer<AccountId>>::transfer(
DOT, &ALICE, &BOB, 10000, true
));
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::balance(DOT, &ALICE),
20000
);
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::balance(DOT, &BOB),
30000
);
});
}

#[test]
fn fungibles_mutate_convert_should_work() {
pub struct ConvertBalanceTest;
impl ConvertBalance<Balance, Balance> for ConvertBalanceTest {
fn convert_balance(balance: Balance) -> Balance {
balance * 100
}

fn convert_balance_back(balance: Balance) -> Balance {
balance / 100
}
}

pub struct IsLiquidToken;
impl Contains<CurrencyId> for IsLiquidToken {
fn contains(currency_id: &CurrencyId) -> bool {
matches!(currency_id, &DOT)
}
}

pub struct GetCurrencyId;
impl Get<CurrencyId> for GetCurrencyId {
fn get() -> CurrencyId {
DOT
}
}

type RebaseTokens = Combiner<
AccountId,
IsLiquidToken,
Mapper<AccountId, Tokens, ConvertBalanceTest, Balance, GetCurrencyId>,
Tokens,
>;

ExtBuilder::default()
.balances(vec![(ALICE, DOT, 300), (BOB, DOT, 200)])
.build()
.execute_with(|| {
assert_ok!(<RebaseTokens as fungibles::Mutate<AccountId>>::mint_into(
DOT, &ALICE, 10000
));
assert_ok!(<RebaseTokens as fungibles::Mutate<AccountId>>::burn_from(
DOT, &BOB, 10000
));
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::balance(DOT, &ALICE),
40000
);
assert_eq!(
<RebaseTokens as fungibles::Inspect<AccountId>>::balance(DOT, &BOB),
10000
);
});
}