Skip to content
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

Pools: use Rate represented as 18 decimals #1520

Merged
merged 12 commits into from
Sep 4, 2023
1 change: 0 additions & 1 deletion libs/mocks/src/pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ pub mod pallet {
impl<T: Config> PoolInspect<T::AccountId, T::CurrencyId> for Pallet<T> {
type Moment = Moment;
type PoolId = T::PoolId;
type Rate = T::Rate;
type TrancheId = T::TrancheId;

fn pool_exists(a: T::PoolId) -> bool {
Expand Down
1 change: 0 additions & 1 deletion libs/traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ pub trait PoolNAV<PoolId, Amount> {
pub trait PoolInspect<AccountId, CurrencyId> {
type PoolId;
type TrancheId;
type Rate;
type Moment;

/// check if the pool exists
Expand Down
3 changes: 3 additions & 0 deletions pallets/investments/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,11 @@ pub mod pallet {
type WeightInfo: weights::WeightInfo;
}

const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

#[pallet::pallet]
#[pallet::generate_store(pub (super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);

#[pallet::hooks]
Expand Down
1 change: 0 additions & 1 deletion pallets/liquidity-pools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ pub mod pallet {
type PoolInspect: PoolInspect<
Self::AccountId,
CurrencyIdOf<Self>,
Rate = Self::Rate,
PoolId = Self::PoolId,
TrancheId = Self::TrancheId,
>;
Expand Down
5 changes: 3 additions & 2 deletions pallets/pool-registry/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use cfg_mocks::pallet_mock_write_off_policy;
use cfg_primitives::{BlockNumber, CollectionId, Moment, PoolEpochId, TrancheWeight};
use cfg_traits::{OrderManager, PoolMutate, PoolUpdateGuard, PreConditions, UpdateState};
use cfg_types::{
fixed_point::Rate,
fixed_point::{Quantity, Rate},
permissions::{PermissionScope, Role},
tokens::{CurrencyId, CustomMetadata, TrancheCurrency},
};
Expand Down Expand Up @@ -138,6 +138,7 @@ impl cfg_test_utils::mocks::nav::Config for Test {
impl pallet_pool_system::Config for Test {
type AssetRegistry = RegistryMock;
type Balance = Balance;
type BalanceRatio = Quantity;
type ChallengeTime = ChallengeTime;
type Currency = Balances;
type CurrencyId = CurrencyId;
Expand Down Expand Up @@ -307,7 +308,7 @@ parameter_types! {
impl pallet_investments::Config for Test {
type Accountant = PoolSystem;
type Amount = Balance;
type BalanceRatio = Rate;
type BalanceRatio = Quantity;
type InvestmentId = TrancheCurrency;
type MaxOutstandingCollects = MaxOutstandingCollects;
type PreConditions = Always;
Expand Down
7 changes: 3 additions & 4 deletions pallets/pool-system/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ use crate::{
impl<T: Config> PoolInspect<T::AccountId, T::CurrencyId> for Pallet<T> {
type Moment = Moment;
type PoolId = T::PoolId;
type Rate = T::Rate;
type TrancheId = T::TrancheId;

fn pool_exists(pool_id: Self::PoolId) -> bool {
Expand All @@ -55,13 +54,13 @@ impl<T: Config> PoolInspect<T::AccountId, T::CurrencyId> for Pallet<T> {
impl<T: Config> TrancheTokenPrice<T::AccountId, T::CurrencyId> for Pallet<T> {
type Moment = Moment;
type PoolId = T::PoolId;
type Rate = T::Rate;
type Rate = T::BalanceRatio;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also rename taht

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

type TrancheId = T::TrancheId;

fn get(
pool_id: Self::PoolId,
tranche_id: Self::TrancheId,
) -> Option<PriceValue<T::CurrencyId, T::Rate, Moment>> {
) -> Option<PriceValue<T::CurrencyId, T::BalanceRatio, Moment>> {
let now = Self::now();
let mut pool = Pool::<T>::get(pool_id)?;

Expand All @@ -77,7 +76,7 @@ impl<T: Config> TrancheTokenPrice<T::AccountId, T::CurrencyId> for Pallet<T> {
.ok()?;
let prices = pool
.tranches
.calculate_prices::<T::Rate, T::Tokens, _>(total_assets, now)
.calculate_prices::<T::BalanceRatio, T::Tokens, _>(total_assets, now)
.ok()?;

let base = pool
Expand Down
28 changes: 18 additions & 10 deletions pallets/pool-system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ pub mod weights;
#[allow(dead_code)]
pub type EpochExecutionTrancheOf<T> = EpochExecutionTranche<
<T as Config>::Balance,
<T as Config>::Rate,
<T as Config>::BalanceRatio,
<T as Config>::TrancheWeight,
<T as Config>::TrancheCurrency,
>;
Expand All @@ -87,7 +87,7 @@ pub type EpochExecutionTrancheOf<T> = EpochExecutionTranche<
/// Type alias for EpochExecutionTranches
pub type EpochExecutionTranchesOf<T> = EpochExecutionTranches<
<T as Config>::Balance,
<T as Config>::Rate,
<T as Config>::BalanceRatio,
<T as Config>::TrancheWeight,
<T as Config>::TrancheCurrency,
<T as Config>::MaxTranches,
Expand Down Expand Up @@ -129,7 +129,7 @@ pub type PoolDetailsOf<T> = PoolDetails<
/// Type alias for `struct EpochExecutionInfo`
type EpochExecutionInfoOf<T> = EpochExecutionInfo<
<T as Config>::Balance,
<T as Config>::Rate,
<T as Config>::BalanceRatio,
<T as Config>::EpochId,
<T as Config>::TrancheWeight,
<T as frame_system::Config>::BlockNumber,
Expand Down Expand Up @@ -212,6 +212,15 @@ pub mod pallet {
+ Convert<Self::TrancheWeight, Self::Balance>
+ From<u128>;

/// A fixed-point number that represent a price with decimals
type BalanceRatio: Member
+ Parameter
+ Default
+ Copy
+ TypeInfo
+ FixedPointNumber<Inner = Self::Balance>
+ MaxEncodedLen;

/// A fixed-point number which represents a Self::Balance
/// in terms of this fixed-point representation.
type Rate: Member
Expand Down Expand Up @@ -301,7 +310,7 @@ pub mod pallet {
Error = DispatchError,
InvestmentId = Self::TrancheCurrency,
Orders = TotalOrder<Self::Balance>,
Fulfillment = FulfillmentWithPrice<Self::Rate>,
Fulfillment = FulfillmentWithPrice<Self::BalanceRatio>,
>;

type Time: UnixTime;
Expand Down Expand Up @@ -354,8 +363,11 @@ pub mod pallet {
type WeightInfo: WeightInfo;
}

const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);

#[pallet::storage]
Expand All @@ -381,10 +393,6 @@ pub mod pallet {
#[pallet::getter(fn pool_deposits)]
pub type PoolDeposit<T: Config> = StorageMap<_, Blake2_128Concat, T::PoolId, PoolDepositOf<T>>;

#[pallet::storage]
#[pallet::getter(fn storage_version)]
pub type StorageVersion<T: Config> = StorageValue<_, Release, ValueQuery>;

#[pallet::storage]
pub type NotedChange<T: Config> = StorageDoubleMap<
_,
Expand Down Expand Up @@ -604,7 +612,7 @@ pub mod pallet {

let epoch_tranche_prices = pool
.tranches
.calculate_prices::<T::Rate, T::Tokens, _>(total_assets, now)?;
.calculate_prices::<T::BalanceRatio, T::Tokens, _>(total_assets, now)?;

// If closing the epoch would wipe out a tranche, the close is invalid.
// TODO: This should instead put the pool into an error state
Expand Down Expand Up @@ -875,7 +883,7 @@ pub mod pallet {

fn summarize_orders(
tranches: &TranchesOf<T>,
prices: &[T::Rate],
prices: &[T::BalanceRatio],
) -> Result<SummarizedOrders<T::Balance>, DispatchError> {
let mut acc_invest_orders = T::Balance::zero();
let mut acc_redeem_orders = T::Balance::zero();
Expand Down
5 changes: 3 additions & 2 deletions pallets/pool-system/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use cfg_traits::{
OrderManager, Permissions as PermissionsT, PoolUpdateGuard, PreConditions,
TrancheCurrency as TrancheCurrencyT,
};
pub use cfg_types::fixed_point::Rate;
pub use cfg_types::fixed_point::{Quantity, Rate};
use cfg_types::{
permissions::{PermissionRoles, PermissionScope, PoolRole, Role, UNION},
time::TimeProvider,
Expand Down Expand Up @@ -256,7 +256,7 @@ parameter_types! {
impl pallet_investments::Config for Runtime {
type Accountant = PoolSystem;
type Amount = Balance;
type BalanceRatio = Rate;
type BalanceRatio = Quantity;
type InvestmentId = TrancheCurrency;
type MaxOutstandingCollects = MaxOutstandingCollects;
type PreConditions = Always;
Expand Down Expand Up @@ -307,6 +307,7 @@ parameter_types! {
impl Config for Runtime {
type AssetRegistry = RegistryMock;
type Balance = Balance;
type BalanceRatio = Quantity;
type ChallengeTime = ChallengeTime;
type Currency = Balances;
type CurrencyId = CurrencyId;
Expand Down
14 changes: 7 additions & 7 deletions pallets/pool-system/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ fn core_constraints_currency_available_cant_cover_redemptions() {
.zip(vec![80, 20, 5, 5]) // no IntoIterator for arrays, so we use a vec here. Meh.
.map(|(_tranche, value)| EpochExecutionTranche {
supply: value,
price: One::one(),
price: Quantity::one(),
redeem: 10,
..Default::default()
})
Expand Down Expand Up @@ -502,7 +502,7 @@ fn pool_constraints_pass() {
assert_ok!(PoolSystem::inspect_solution(pool, &epoch, &full_solution));

assert_eq!(
calculate_risk_buffers::<u128, Rate>(&vec![3, 1], &vec![One::one(), One::one()])
calculate_risk_buffers::<u128, Quantity>(&vec![3, 1], &vec![One::one(), One::one()])
.unwrap(),
vec![Perquintill::zero(), Perquintill::from_float(0.75),]
);
Expand Down Expand Up @@ -577,7 +577,7 @@ fn epoch() {
>>::get(0, SeniorTrancheId::get())
.unwrap()
.price,
Rate::one()
Quantity::one()
);

assert_err!(
Expand Down Expand Up @@ -725,14 +725,14 @@ fn epoch() {
0
);
assert_eq!(pool.reserve.available, pool.reserve.total);
assert_eq!(pool.reserve.total, 758968368969420653370);
assert_eq!(pool.reserve.total, 758968368969420653250);
assert_eq!(
pool.tranches.residual_top_slice()[SENIOR_TRANCHE_INDEX as usize].reserve,
251031631030579346631
251031631030579346511
);
assert_eq!(
pool.reserve.total + senior_price.saturating_mul_int(250 * CURRENCY),
1010 * CURRENCY + 1 // TODO: Fix rounding issue with FixedPointNumberExtension
1009999999999999999750 // TODO: Fix rounding issue with FixedPointNumberExtension
);
Comment on lines +728 to 736
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After separating the pool rate into 18 and 27 decimals, I found these tests magic values has changed. I do not know where they come from (probably from calculating prices in tranches), but I'm not able to answer why they change in that way.

It changes in the last decimals, so it probably is an accumulated rounding issue with some pow() or similar.


assert_eq!(
Expand All @@ -742,7 +742,7 @@ fn epoch() {
>>::get(0, SeniorTrancheId::get())
.unwrap()
.price,
Rate::from_inner(1004126524122317386524000000)
Quantity::from_inner(1004126524122317386)
);
});
}
Expand Down
17 changes: 10 additions & 7 deletions pallets/pool-system/src/tranches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use cfg_primitives::Moment;
use cfg_primitives::{Balance, PoolId, TrancheId, TrancheWeight};
use cfg_traits::TrancheCurrency as TrancheCurrencyT;
#[cfg(test)]
use cfg_types::{fixed_point::Rate, tokens::TrancheCurrency};
use cfg_types::{
fixed_point::{Quantity, Rate},
tokens::TrancheCurrency,
};
use cfg_types::{
pools::TrancheMetadata,
tokens::{CrossChainTransferability, CustomMetadata},
Expand Down Expand Up @@ -1048,12 +1051,12 @@ pub struct EpochExecutionTranche<Balance, BalanceRatio, Weight, TrancheCurrency>
}

#[cfg(test)]
impl Default for EpochExecutionTranche<Balance, Rate, TrancheWeight, TrancheCurrency> {
impl Default for EpochExecutionTranche<Balance, Quantity, TrancheWeight, TrancheCurrency> {
fn default() -> Self {
Self {
currency: TrancheCurrency::generate(0, [0u8; 16]),
supply: 0,
price: Rate::one(),
price: Quantity::one(),
invest: 0,
redeem: 0,
min_risk_buffer: Default::default(),
Expand Down Expand Up @@ -1524,14 +1527,14 @@ fn finalize_combine<R, T, W>(
pub mod test {
use cfg_primitives::{Balance, PoolId, TrancheId, TrancheWeight};
use cfg_types::{
fixed_point::{FixedPointNumberExtension, Rate},
fixed_point::{FixedPointNumberExtension, Quantity, Rate},
tokens::TrancheCurrency,
};

use super::*;
use crate::mock::MaxTranches;

type BalanceRatio = Rate;
type BalanceRatio = Quantity;
type TTrancheType = TrancheType<Rate>;
type TTranche = Tranche<Balance, Rate, TrancheWeight, TrancheCurrency>;
type TTranches =
Expand Down Expand Up @@ -3861,7 +3864,7 @@ pub mod test {
let tranches = default_epoch_tranches();

assert_eq!(
vec![Rate::one(), Rate::one(), Rate::one()],
vec![Quantity::one(), Quantity::one(), Quantity::one()],
tranches.prices()
)
}
Expand Down Expand Up @@ -4099,7 +4102,7 @@ pub mod test {
#[test]
fn epoch_execution_tranches_prices() {
let epoch_execution_tranches = default_epoch_tranches();
let r = Rate::one();
let r = Quantity::one();
assert_eq!(epoch_execution_tranches.prices(), vec![r, r, r])
}
}
Expand Down
7 changes: 4 additions & 3 deletions runtime/altair/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,7 @@ impl pallet_liquidity_pools::Config for Runtime {
type Permission = Permissions;
type PoolId = PoolId;
type PoolInspect = PoolSystem;
type Rate = Rate;
type Rate = Quantity;
type RuntimeEvent = RuntimeEvent;
type Time = Timestamp;
type Tokens = Tokens;
Expand All @@ -1417,7 +1417,7 @@ impl pallet_liquidity_pools_gateway::Config for Runtime {
type InboundQueue = LiquidityPools;
type LocalEVMOrigin = pallet_liquidity_pools_gateway::EnsureLocal;
type MaxIncomingMessageSize = MaxIncomingMessageSize;
type Message = pallet_liquidity_pools::Message<Domain, PoolId, TrancheId, Balance, Rate>;
type Message = pallet_liquidity_pools::Message<Domain, PoolId, TrancheId, Balance, Quantity>;
type Router = liquidity_pools_gateway_routers::DomainRouter<Runtime>;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
Expand Down Expand Up @@ -1509,6 +1509,7 @@ parameter_types! {
impl pallet_pool_system::Config for Runtime {
type AssetRegistry = OrmlAssetRegistry;
type Balance = Balance;
type BalanceRatio = Quantity;
type ChallengeTime = ChallengeTime;
type Currency = Balances;
type CurrencyId = CurrencyId;
Expand Down Expand Up @@ -1655,7 +1656,7 @@ parameter_types! {
impl pallet_investments::Config for Runtime {
type Accountant = PoolSystem;
type Amount = Balance;
type BalanceRatio = Rate;
type BalanceRatio = Quantity;
type InvestmentId = TrancheCurrency;
type MaxOutstandingCollects = MaxOutstandingCollects;
type PreConditions = IsTrancheInvestor<Permissions, Timestamp>;
Expand Down
4 changes: 4 additions & 0 deletions runtime/altair/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub type UpgradeAltair1030 = (
pool_system::MigrateAUSDPools,
runtime_common::migrations::nuke::Migration<crate::Loans, RocksDbWeight, 1>,
runtime_common::migrations::nuke::Migration<crate::InterestAccrual, RocksDbWeight, 0>,
runtime_common::migrations::nuke::Migration<crate::PoolSystem, RocksDbWeight, 0>,
runtime_common::migrations::nuke::Migration<crate::Investments, RocksDbWeight, 0>,
pallet_rewards::migrations::new_instance::FundExistentialDeposit<
crate::Runtime,
pallet_rewards::Instance2,
Expand All @@ -44,6 +46,8 @@ pub type UpgradeAltair1030 = (
pub type UpgradeAltair1030 = (
runtime_common::migrations::nuke::Migration<crate::Loans, RocksDbWeight, 1>,
runtime_common::migrations::nuke::Migration<crate::InterestAccrual, RocksDbWeight, 0>,
runtime_common::migrations::nuke::Migration<crate::PoolSystem, RocksDbWeight, 0>,
runtime_common::migrations::nuke::Migration<crate::Investments, RocksDbWeight, 0>,
pallet_rewards::migrations::new_instance::FundExistentialDeposit<
crate::Runtime,
pallet_rewards::Instance2,
Expand Down
3 changes: 2 additions & 1 deletion runtime/centrifuge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1437,6 +1437,7 @@ impl pallet_pool_registry::Config for Runtime {
impl pallet_pool_system::Config for Runtime {
type AssetRegistry = OrmlAssetRegistry;
type Balance = Balance;
type BalanceRatio = Quantity;
type ChallengeTime = ChallengeTime;
type Currency = Balances;
type CurrencyId = CurrencyId;
Expand Down Expand Up @@ -1597,7 +1598,7 @@ impl<
impl pallet_investments::Config for Runtime {
type Accountant = PoolSystem;
type Amount = Balance;
type BalanceRatio = Rate;
type BalanceRatio = Quantity;
type InvestmentId = TrancheCurrency;
type MaxOutstandingCollects = MaxOutstandingCollects;
type PreConditions = IsTrancheInvestor<Permissions, Timestamp>;
Expand Down