From 1858039cf01386690361e59359a29e401578c9bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Enrique=20Mu=C3=B1oz=20Mart=C3=ADn?= Date: Wed, 7 Feb 2024 07:26:59 +0100 Subject: [PATCH] Add typed balances to FI and OrderBook. (#1719) * typed balances in foreing-investment * typed balances in pallet-order-book * order-book in runtimes * fix pool mocks * fix IT --- libs/mocks/src/investment.rs | 11 +- libs/mocks/src/token_swaps.rs | 24 +-- libs/traits/src/investments.rs | 12 +- libs/traits/src/lib.rs | 18 ++- libs/types/src/investments.rs | 44 +++--- pallets/foreign-investments/src/entities.rs | 147 +++++++++++------- pallets/foreign-investments/src/impls.rs | 76 ++++----- pallets/foreign-investments/src/lib.rs | 78 +++++++--- pallets/foreign-investments/src/mock.rs | 14 +- pallets/foreign-investments/src/swaps.rs | 16 +- pallets/investments/src/lib.rs | 13 +- pallets/investments/src/mock.rs | 2 +- pallets/liquidity-pools/src/hooks.rs | 8 +- pallets/liquidity-pools/src/lib.rs | 3 +- pallets/order-book/src/benchmarking.rs | 15 +- pallets/order-book/src/lib.rs | 141 +++++++++-------- pallets/order-book/src/mock.rs | 7 +- pallets/pool-registry/src/mock.rs | 2 +- pallets/pool-system/src/mock.rs | 2 +- runtime/altair/src/lib.rs | 3 +- runtime/altair/src/liquidity_pools.rs | 6 +- runtime/centrifuge/src/lib.rs | 3 +- runtime/centrifuge/src/liquidity_pools.rs | 6 +- runtime/common/src/lib.rs | 2 - runtime/development/src/lib.rs | 3 +- runtime/development/src/liquidity_pools.rs | 6 +- .../integration-tests/src/generic/config.rs | 7 +- .../tests/liquidity_pools/setup.rs | 1 - 28 files changed, 391 insertions(+), 279 deletions(-) delete mode 100644 runtime/integration-tests/src/liquidity_pools/pallet/development/tests/liquidity_pools/setup.rs diff --git a/libs/mocks/src/investment.rs b/libs/mocks/src/investment.rs index f35cdc1ef1..b42052c74b 100644 --- a/libs/mocks/src/investment.rs +++ b/libs/mocks/src/investment.rs @@ -7,6 +7,7 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { type Amount; + type TrancheAmount; type CurrencyId; type InvestmentId; } @@ -42,7 +43,7 @@ pub mod pallet { } pub fn mock_update_redemption( - f: impl Fn(&T::AccountId, T::InvestmentId, T::Amount) -> DispatchResult + 'static, + f: impl Fn(&T::AccountId, T::InvestmentId, T::TrancheAmount) -> DispatchResult + 'static, ) { register_call!(move |(a, b, c)| f(a, b, c)); } @@ -54,7 +55,8 @@ pub mod pallet { } pub fn mock_redemption( - f: impl Fn(&T::AccountId, T::InvestmentId) -> Result + 'static, + f: impl Fn(&T::AccountId, T::InvestmentId) -> Result + + 'static, ) { register_call!(move |(a, b)| f(a, b)); } @@ -89,6 +91,7 @@ pub mod pallet { type CurrencyId = T::CurrencyId; type Error = DispatchError; type InvestmentId = T::InvestmentId; + type TrancheAmount = T::TrancheAmount; fn update_investment( a: &T::AccountId, @@ -112,7 +115,7 @@ pub mod pallet { fn update_redemption( a: &T::AccountId, b: Self::InvestmentId, - c: Self::Amount, + c: Self::TrancheAmount, ) -> DispatchResult { execute_call!((a, b, c)) } @@ -124,7 +127,7 @@ pub mod pallet { fn redemption( a: &T::AccountId, b: Self::InvestmentId, - ) -> Result { + ) -> Result { execute_call!((a, b)) } diff --git a/libs/mocks/src/token_swaps.rs b/libs/mocks/src/token_swaps.rs index 51d285f304..4eb8deb6af 100644 --- a/libs/mocks/src/token_swaps.rs +++ b/libs/mocks/src/token_swaps.rs @@ -7,7 +7,8 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { type CurrencyId; - type Balance; + type BalanceIn; + type BalanceOut; type Ratio; type OrderId; type OrderDetails; @@ -30,7 +31,7 @@ pub mod pallet { T::AccountId, T::CurrencyId, T::CurrencyId, - T::Balance, + T::BalanceOut, OrderRatio, ) -> Result + 'static, @@ -39,7 +40,7 @@ pub mod pallet { } pub fn mock_update_order( - f: impl Fn(T::OrderId, T::Balance, OrderRatio) -> DispatchResult + 'static, + f: impl Fn(T::OrderId, T::BalanceOut, OrderRatio) -> DispatchResult + 'static, ) { register_call!(move |(a, b, c)| f(a, b, c)); } @@ -63,7 +64,11 @@ pub mod pallet { } pub fn mock_convert_by_market( - f: impl Fn(T::CurrencyId, T::CurrencyId, T::Balance) -> Result + f: impl Fn( + T::CurrencyId, + T::CurrencyId, + T::BalanceOut, + ) -> Result + 'static, ) { register_call!(move |(a, b, c)| f(a, b, c)); @@ -71,7 +76,8 @@ pub mod pallet { } impl TokenSwaps for Pallet { - type Balance = T::Balance; + type BalanceIn = T::BalanceOut; + type BalanceOut = T::BalanceIn; type CurrencyId = T::CurrencyId; type OrderDetails = T::OrderDetails; type OrderId = T::OrderId; @@ -81,7 +87,7 @@ pub mod pallet { a: T::AccountId, b: Self::CurrencyId, c: Self::CurrencyId, - d: Self::Balance, + d: Self::BalanceOut, e: OrderRatio, ) -> Result { execute_call!((a, b, c, d, e)) @@ -89,7 +95,7 @@ pub mod pallet { fn update_order( a: Self::OrderId, - b: Self::Balance, + b: Self::BalanceOut, c: OrderRatio, ) -> DispatchResult { execute_call!((a, b, c)) @@ -110,8 +116,8 @@ pub mod pallet { fn convert_by_market( a: Self::CurrencyId, b: Self::CurrencyId, - c: Self::Balance, - ) -> Result { + c: Self::BalanceOut, + ) -> Result { execute_call!((a, b, c)) } } diff --git a/libs/traits/src/investments.rs b/libs/traits/src/investments.rs index 787a99818e..2f03c7fa4e 100644 --- a/libs/traits/src/investments.rs +++ b/libs/traits/src/investments.rs @@ -27,6 +27,7 @@ pub trait TrancheCurrency { /// investment classes pub trait Investment { type Amount; + type TrancheAmount; type CurrencyId; type Error: Debug; type InvestmentId; @@ -66,7 +67,7 @@ pub trait Investment { fn update_redemption( who: &AccountId, investment_id: Self::InvestmentId, - amount: Self::Amount, + amount: Self::TrancheAmount, ) -> Result<(), Self::Error>; /// Checks whether a currency is accepted as a payout for the given @@ -84,7 +85,7 @@ pub trait Investment { fn redemption( who: &AccountId, investment_id: Self::InvestmentId, - ) -> Result; + ) -> Result; /// Checks whether an investment requires to be collected before it can be /// updated. @@ -225,6 +226,7 @@ pub trait InvestmentAccountant { /// NOTE: Has many similarities with the [Investment] trait. pub trait ForeignInvestment { type Amount; + type TrancheAmount; type CurrencyId; type Error: Debug; type InvestmentId; @@ -268,7 +270,7 @@ pub trait ForeignInvestment { fn increase_foreign_redemption( who: &AccountId, investment_id: Self::InvestmentId, - amount: Self::Amount, + amount: Self::TrancheAmount, foreign_payout_currency: Self::CurrencyId, ) -> Result<(), Self::Error>; @@ -282,7 +284,7 @@ pub trait ForeignInvestment { fn decrease_foreign_redemption( who: &AccountId, investment_id: Self::InvestmentId, - amount: Self::Amount, + amount: Self::TrancheAmount, foreign_payout_currency: Self::CurrencyId, ) -> Result<(), Self::Error>; @@ -326,7 +328,7 @@ pub trait ForeignInvestment { fn redemption( who: &AccountId, investment_id: Self::InvestmentId, - ) -> Result; + ) -> Result; /// Checks whether a currency can be used for buying the given investment. fn accepted_payment_currency( diff --git a/libs/traits/src/lib.rs b/libs/traits/src/lib.rs index ea03873db7..cf5a24413b 100644 --- a/libs/traits/src/lib.rs +++ b/libs/traits/src/lib.rs @@ -512,7 +512,8 @@ pub enum OrderRatio { pub trait TokenSwaps { type CurrencyId; - type Balance; + type BalanceOut; + type BalanceIn; type Ratio; type OrderId; type OrderDetails; @@ -523,14 +524,14 @@ pub trait TokenSwaps { account: Account, currency_in: Self::CurrencyId, currency_out: Self::CurrencyId, - amount_out: Self::Balance, + amount_out: Self::BalanceOut, ratio: OrderRatio, ) -> Result; /// Update an existing active order. fn update_order( order_id: Self::OrderId, - amount_out: Self::Balance, + amount_out: Self::BalanceOut, ratio: OrderRatio, ) -> DispatchResult; @@ -550,8 +551,8 @@ pub trait TokenSwaps { fn convert_by_market( currency_in: Self::CurrencyId, currency_out: Self::CurrencyId, - amount_out: Self::Balance, - ) -> Result; + amount_out: Self::BalanceOut, + ) -> Result; } /// Trait to transmit a change of status for anything uniquely identifiable. @@ -621,9 +622,10 @@ pub trait TryConvert { // TODO: Remove usage for the one from frame_support::traits::tokens once we are // on the same Polkadot version pub trait ConversionToAssetBalance { - type Error; - fn to_asset_balance(balance: InBalance, asset_id: AssetId) - -> Result; + fn to_asset_balance( + balance: InBalance, + asset_id: AssetId, + ) -> Result; } /// Converts an asset balance value into balance. diff --git a/libs/types/src/investments.rs b/libs/types/src/investments.rs index eaa1898542..64be9aae4a 100644 --- a/libs/types/src/investments.rs +++ b/libs/types/src/investments.rs @@ -16,7 +16,7 @@ use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{ traits::{EnsureAddAssign, Zero}, - ArithmeticError, DispatchError, + DispatchError, DispatchResult, }; use sp_std::cmp::PartialEq; @@ -116,36 +116,30 @@ impl RedeemCollection { /// The collected investment/redemption amount for an account #[derive(Encode, Default, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct CollectedAmount { +pub struct CollectedAmount { /// The amount which was collected /// * If investment: Tranche tokens /// * If redemption: Payment currency - pub amount_collected: Balance, + pub amount_collected: Collected, /// The amount which was converted during processing based on the /// fulfillment price(s) /// * If investment: Payment currency /// * If redemption: Tranche tokens - pub amount_payment: Balance, + pub amount_payment: Payment, } -impl CollectedAmount { - pub fn increase(&mut self, other: &Self) -> Result<(), ArithmeticError> { +impl + CollectedAmount +{ + pub fn increase(&mut self, other: &Self) -> DispatchResult { self.amount_collected .ensure_add_assign(other.amount_collected)?; - self.amount_payment.ensure_add_assign(other.amount_payment) - } -} - -/// A representation of an investment identifier and the corresponding owner. -/// -/// NOTE: Trimmed version of `InvestmentInfo` required for foreign investments. -#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)] + self.amount_payment + .ensure_add_assign(other.amount_payment)?; -pub struct ForeignInvestmentInfo { - pub owner: AccountId, - pub id: InvestmentId, - pub last_swap_reason: Option, + Ok(()) + } } /// A simple representation of a currency swap. @@ -177,14 +171,14 @@ impl Swap { /// A representation of a currency swap in process. #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct SwapState { +pub struct SwapState { /// Swap not yet processed with the pending outcomming amount - pub remaining: Swap, + pub remaining: Swap, /// Amount of incoming currency already swapped - pub swapped_in: Balance, + pub swapped_in: BalanceIn, /// Amount of incoming currency already swapped denominated in outgoing /// currency - pub swapped_out: Balance, + pub swapped_out: BalanceOut, } /// A representation of an executed investment decrement. @@ -203,7 +197,7 @@ pub struct ExecutedForeignDecreaseInvest { /// A representation of an executed collected foreign investment or redemption. #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)] -pub struct ExecutedForeignCollect { +pub struct ExecutedForeignCollect { /// The foreign currency in which ... /// * If investment: the payment took place /// * If redemption: the payout takes place @@ -217,14 +211,14 @@ pub struct ExecutedForeignCollect { /// The amount of tranche tokens... /// * If investment: received for the investment made /// * If redemption: which were actually redeemed - pub amount_tranche_tokens_payout: Balance, + pub amount_tranche_tokens_payout: TrancheTokens, /// The unprocessed ... /// * If investment: investment amount of `currency` (denominated in foreign /// currency) /// * If redemption: redemption amount of tranche tokens (denominated in /// pool currency) - pub amount_remaining: Balance, + pub amount_remaining: Remaining, } /// A representation of an investment portfolio consisting of free, pending and diff --git a/pallets/foreign-investments/src/entities.rs b/pallets/foreign-investments/src/entities.rs index 0707308601..67b463525e 100644 --- a/pallets/foreign-investments/src/entities.rs +++ b/pallets/foreign-investments/src/entities.rs @@ -32,12 +32,12 @@ use crate::{ #[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebugNoBound)] #[scale_info(skip_type_params(T))] pub struct Correlation { - pub pool_amount: T::Balance, - pub foreign_amount: T::Balance, + pub pool_amount: T::PoolBalance, + pub foreign_amount: T::ForeignBalance, } impl Correlation { - pub fn new(pool_amount: T::Balance, foreign_amount: T::Balance) -> Self { + pub fn new(pool_amount: T::PoolBalance, foreign_amount: T::ForeignBalance) -> Self { Self { pool_amount, foreign_amount, @@ -48,8 +48,8 @@ impl Correlation { /// The difference between both values will affect the correlation pub fn increase( &mut self, - pool_amount: T::Balance, - foreign_amount: T::Balance, + pool_amount: T::PoolBalance, + foreign_amount: T::ForeignBalance, ) -> DispatchResult { self.pool_amount.ensure_add_assign(pool_amount)?; self.foreign_amount.ensure_add_assign(foreign_amount)?; @@ -59,7 +59,7 @@ impl Correlation { /// Decrease a correlation /// The foreign amount amount is proportionally decreased - pub fn decrease(&mut self, pool_amount: T::Balance) -> DispatchResult { + pub fn decrease(&mut self, pool_amount: T::PoolBalance) -> DispatchResult { let foreign_amount = self.pool_to_foreign(pool_amount)?; self.pool_amount.ensure_sub_assign(pool_amount)?; @@ -69,25 +69,33 @@ impl Correlation { } /// Transform any pool amount into a foreign amount - pub fn pool_to_foreign(&self, pool_amount: T::Balance) -> Result { + pub fn pool_to_foreign( + &self, + pool_amount: T::PoolBalance, + ) -> Result { if pool_amount.is_zero() { - return Ok(T::Balance::default()); + return Ok(T::ForeignBalance::zero()); } Ok(pool_amount - .ensure_mul(self.foreign_amount)? - .ensure_div(self.pool_amount)?) + .ensure_mul(self.foreign_amount.into())? + .ensure_div(self.pool_amount)? + .into()) } /// Transform any foreign amount into a pool amount - pub fn foreign_to_pool(&self, foreign_amount: T::Balance) -> Result { + pub fn foreign_to_pool( + &self, + foreign_amount: T::ForeignBalance, + ) -> Result { if foreign_amount.is_zero() { - return Ok(T::Balance::default()); + return Ok(T::PoolBalance::zero()); } Ok(foreign_amount - .ensure_mul(self.pool_amount)? - .ensure_div(self.foreign_amount)?) + .ensure_mul(self.pool_amount.into())? + .ensure_div(self.foreign_amount)? + .into()) } } @@ -112,15 +120,15 @@ pub struct InvestmentInfo { /// Total decrease swapped amount pending to execute. /// It accumulates different partial swaps. - pub decrease_swapped_foreign_amount: T::Balance, + pub decrease_swapped_foreign_amount: T::ForeignBalance, } impl InvestmentInfo { pub fn new(foreign_currency: T::CurrencyId) -> Self { Self { foreign_currency, - correlation: Correlation::new(T::Balance::default(), T::Balance::default()), - decrease_swapped_foreign_amount: T::Balance::default(), + correlation: Correlation::new(T::PoolBalance::zero(), T::ForeignBalance::zero()), + decrease_swapped_foreign_amount: T::ForeignBalance::zero(), } } @@ -138,12 +146,12 @@ impl InvestmentInfo { &mut self, _who: &T::AccountId, investment_id: T::InvestmentId, - foreign_amount: T::Balance, + foreign_amount: T::ForeignBalance, ) -> Result, DispatchError> { Ok(Swap { currency_in: pool_currency_of::(investment_id)?, currency_out: self.foreign_currency, - amount_out: foreign_amount, + amount_out: foreign_amount.into(), }) } @@ -154,7 +162,7 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - foreign_amount: T::Balance, + foreign_amount: T::ForeignBalance, ) -> Result, DispatchError> { let pool_currency = pool_currency_of::(investment_id)?; @@ -180,13 +188,13 @@ impl InvestmentInfo { let increasing_pool_amount = T::TokenSwaps::convert_by_market( pool_currency, self.foreign_currency, - min(foreign_amount, increasing_foreign_amount), + min(foreign_amount, increasing_foreign_amount).into(), )?; Ok(Swap { currency_in: self.foreign_currency, currency_out: pool_currency, - amount_out: increasing_pool_amount.ensure_add(pool_investment_decrement)?, + amount_out: increasing_pool_amount.ensure_add(pool_investment_decrement.into())?, }) } @@ -195,8 +203,8 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - swapped_pool_amount: T::Balance, - swapped_foreign_amount: T::Balance, + swapped_pool_amount: T::PoolBalance, + swapped_foreign_amount: T::ForeignBalance, ) -> DispatchResult { self.correlation .increase(swapped_pool_amount, swapped_foreign_amount)?; @@ -210,9 +218,12 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - swapped_pool_amount: T::Balance, - swapped_foreign_amount: T::Balance, - ) -> Result>, DispatchError> { + swapped_pool_amount: T::PoolBalance, + swapped_foreign_amount: T::ForeignBalance, + ) -> Result< + Option>, + DispatchError, + > { self.increase_investment(who, investment_id, swapped_pool_amount)?; self.decrease_swapped_foreign_amount @@ -236,10 +247,13 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - swapped_foreign_amount: T::Balance, - swapped_pool_amount: T::Balance, - pending_pool_amount: T::Balance, - ) -> Result>, DispatchError> { + swapped_foreign_amount: T::ForeignBalance, + swapped_pool_amount: T::PoolBalance, + pending_pool_amount: T::PoolBalance, + ) -> Result< + Option>, + DispatchError, + > { self.correlation.decrease(swapped_pool_amount)?; self.post_decrease_swap_by_cancel( @@ -256,9 +270,12 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - swapped_foreign_amount: T::Balance, - pending_pool_amount: T::Balance, - ) -> Result>, DispatchError> { + swapped_foreign_amount: T::ForeignBalance, + pending_pool_amount: T::PoolBalance, + ) -> Result< + Option>, + DispatchError, + > { self.decrease_swapped_foreign_amount .ensure_add_assign(swapped_foreign_amount)?; @@ -279,8 +296,16 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - collected: CollectedAmount, - ) -> Result, DispatchError> { + collected: CollectedAmount, + ) -> Result< + ExecutedForeignCollect< + T::ForeignBalance, + T::TrancheBalance, + T::ForeignBalance, + T::CurrencyId, + >, + DispatchError, + > { let collected_foreign_amount = self.correlation.pool_to_foreign(collected.amount_payment)?; @@ -298,7 +323,7 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - pool_amount: T::Balance, + pool_amount: T::PoolBalance, ) -> DispatchResult { if !pool_amount.is_zero() { T::Investment::update_investment( @@ -315,7 +340,7 @@ impl InvestmentInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - pool_amount: T::Balance, + pool_amount: T::PoolBalance, ) -> DispatchResult { if !pool_amount.is_zero() { T::Investment::update_investment( @@ -340,7 +365,7 @@ impl InvestmentInfo { &self, who: &T::AccountId, investment_id: T::InvestmentId, - ) -> Result { + ) -> Result { let investment_and_pending_decrease = self.correlation.foreign_amount; Ok(investment_and_pending_decrease .ensure_add(self.pending_increase_swap(who, investment_id)?)? @@ -352,13 +377,14 @@ impl InvestmentInfo { &self, who: &T::AccountId, investment_id: T::InvestmentId, - ) -> Result { + ) -> Result { Ok(Swaps::::pending_amount_for( who, investment_id, Action::Investment, self.foreign_currency, - )) + ) + .into()) } /// In foreign currency denomination @@ -366,13 +392,14 @@ impl InvestmentInfo { &self, who: &T::AccountId, investment_id: T::InvestmentId, - ) -> Result { + ) -> Result { Ok(Swaps::::pending_amount_for( who, investment_id, Action::Investment, pool_currency_of::(investment_id)?, - )) + ) + .into()) } pub fn is_completed( @@ -392,17 +419,17 @@ pub struct RedemptionInfo { pub foreign_currency: T::CurrencyId, /// Total swapped amount pending to execute. - pub swapped_amount: T::Balance, + pub swapped_amount: T::ForeignBalance, /// Total collected amount pending to be sent. - pub collected: CollectedAmount, + pub collected: CollectedAmount, } impl RedemptionInfo { pub fn new(foreign_currency: T::CurrencyId) -> Self { Self { foreign_currency, - swapped_amount: T::Balance::default(), + swapped_amount: T::ForeignBalance::default(), collected: CollectedAmount::default(), } } @@ -420,7 +447,7 @@ impl RedemptionInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - tranche_tokens_amount: T::Balance, + tranche_tokens_amount: T::TrancheBalance, ) -> DispatchResult { T::Investment::update_redemption( who, @@ -433,7 +460,7 @@ impl RedemptionInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - tranche_tokens_amount: T::Balance, + tranche_tokens_amount: T::TrancheBalance, ) -> DispatchResult { T::Investment::update_redemption( who, @@ -446,14 +473,14 @@ impl RedemptionInfo { pub fn post_collect_and_pre_swap( &mut self, investment_id: T::InvestmentId, - collected: CollectedAmount, + collected: CollectedAmount, ) -> Result, DispatchError> { self.collected.increase(&collected)?; Ok(Swap { currency_in: self.foreign_currency, currency_out: pool_currency_of::(investment_id)?, - amount_out: collected.amount_collected, + amount_out: collected.amount_collected.into(), }) } @@ -463,9 +490,19 @@ impl RedemptionInfo { &mut self, who: &T::AccountId, investment_id: T::InvestmentId, - swapped_amount: T::Balance, - pending_amount: T::Balance, - ) -> Result>, DispatchError> { + swapped_amount: T::ForeignBalance, + pending_amount: T::PoolBalance, + ) -> Result< + Option< + ExecutedForeignCollect< + T::ForeignBalance, + T::TrancheBalance, + T::TrancheBalance, + T::CurrencyId, + >, + >, + DispatchError, + > { self.swapped_amount.ensure_add_assign(swapped_amount)?; if pending_amount.is_zero() { @@ -477,7 +514,7 @@ impl RedemptionInfo { }; self.collected = CollectedAmount::default(); - self.swapped_amount = T::Balance::default(); + self.swapped_amount = T::ForeignBalance::zero(); return Ok(Some(msg)); } @@ -485,7 +522,7 @@ impl RedemptionInfo { Ok(None) } - fn collected_tranche_tokens(&self) -> T::Balance { + fn collected_tranche_tokens(&self) -> T::TrancheBalance { self.collected.amount_payment } diff --git a/pallets/foreign-investments/src/impls.rs b/pallets/foreign-investments/src/impls.rs index 4f31701d32..ca000d8cbb 100644 --- a/pallets/foreign-investments/src/impls.rs +++ b/pallets/foreign-investments/src/impls.rs @@ -18,15 +18,16 @@ use crate::{ }; impl ForeignInvestment for Pallet { - type Amount = T::Balance; + type Amount = T::ForeignBalance; type CurrencyId = T::CurrencyId; type Error = DispatchError; type InvestmentId = T::InvestmentId; + type TrancheAmount = T::TrancheBalance; fn increase_foreign_investment( who: &T::AccountId, investment_id: T::InvestmentId, - foreign_amount: T::Balance, + foreign_amount: T::ForeignBalance, foreign_currency: T::CurrencyId, ) -> DispatchResult { let msg = ForeignInvestmentInfo::::mutate(who, investment_id, |entry| { @@ -38,19 +39,19 @@ impl ForeignInvestment for Pallet { let mut msg = None; if !status.swapped.is_zero() { - let swapped_foreign_amount = foreign_amount.ensure_sub(status.pending)?; + let swapped_foreign_amount = foreign_amount.ensure_sub(status.pending.into())?; if !swap.has_same_currencies() { msg = info.post_increase_swap_by_cancel( who, investment_id, - status.swapped, + status.swapped.into(), swapped_foreign_amount, )?; } else { info.post_increase_swap( who, investment_id, - status.swapped, + status.swapped.into(), swapped_foreign_amount, )?; } @@ -72,7 +73,7 @@ impl ForeignInvestment for Pallet { fn decrease_foreign_investment( who: &T::AccountId, investment_id: T::InvestmentId, - foreign_amount: T::Balance, + foreign_amount: T::ForeignBalance, foreign_currency: T::CurrencyId, ) -> DispatchResult { let msg = ForeignInvestmentInfo::::mutate(who, investment_id, |entry| { @@ -88,16 +89,16 @@ impl ForeignInvestment for Pallet { msg = info.post_decrease_swap_by_cancel( who, investment_id, - status.swapped, - status.pending, + status.swapped.into(), + status.pending.into(), )?; } else { msg = info.post_decrease_swap( who, investment_id, - status.swapped, - status.swapped, - status.pending, + status.swapped.into(), + status.swapped.into(), + status.pending.into(), )?; } } @@ -122,7 +123,7 @@ impl ForeignInvestment for Pallet { fn increase_foreign_redemption( who: &T::AccountId, investment_id: T::InvestmentId, - tranche_tokens_amount: T::Balance, + tranche_tokens_amount: T::TrancheBalance, payout_foreign_currency: T::CurrencyId, ) -> DispatchResult { ForeignRedemptionInfo::::mutate(who, investment_id, |info| -> DispatchResult { @@ -135,7 +136,7 @@ impl ForeignInvestment for Pallet { fn decrease_foreign_redemption( who: &T::AccountId, investment_id: T::InvestmentId, - tranche_tokens_amount: T::Balance, + tranche_tokens_amount: T::TrancheBalance, payout_foreign_currency: T::CurrencyId, ) -> DispatchResult { ForeignRedemptionInfo::::mutate_exists(who, investment_id, |entry| { @@ -180,7 +181,7 @@ impl ForeignInvestment for Pallet { fn investment( who: &T::AccountId, investment_id: T::InvestmentId, - ) -> Result { + ) -> Result { Ok(match ForeignInvestmentInfo::::get(who, investment_id) { Some(info) => { let pool_investment = T::Investment::investment(who, investment_id)?; @@ -191,14 +192,14 @@ impl ForeignInvestment for Pallet { foreing_investment.ensure_add(info.pending_increase_swap(who, investment_id)?)? } - None => T::Balance::default(), + None => T::ForeignBalance::default(), }) } fn redemption( who: &T::AccountId, investment_id: T::InvestmentId, - ) -> Result { + ) -> Result { T::Investment::redemption(who, investment_id) } @@ -246,22 +247,22 @@ impl StatusNotificationHook for FulfilledSwapOrderHook { true => SwapDone::::for_increase_investment( &who, investment_id, - swapped_amount_in, - swapped_amount_out, + swapped_amount_in.into(), + swapped_amount_out.into(), ), false => SwapDone::::for_decrease_investment( &who, investment_id, - swapped_amount_in, - swapped_amount_out, - pending_amount, + swapped_amount_in.into(), + swapped_amount_out.into(), + pending_amount.into(), ), }, Action::Redemption => SwapDone::::for_redemption( &who, investment_id, - swapped_amount_in, - pending_amount, + swapped_amount_in.into(), + pending_amount.into(), ), } } @@ -274,11 +275,11 @@ pub struct CollectedInvestmentHook(PhantomData); impl StatusNotificationHook for CollectedInvestmentHook { type Error = DispatchError; type Id = (T::AccountId, T::InvestmentId); - type Status = CollectedAmount; + type Status = CollectedAmount; fn notify_status_change( (who, investment_id): (T::AccountId, T::InvestmentId), - collected: CollectedAmount, + collected: CollectedAmount, ) -> DispatchResult { let msg = ForeignInvestmentInfo::::mutate_exists(&who, investment_id, |entry| { match entry.as_mut() { @@ -311,11 +312,11 @@ pub struct CollectedRedemptionHook(PhantomData); impl StatusNotificationHook for CollectedRedemptionHook { type Error = DispatchError; type Id = (T::AccountId, T::InvestmentId); - type Status = CollectedAmount; + type Status = CollectedAmount; fn notify_status_change( (who, investment_id): (T::AccountId, T::InvestmentId), - collected: CollectedAmount, + collected: CollectedAmount, ) -> DispatchResult { let swap = ForeignRedemptionInfo::::mutate(&who, investment_id, |entry| { match entry.as_mut() { @@ -330,7 +331,12 @@ impl StatusNotificationHook for CollectedRedemptionHook { let status = Swaps::::apply(&who, investment_id, Action::Redemption, swap)?; if !status.swapped.is_zero() { - SwapDone::::for_redemption(&who, investment_id, status.swapped, status.pending)?; + SwapDone::::for_redemption( + &who, + investment_id, + status.swapped.into(), + status.pending.into(), + )?; } } @@ -346,8 +352,8 @@ impl SwapDone { fn for_increase_investment( who: &T::AccountId, investment_id: T::InvestmentId, - swapped_pool_amount: T::Balance, - swapped_foreign_amount: T::Balance, + swapped_pool_amount: T::PoolBalance, + swapped_foreign_amount: T::ForeignBalance, ) -> DispatchResult { ForeignInvestmentInfo::::mutate_exists(who, investment_id, |entry| { let info = entry.as_mut().ok_or(Error::::InfoNotFound)?; @@ -365,9 +371,9 @@ impl SwapDone { fn for_decrease_investment( who: &T::AccountId, investment_id: T::InvestmentId, - swapped_foreign_amount: T::Balance, - swapped_pool_amount: T::Balance, - pending_pool_amount: T::Balance, + swapped_foreign_amount: T::ForeignBalance, + swapped_pool_amount: T::PoolBalance, + pending_pool_amount: T::PoolBalance, ) -> DispatchResult { let msg = ForeignInvestmentInfo::::mutate_exists(who, investment_id, |entry| { let info = entry.as_mut().ok_or(Error::::InfoNotFound)?; @@ -402,8 +408,8 @@ impl SwapDone { fn for_redemption( who: &T::AccountId, investment_id: T::InvestmentId, - swapped_amount: T::Balance, - pending_amount: T::Balance, + swapped_amount: T::ForeignBalance, + pending_amount: T::PoolBalance, ) -> DispatchResult { let msg = ForeignRedemptionInfo::::mutate_exists(who, investment_id, |entry| { let info = entry.as_mut().ok_or(Error::::InfoNotFound)?; diff --git a/pallets/foreign-investments/src/lib.rs b/pallets/foreign-investments/src/lib.rs index 86a4e64001..3f21eea530 100644 --- a/pallets/foreign-investments/src/lib.rs +++ b/pallets/foreign-investments/src/lib.rs @@ -23,17 +23,11 @@ //! //! - The implementer of the pallet's associated `Investment` type sends //! notifications for collected investments via `CollectedInvestmentHook` and -//! for collected redemptions via `CollectedRedemptionHook`]. Otherwise the -//! payment and collected amounts for foreign investments/redemptions are -//! never incremented. +//! for collected redemptions via `CollectedRedemptionHook`]. //! - The implementer of the pallet's associated `TokenSwaps` type sends //! notifications for fulfilled swap orders via the `FulfilledSwapOrderHook`. -//! Otherwise investment/redemption states can never advance the -//! `ActiveSwapInto*Currency` state. //! - The implementer of the pallet's associated `TokenSwaps` type sends //! notifications for fulfilled swap orders via the `FulfilledSwapOrderHook`. -//! Otherwise investment/redemption states can never advance the -//! `ActiveSwapInto*Currency` state. //! - The implementer of the pallet's associated //! `DecreasedForeignInvestOrderHook` type handles the refund of the decreased //! amount to the investor. @@ -76,10 +70,11 @@ pub type ForeignId = ( ); /// Swap alias -pub type SwapOf = Swap<::Balance, ::CurrencyId>; +pub type SwapOf = Swap<::SwapBalance, ::CurrencyId>; /// Swap state alias -pub type SwapStateOf = SwapState<::Balance, ::CurrencyId>; +pub type SwapStateOf = + SwapState<::SwapBalance, ::SwapBalance, ::CurrencyId>; /// TrancheId Identification pub type TrancheIdOf = <::PoolInspect as cfg_traits::PoolInspect< @@ -121,8 +116,34 @@ pub mod pallet { /// depends. #[pallet::config] pub trait Config: frame_system::Config { - /// The source of truth for the balance of accounts - type Balance: Parameter + /// Represents a foreign amount + type ForeignBalance: Parameter + + Member + + AtLeast32BitUnsigned + + FixedPointOperand + + Default + + Copy + + MaybeSerializeDeserialize + + MaxEncodedLen + + Into + + From + + Into; + + /// Represents a pool amount + type PoolBalance: Parameter + + Member + + AtLeast32BitUnsigned + + FixedPointOperand + + Default + + Copy + + MaybeSerializeDeserialize + + MaxEncodedLen + + Into + + From + + Into; + + /// Represents a tranche token amount + type TrancheBalance: Parameter + Member + AtLeast32BitUnsigned + FixedPointOperand @@ -131,13 +152,13 @@ pub mod pallet { + MaybeSerializeDeserialize + MaxEncodedLen; - /// Type for price ratio for cost of incoming currency relative to - /// outgoing - type BalanceRatio: Parameter + /// Any balances used in TokenSwaps + type SwapBalance: Parameter + Member - + sp_runtime::FixedPointNumber - + sp_runtime::traits::EnsureMul - + sp_runtime::traits::EnsureDiv + + AtLeast32BitUnsigned + + FixedPointOperand + + Default + + Copy + MaybeSerializeDeserialize + MaxEncodedLen; @@ -157,7 +178,8 @@ pub mod pallet { /// top of the wrapper implementation of this Pallet type Investment: Investment< Self::AccountId, - Amount = Self::Balance, + Amount = Self::PoolBalance, + TrancheAmount = Self::TrancheBalance, CurrencyId = Self::CurrencyId, Error = DispatchError, InvestmentId = Self::InvestmentId, @@ -173,30 +195,40 @@ pub mod pallet { type TokenSwaps: TokenSwaps< Self::AccountId, CurrencyId = Self::CurrencyId, - Balance = Self::Balance, + BalanceIn = Self::SwapBalance, + BalanceOut = Self::SwapBalance, OrderId = Self::SwapId, OrderDetails = SwapOf, - Ratio = Self::BalanceRatio, >; /// The hook type which acts upon a finalized investment decrement. type DecreasedForeignInvestOrderHook: StatusNotificationHook< Id = (Self::AccountId, Self::InvestmentId), - Status = ExecutedForeignDecreaseInvest, + Status = ExecutedForeignDecreaseInvest, Error = DispatchError, >; /// The hook type which acts upon a finalized redemption collection. type CollectedForeignRedemptionHook: StatusNotificationHook< Id = (Self::AccountId, Self::InvestmentId), - Status = ExecutedForeignCollect, + Status = ExecutedForeignCollect< + Self::ForeignBalance, + Self::TrancheBalance, + Self::TrancheBalance, + Self::CurrencyId, + >, Error = DispatchError, >; /// The hook type which acts upon a finalized redemption collection. type CollectedForeignInvestmentHook: StatusNotificationHook< Id = (Self::AccountId, Self::InvestmentId), - Status = ExecutedForeignCollect, + Status = ExecutedForeignCollect< + Self::ForeignBalance, + Self::TrancheBalance, + Self::ForeignBalance, + Self::CurrencyId, + >, Error = DispatchError, >; diff --git a/pallets/foreign-investments/src/mock.rs b/pallets/foreign-investments/src/mock.rs index b72e7d7d56..8e3e44e01c 100644 --- a/pallets/foreign-investments/src/mock.rs +++ b/pallets/foreign-investments/src/mock.rs @@ -92,10 +92,12 @@ impl pallet_mock_investment::Config for Runtime { type Amount = Balance; type CurrencyId = CurrencyId; type InvestmentId = InvestmentId; + type TrancheAmount = Balance; } impl pallet_mock_token_swaps::Config for Runtime { - type Balance = Balance; + type BalanceIn = Balance; + type BalanceOut = Balance; type CurrencyId = CurrencyId; type OrderDetails = Swap; type OrderId = SwapId; @@ -111,13 +113,13 @@ impl pallet_mock_status_notification::Config for Runtime { type Hook2 = pallet_mock_status_notification::Instance2; impl pallet_mock_status_notification::Config for Runtime { type Id = (AccountId, InvestmentId); - type Status = ExecutedForeignCollect; + type Status = ExecutedForeignCollect; } type Hook3 = pallet_mock_status_notification::Instance3; impl pallet_mock_status_notification::Config for Runtime { type Id = (AccountId, InvestmentId); - type Status = ExecutedForeignCollect; + type Status = ExecutedForeignCollect; } impl pallet_mock_pools::Config for Runtime { @@ -130,17 +132,19 @@ impl pallet_mock_pools::Config for Runtime { } impl pallet_foreign_investments::Config for Runtime { - type Balance = Balance; - type BalanceRatio = Ratio; type CollectedForeignInvestmentHook = MockCollectInvestHook; type CollectedForeignRedemptionHook = MockCollectRedeemHook; type CurrencyId = CurrencyId; type DecreasedForeignInvestOrderHook = MockDecreaseInvestHook; + type ForeignBalance = Balance; type Investment = MockInvestment; type InvestmentId = InvestmentId; + type PoolBalance = Balance; type PoolInspect = MockPools; + type SwapBalance = Balance; type SwapId = SwapId; type TokenSwaps = MockTokenSwaps; + type TrancheBalance = Balance; } pub fn new_test_ext() -> sp_io::TestExternalities { diff --git a/pallets/foreign-investments/src/swaps.rs b/pallets/foreign-investments/src/swaps.rs index 2c3f365487..528fece6ac 100644 --- a/pallets/foreign-investments/src/swaps.rs +++ b/pallets/foreign-investments/src/swaps.rs @@ -16,10 +16,10 @@ use crate::{ #[derive(RuntimeDebugNoBound, PartialEq)] pub struct SwapStatus { /// The incoming amount already swapped and available to use. - pub swapped: T::Balance, + pub swapped: T::SwapBalance, /// The outgoing amount pending to be swapped - pub pending: T::Balance, + pub pending: T::SwapBalance, /// The swap id for a possible reminder swap order after `apply_swap()` pub swap_id: Option, @@ -76,7 +76,7 @@ impl Swaps { investment_id: T::InvestmentId, action: Action, currency_out: T::CurrencyId, - ) -> T::Balance { + ) -> T::SwapBalance { ForeignIdToSwapId::::get((who, investment_id, action)) .and_then(T::TokenSwaps::get_order_details) .filter(|swap| swap.currency_out == currency_out) @@ -96,7 +96,7 @@ impl Swaps { if new_swap.currency_in == new_swap.currency_out { return Ok(SwapStatus { swapped: new_swap.amount_out, - pending: T::Balance::zero(), + pending: T::SwapBalance::zero(), swap_id: None, }); } @@ -135,7 +135,7 @@ impl Swaps { )?; Ok(SwapStatus { - swapped: T::Balance::zero(), + swapped: T::SwapBalance::zero(), pending: new_swap.amount_out, swap_id: Some(swap_id), }) @@ -149,7 +149,7 @@ impl Swaps { T::TokenSwaps::update_order(swap_id, amount_to_swap, OrderRatio::Market)?; Ok(SwapStatus { - swapped: T::Balance::zero(), + swapped: T::SwapBalance::zero(), pending: amount_to_swap, swap_id: Some(swap_id), }) @@ -175,7 +175,7 @@ impl Swaps { Ok(SwapStatus { swapped: new_swap_amount_in, - pending: T::Balance::zero(), + pending: T::SwapBalance::zero(), swap_id: Some(swap_id), }) } @@ -184,7 +184,7 @@ impl Swaps { Ok(SwapStatus { swapped: new_swap_amount_in, - pending: T::Balance::zero(), + pending: T::SwapBalance::zero(), swap_id: None, }) } diff --git a/pallets/investments/src/lib.rs b/pallets/investments/src/lib.rs index 3241018e4c..fb84dbc51e 100644 --- a/pallets/investments/src/lib.rs +++ b/pallets/investments/src/lib.rs @@ -172,7 +172,7 @@ pub mod pallet { type CollectedInvestmentHook: StatusNotificationHook< Error = DispatchError, Id = (Self::AccountId, Self::InvestmentId), - Status = CollectedAmount, + Status = CollectedAmount, >; /// The hook which acts upon a (partially) fulfilled order @@ -181,7 +181,7 @@ pub mod pallet { type CollectedRedemptionHook: StatusNotificationHook< Error = DispatchError, Id = (Self::AccountId, Self::InvestmentId), - Status = CollectedAmount, + Status = CollectedAmount, >; /// The weight information for this pallet extrinsics. @@ -629,7 +629,7 @@ impl Pallet { &who, investment_id, |maybe_order| -> Result< - (CollectedAmount, PostDispatchInfo), + (CollectedAmount, PostDispatchInfo), DispatchErrorWithPostInfo, > { // Exit early if order does not exist @@ -749,7 +749,7 @@ impl Pallet { &who, investment_id, |maybe_order| -> Result< - (CollectedAmount, PostDispatchInfo), + (CollectedAmount, PostDispatchInfo), DispatchErrorWithPostInfo, > { // Exit early if order does not exist @@ -1087,6 +1087,7 @@ impl Investment for Pallet { type CurrencyId = CurrencyOf; type Error = DispatchError; type InvestmentId = T::InvestmentId; + type TrancheAmount = T::Amount; fn update_investment( who: &T::AccountId, @@ -1116,7 +1117,7 @@ impl Investment for Pallet { fn update_redemption( who: &T::AccountId, investment_id: Self::InvestmentId, - amount: Self::Amount, + amount: Self::TrancheAmount, ) -> Result<(), Self::Error> { Pallet::::do_update_redemption(who.clone(), investment_id, amount) } @@ -1133,7 +1134,7 @@ impl Investment for Pallet { fn redemption( who: &T::AccountId, investment_id: Self::InvestmentId, - ) -> Result { + ) -> Result { Ok(RedeemOrders::::get(who, investment_id) .map_or_else(Zero::zero, |order| order.amount())) } diff --git a/pallets/investments/src/mock.rs b/pallets/investments/src/mock.rs index 9bd865928e..206612635f 100644 --- a/pallets/investments/src/mock.rs +++ b/pallets/investments/src/mock.rs @@ -161,7 +161,7 @@ pub struct NoopCollectHook; impl cfg_traits::StatusNotificationHook for NoopCollectHook { type Error = sp_runtime::DispatchError; type Id = (MockAccountId, InvestmentId); - type Status = cfg_types::investments::CollectedAmount; + type Status = cfg_types::investments::CollectedAmount; fn notify_status_change(_id: Self::Id, _status: Self::Status) -> DispatchResult { Ok(()) diff --git a/pallets/liquidity-pools/src/hooks.rs b/pallets/liquidity-pools/src/hooks.rs index eb1c529b6e..fcf43a495c 100644 --- a/pallets/liquidity-pools/src/hooks.rs +++ b/pallets/liquidity-pools/src/hooks.rs @@ -83,12 +83,12 @@ where { type Error = DispatchError; type Id = (T::AccountId, T::TrancheCurrency); - type Status = ExecutedForeignCollect; + type Status = ExecutedForeignCollect; #[transactional] fn notify_status_change( (investor, investment_id): (T::AccountId, T::TrancheCurrency), - status: ExecutedForeignCollect, + status: ExecutedForeignCollect, ) -> DispatchResult { let currency = Pallet::::try_get_general_index(status.currency)?; let wrapped_token = Pallet::::try_get_wrapped_token(&status.currency)?; @@ -127,12 +127,12 @@ where { type Error = DispatchError; type Id = (T::AccountId, T::TrancheCurrency); - type Status = ExecutedForeignCollect; + type Status = ExecutedForeignCollect; #[transactional] fn notify_status_change( (investor, investment_id): (T::AccountId, T::TrancheCurrency), - status: ExecutedForeignCollect, + status: ExecutedForeignCollect, ) -> DispatchResult { let currency = Pallet::::try_get_general_index(status.currency)?; let wrapped_token = Pallet::::try_get_wrapped_token(&status.currency)?; diff --git a/pallets/liquidity-pools/src/lib.rs b/pallets/liquidity-pools/src/lib.rs index da9e45f102..f5ec048378 100644 --- a/pallets/liquidity-pools/src/lib.rs +++ b/pallets/liquidity-pools/src/lib.rs @@ -227,7 +227,8 @@ pub mod pallet { /// currencies. type ForeignInvestment: ForeignInvestment< Self::AccountId, - Amount = ::Balance, + Amount = Self::Balance, + TrancheAmount = Self::Balance, CurrencyId = CurrencyIdOf, Error = DispatchError, InvestmentId = ::TrancheCurrency, diff --git a/pallets/order-book/src/benchmarking.rs b/pallets/order-book/src/benchmarking.rs index 32376548c2..0ad31d92fb 100644 --- a/pallets/order-book/src/benchmarking.rs +++ b/pallets/order-book/src/benchmarking.rs @@ -49,7 +49,7 @@ where decimals: 6, name: "CURRENCY IN".as_bytes().to_vec(), symbol: "IN".as_bytes().to_vec(), - existential_deposit: T::Balance::zero(), + existential_deposit: Zero::zero(), location: None, additional: CustomMetadata::default(), }, @@ -62,7 +62,7 @@ where decimals: 3, name: "CURRENCY OUT".as_bytes().to_vec(), symbol: "OUT".as_bytes().to_vec(), - existential_deposit: T::Balance::zero(), + existential_deposit: Zero::zero(), location: None, additional: CustomMetadata::default(), }, @@ -82,8 +82,9 @@ where let account_out = account::("account_out", 0, 0); let account_in = account::("account_in", 0, 0); - T::Currency::mint_into(CURRENCY_OUT.into(), &account_out, Self::amount_out()).unwrap(); - T::Currency::mint_into(CURRENCY_IN.into(), &account_in, expected_amount_in).unwrap(); + T::Currency::mint_into(CURRENCY_OUT.into(), &account_out, Self::amount_out().into()) + .unwrap(); + T::Currency::mint_into(CURRENCY_IN.into(), &account_in, expected_amount_in.into()).unwrap(); (account_out, account_in) } @@ -93,7 +94,7 @@ where Self::setup_accounts() } - pub fn amount_out() -> T::Balance { + pub fn amount_out() -> T::BalanceOut { let min_fulfillment = T::DecimalConverter::to_asset_balance( T::MinFulfillmentAmountNative::get(), CURRENCY_OUT.into(), @@ -104,9 +105,9 @@ where .unwrap() .decimals as usize; - let zeros = checked_pow(T::Balance::from(10u32), decimals_out).unwrap(); + let zeros = checked_pow(T::BalanceOut::from(10u32), decimals_out).unwrap(); - min_fulfillment + T::Balance::from(5u32) * zeros + min_fulfillment + T::BalanceOut::from(5u32) * zeros } pub fn add_trading_pair() { diff --git a/pallets/order-book/src/lib.rs b/pallets/order-book/src/lib.rs index 36c46d6064..456df9f64d 100644 --- a/pallets/order-book/src/lib.rs +++ b/pallets/order-book/src/lib.rs @@ -69,6 +69,9 @@ pub mod pallet { /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + pub type BalanceOf = + <::Currency as AssetInspect<::AccountId>>::Balance; + #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(_); @@ -80,7 +83,7 @@ pub mod pallet { /// Asset registry for foreign currencies we can take orders for. type AssetRegistry: asset_registry::Inspect< AssetId = Self::CurrencyId, - Balance = Self::Balance, + Balance = BalanceOf, CustomMetadata = CustomMetadata, >; @@ -104,17 +107,30 @@ pub mod pallet { + MaybeSerializeDeserialize + MaxEncodedLen; - /// Balance type - type Balance: Member + /// Balance type for incomming values + type BalanceIn: Member + Parameter + FixedPointOperand + AtLeast32BitUnsigned + EnsureMul + EnsureDiv - + MaxEncodedLen; + + MaxEncodedLen + + Into> + + From>; + + /// Balance type for outcomming values + type BalanceOut: Member + + Parameter + + FixedPointOperand + + AtLeast32BitUnsigned + + EnsureMul + + EnsureDiv + + MaxEncodedLen + + Into> + + From>; /// Type for currency orders can be made for - type Currency: AssetInspect + type Currency: AssetInspect + InspectHold + MutateHold + Mutate; @@ -140,23 +156,22 @@ pub mod pallet { /// When applying to a swap order, it will be re-denominated into the /// target currency. #[pallet::constant] - type MinFulfillmentAmountNative: Get; + type MinFulfillmentAmountNative: Get; /// Type which provides a decimal conversion from native to another /// currency. /// /// NOTE: Required for `MinFulfillmentAmountNative`. type DecimalConverter: cfg_traits::ConversionToAssetBalance< - Self::Balance, + Self::BalanceOut, Self::CurrencyId, - Self::Balance, - Error = DispatchError, + Self::BalanceOut, >; /// The hook which acts upon a (partially) fulfilled order type FulfilledOrderHook: StatusNotificationHook< Id = Self::OrderIdNonce, - Status = SwapState, + Status = SwapState, Error = DispatchError, >; @@ -197,13 +212,13 @@ pub mod pallet { pub currency_out: T::CurrencyId, /// Amount in `currency_in` obtained by swaping `amount_out` - pub amount_in: T::Balance, + pub amount_in: T::BalanceIn, /// How many tokens of `currency_out` available to sell - pub amount_out: T::Balance, + pub amount_out: T::BalanceOut, /// Initial value of amount out, used for tracking amount fulfilled - pub amount_out_initial: T::Balance, + pub amount_out_initial: T::BalanceOut, /// Price given for this order, pub ratio: OrderRatio, @@ -254,7 +269,7 @@ pub mod pallet { T::CurrencyId, Twox64Concat, T::CurrencyId, - T::Balance, + T::BalanceOut, ResultQuery::InvalidTradingPair>, >; @@ -272,8 +287,8 @@ pub mod pallet { creator_account: T::AccountId, currency_in: T::CurrencyId, currency_out: T::CurrencyId, - amount_out: T::Balance, - min_fulfillment_amount_out: T::Balance, + amount_out: T::BalanceOut, + min_fulfillment_amount_out: T::BalanceOut, ratio: OrderRatio, }, /// Event emitted when an order is cancelled. @@ -285,9 +300,9 @@ pub mod pallet { OrderUpdated { order_id: T::OrderIdNonce, account: T::AccountId, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, - min_fulfillment_amount_out: T::Balance, + min_fulfillment_amount_out: T::BalanceOut, }, /// Event emitted when an order is fulfilled. /// Can be for either partial or total fulfillment. @@ -298,7 +313,7 @@ pub mod pallet { placing_account: T::AccountId, fulfilling_account: T::AccountId, partial_fulfillment: bool, - fulfillment_amount: T::Balance, + fulfillment_amount: T::BalanceOut, currency_in: T::CurrencyId, currency_out: T::CurrencyId, ratio: T::Ratio, @@ -307,7 +322,7 @@ pub mod pallet { TradingPairAdded { currency_in: T::CurrencyId, currency_out: T::CurrencyId, - min_order: T::Balance, + min_order: T::BalanceOut, }, /// Event emitted when a valid trading pair is removed. TradingPairRemoved { @@ -359,7 +374,7 @@ pub mod pallet { origin: OriginFor, currency_in: T::CurrencyId, currency_out: T::CurrencyId, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, ) -> DispatchResult { let account_id = ensure_signed(origin)?; @@ -383,7 +398,7 @@ pub mod pallet { pub fn update_order( origin: OriginFor, order_id: T::OrderIdNonce, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, ) -> DispatchResult { let account_id = ensure_signed(origin)?; @@ -426,7 +441,7 @@ pub mod pallet { pub fn fill_order( origin: OriginFor, order_id: T::OrderIdNonce, - amount_out: T::Balance, + amount_out: T::BalanceOut, ) -> DispatchResult { let account_id = ensure_signed(origin)?; let order = >::get(order_id)?; @@ -441,7 +456,7 @@ pub mod pallet { origin: OriginFor, currency_in: T::CurrencyId, currency_out: T::CurrencyId, - min_order: T::Balance, + min_order: T::BalanceOut, ) -> DispatchResult { T::AdminOrigin::ensure_origin(origin)?; @@ -503,10 +518,10 @@ pub mod pallet { account: T::AccountId, currency_in: T::CurrencyId, currency_out: T::CurrencyId, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, - min_amount_out: T::Balance, - min_fulfillment_amount_out: T::Balance, + min_amount_out: T::BalanceOut, + min_fulfillment_amount_out: T::BalanceOut, ) -> Result { let order_id = OrderIdNonceStore::::try_mutate(|n| { n.ensure_add_assign(One::one())?; @@ -517,7 +532,7 @@ pub mod pallet { ensure!(currency_in != currency_out, Error::::SameCurrencyIds); - T::Currency::hold(currency_out, &(), &account, amount_out)?; + T::Currency::hold(currency_out, &(), &account, amount_out.into())?; let new_order = Order { order_id, @@ -548,10 +563,10 @@ pub mod pallet { fn inner_update_order( mut order: Order, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, - min_amount_out: T::Balance, - min_fulfillment_amount_out: T::Balance, + min_amount_out: T::BalanceOut, + min_fulfillment_amount_out: T::BalanceOut, ) -> DispatchResult { Self::validate_amount(amount_out, min_fulfillment_amount_out, min_amount_out)?; @@ -563,7 +578,7 @@ pub mod pallet { order.currency_out, &(), &order.placing_account, - amount_diff, + amount_diff.into(), )?; } Ordering::Less => { @@ -574,7 +589,7 @@ pub mod pallet { order.currency_out, &(), &order.placing_account, - amount_diff, + amount_diff.into(), Precision::Exact, )?; } @@ -609,7 +624,7 @@ pub mod pallet { fn fulfill_order_with_amount( order: Order, - amount_out: T::Balance, + amount_out: T::BalanceOut, fulfilling_account: T::AccountId, ) -> DispatchResult { let min_fulfillment_amount_out = min( @@ -650,15 +665,16 @@ pub mod pallet { order.currency_out, &(), &order.placing_account, - amount_out, + amount_out.into(), Precision::Exact, )?; - if T::Currency::balance(order.currency_out, &order.placing_account) < amount_out { + if T::Currency::balance(order.currency_out, &order.placing_account) < amount_out.into() + { Err(DispatchError::Token(TokenError::FundsUnavailable))? } - if T::Currency::balance(order.currency_in, &fulfilling_account) < amount_in { + if T::Currency::balance(order.currency_in, &fulfilling_account) < amount_in.into() { Err(DispatchError::Token(TokenError::FundsUnavailable))? } @@ -666,14 +682,14 @@ pub mod pallet { order.currency_out, &order.placing_account, &fulfilling_account, - amount_out, + amount_out.into(), Preservation::Expendable, )?; T::Currency::transfer( order.currency_in, &fulfilling_account, &order.placing_account, - amount_in, + amount_in.into(), Preservation::Expendable, )?; @@ -720,8 +736,8 @@ pub mod pallet { currency_from: T::CurrencyId, currency_to: T::CurrencyId, ratio: T::Ratio, - amount_from: T::Balance, - ) -> Result { + amount_from: T::BalanceOut, + ) -> Result { let from_decimals = T::AssetRegistry::metadata(¤cy_from) .ok_or(Error::::InvalidCurrencyId)? .decimals; @@ -730,17 +746,14 @@ pub mod pallet { .ok_or(Error::::InvalidCurrencyId)? .decimals; - Ok(convert_balance_decimals( - from_decimals, - to_decimals, - ratio.ensure_mul_int(amount_from)?, - )?) + let amount_in = ratio.ensure_mul_int(amount_from)?; + Ok(convert_balance_decimals(from_decimals, to_decimals, amount_in.into())?.into()) } fn validate_amount( - amount_out: T::Balance, - min_fulfillment_amount_out: T::Balance, - min_order_amount: T::Balance, + amount_out: T::BalanceOut, + min_fulfillment_amount_out: T::BalanceOut, + min_order_amount: T::BalanceOut, ) -> DispatchResult { ensure!( amount_out >= min_fulfillment_amount_out, @@ -757,15 +770,16 @@ pub mod pallet { pub fn min_fulfillment_amount( currency: T::CurrencyId, - ) -> Result { + ) -> Result { T::DecimalConverter::to_asset_balance(T::MinFulfillmentAmountNative::get(), currency) } } impl TokenSwaps for Pallet { - type Balance = T::Balance; + type BalanceIn = T::BalanceIn; + type BalanceOut = T::BalanceOut; type CurrencyId = T::CurrencyId; - type OrderDetails = Swap; + type OrderDetails = Swap; type OrderId = T::OrderIdNonce; type Ratio = T::Ratio; @@ -773,7 +787,7 @@ pub mod pallet { account: T::AccountId, currency_in: T::CurrencyId, currency_out: T::CurrencyId, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, ) -> Result { Self::inner_place_order( @@ -782,8 +796,8 @@ pub mod pallet { currency_out, amount_out, ratio, - T::Balance::zero(), - T::Balance::zero(), + T::BalanceOut::zero(), + T::BalanceOut::zero(), ) } @@ -795,7 +809,7 @@ pub mod pallet { order.currency_out, &(), &order.placing_account, - order.amount_out, + order.amount_out.into(), Precision::Exact, )?; @@ -810,7 +824,7 @@ pub mod pallet { fn update_order( order_id: Self::OrderId, - amount_out: T::Balance, + amount_out: T::BalanceOut, ratio: OrderRatio, ) -> DispatchResult { let order = Orders::::get(order_id)?; @@ -819,12 +833,12 @@ pub mod pallet { order, amount_out, ratio, - T::Balance::zero(), - T::Balance::zero(), + T::BalanceOut::zero(), + T::BalanceOut::zero(), ) } - fn get_order_details(order: Self::OrderId) -> Option> { + fn get_order_details(order: Self::OrderId) -> Option> { Orders::::get(order) .map(|order| Swap { amount_out: order.amount_out, @@ -841,10 +855,11 @@ pub mod pallet { fn convert_by_market( currency_in: Self::CurrencyId, currency_out: Self::CurrencyId, - amount_out: Self::Balance, - ) -> Result { + amount_out: T::BalanceOut, + ) -> Result { if currency_in == currency_out { - return Ok(amount_out); + let amount: BalanceOf = amount_out.into(); + return Ok(amount.into()); } let ratio = Self::market_ratio(currency_out, currency_in)?; diff --git a/pallets/order-book/src/mock.rs b/pallets/order-book/src/mock.rs index 9261fa5f4e..c7b7bb6e3f 100644 --- a/pallets/order-book/src/mock.rs +++ b/pallets/order-book/src/mock.rs @@ -129,7 +129,7 @@ impl cfg_mocks::fees::pallet::Config for Runtime { impl cfg_mocks::status_notification::pallet::Config for Runtime { type Id = OrderId; - type Status = SwapState; + type Status = SwapState; } parameter_types! { @@ -207,8 +207,6 @@ parameter_types! { pub struct DecimalConverter; impl ConversionToAssetBalance for DecimalConverter { - type Error = DispatchError; - fn to_asset_balance( balance: Balance, currency_in: CurrencyId, @@ -224,7 +222,8 @@ impl ConversionToAssetBalance for DecimalConverter impl order_book::Config for Runtime { type AdminOrigin = EnsureRoot; type AssetRegistry = RegistryMock; - type Balance = Balance; + type BalanceIn = Balance; + type BalanceOut = Balance; type Currency = Tokens; type CurrencyId = CurrencyId; type DecimalConverter = DecimalConverter; diff --git a/pallets/pool-registry/src/mock.rs b/pallets/pool-registry/src/mock.rs index b37e8eccae..202758e281 100644 --- a/pallets/pool-registry/src/mock.rs +++ b/pallets/pool-registry/src/mock.rs @@ -346,7 +346,7 @@ pub struct NoopCollectHook; impl cfg_traits::StatusNotificationHook for NoopCollectHook { type Error = DispatchError; type Id = (AccountId, TrancheCurrency); - type Status = cfg_types::investments::CollectedAmount; + type Status = cfg_types::investments::CollectedAmount; fn notify_status_change(_id: Self::Id, _status: Self::Status) -> DispatchResult { Ok(()) diff --git a/pallets/pool-system/src/mock.rs b/pallets/pool-system/src/mock.rs index 4c590315a8..a86decc88a 100644 --- a/pallets/pool-system/src/mock.rs +++ b/pallets/pool-system/src/mock.rs @@ -337,7 +337,7 @@ pub struct NoopCollectHook; impl cfg_traits::StatusNotificationHook for NoopCollectHook { type Error = sp_runtime::DispatchError; type Id = (MockAccountId, TrancheCurrency); - type Status = cfg_types::investments::CollectedAmount; + type Status = cfg_types::investments::CollectedAmount; fn notify_status_change(_id: Self::Id, _status: Self::Status) -> DispatchResult { Ok(()) diff --git a/runtime/altair/src/lib.rs b/runtime/altair/src/lib.rs index 71f0b04b0e..7286344341 100644 --- a/runtime/altair/src/lib.rs +++ b/runtime/altair/src/lib.rs @@ -1726,7 +1726,8 @@ parameter_types! { impl pallet_order_book::Config for Runtime { type AdminOrigin = EnsureRoot; type AssetRegistry = OrmlAssetRegistry; - type Balance = Balance; + type BalanceIn = Balance; + type BalanceOut = Balance; type Currency = Tokens; type CurrencyId = CurrencyId; type DecimalConverter = diff --git a/runtime/altair/src/liquidity_pools.rs b/runtime/altair/src/liquidity_pools.rs index f0f4b48609..46deac4b38 100644 --- a/runtime/altair/src/liquidity_pools.rs +++ b/runtime/altair/src/liquidity_pools.rs @@ -35,17 +35,19 @@ use crate::{ }; impl pallet_foreign_investments::Config for Runtime { - type Balance = Balance; - type BalanceRatio = Ratio; type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; type CurrencyId = CurrencyId; type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; type Investment = Investments; type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; type PoolInspect = PoolSystem; + type SwapBalance = Balance; type SwapId = u64; type TokenSwaps = OrderBook; + type TrancheBalance = Balance; } parameter_types! { diff --git a/runtime/centrifuge/src/lib.rs b/runtime/centrifuge/src/lib.rs index 11bda597e4..8af43c3284 100644 --- a/runtime/centrifuge/src/lib.rs +++ b/runtime/centrifuge/src/lib.rs @@ -1817,7 +1817,8 @@ parameter_types! { impl pallet_order_book::Config for Runtime { type AdminOrigin = EnsureRoot; type AssetRegistry = OrmlAssetRegistry; - type Balance = Balance; + type BalanceIn = Balance; + type BalanceOut = Balance; type Currency = Tokens; type CurrencyId = CurrencyId; type DecimalConverter = diff --git a/runtime/centrifuge/src/liquidity_pools.rs b/runtime/centrifuge/src/liquidity_pools.rs index a73e7eb6e2..26c081947a 100644 --- a/runtime/centrifuge/src/liquidity_pools.rs +++ b/runtime/centrifuge/src/liquidity_pools.rs @@ -36,17 +36,19 @@ use crate::{ }; impl pallet_foreign_investments::Config for Runtime { - type Balance = Balance; - type BalanceRatio = Ratio; type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; type CurrencyId = CurrencyId; type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; type Investment = Investments; type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; type PoolInspect = PoolSystem; + type SwapBalance = Balance; type SwapId = u64; type TokenSwaps = OrderBook; + type TrancheBalance = Balance; } parameter_types! { diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 7715d1567c..4b4cbe5f7c 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -469,8 +469,6 @@ pub mod foreign_investments { CustomMetadata = cfg_types::tokens::CustomMetadata, >, { - type Error = DispatchError; - fn to_asset_balance( balance: Balance, currency_in: CurrencyId, diff --git a/runtime/development/src/lib.rs b/runtime/development/src/lib.rs index 727c535916..f9508f9173 100644 --- a/runtime/development/src/lib.rs +++ b/runtime/development/src/lib.rs @@ -1812,7 +1812,8 @@ parameter_types! { impl pallet_order_book::Config for Runtime { type AdminOrigin = EnsureRoot; type AssetRegistry = OrmlAssetRegistry; - type Balance = Balance; + type BalanceIn = Balance; + type BalanceOut = Balance; type Currency = Tokens; type CurrencyId = CurrencyId; type DecimalConverter = diff --git a/runtime/development/src/liquidity_pools.rs b/runtime/development/src/liquidity_pools.rs index 107061b2c8..ee650f21f5 100644 --- a/runtime/development/src/liquidity_pools.rs +++ b/runtime/development/src/liquidity_pools.rs @@ -36,17 +36,19 @@ use crate::{ }; impl pallet_foreign_investments::Config for Runtime { - type Balance = Balance; - type BalanceRatio = Ratio; type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; type CurrencyId = CurrencyId; type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; type Investment = Investments; type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; type PoolInspect = PoolSystem; + type SwapBalance = Balance; type SwapId = u64; type TokenSwaps = OrderBook; + type TrancheBalance = Balance; } parameter_types! { diff --git a/runtime/integration-tests/src/generic/config.rs b/runtime/integration-tests/src/generic/config.rs index 415b57edb8..5e9f08333d 100644 --- a/runtime/integration-tests/src/generic/config.rs +++ b/runtime/integration-tests/src/generic/config.rs @@ -130,13 +130,16 @@ pub trait Runtime: + pallet_ethereum::Config + pallet_ethereum_transaction::Config + pallet_order_book::Config< - Balance = Balance, + BalanceIn = Balance, + BalanceOut = Balance, CurrencyId = CurrencyId, OrderIdNonce = u64, Ratio = Ratio, FeederId = Feeder, > + pallet_foreign_investments::Config< - Balance = Balance, + ForeignBalance = Balance, + PoolBalance = Balance, + TrancheBalance = Balance, InvestmentId = TrancheCurrency, CurrencyId = CurrencyId, SwapId = u64, diff --git a/runtime/integration-tests/src/liquidity_pools/pallet/development/tests/liquidity_pools/setup.rs b/runtime/integration-tests/src/liquidity_pools/pallet/development/tests/liquidity_pools/setup.rs deleted file mode 100644 index 8b13789179..0000000000 --- a/runtime/integration-tests/src/liquidity_pools/pallet/development/tests/liquidity_pools/setup.rs +++ /dev/null @@ -1 +0,0 @@ -