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

Loans: Moment as Seconds & Millis explicitly #1575

Merged
merged 14 commits into from
Oct 16, 2023
Prev Previous commit
Next Next commit
implementation for pool-system & tests
  • Loading branch information
lemunozm committed Oct 9, 2023
commit 59f756122dd83462af6a628bf8fa2cb795a53c1b
12 changes: 6 additions & 6 deletions pallets/pool-system/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl<T: Config> TrancheTokenPrice<T::AccountId, T::CurrencyId> for Pallet<T> {
pool_id: Self::PoolId,
tranche_id: Self::TrancheId,
) -> Option<PriceValue<T::CurrencyId, T::BalanceRatio, Moment>> {
let now = Self::now();
let now = T::Time::now();
let mut pool = Pool::<T>::get(pool_id)?;

// Get cached nav as calculating current nav would be too computationally
Expand Down Expand Up @@ -136,7 +136,7 @@ impl<T: Config> PoolMutate<T::AccountId, T::PoolId> for Pallet<T> {

Self::take_deposit(depositor.clone(), pool_id)?;

let now = Self::now();
let now = T::Time::now();

let tranches = Tranches::<
T::Balance,
Expand Down Expand Up @@ -264,7 +264,7 @@ impl<T: Config> PoolMutate<T::AccountId, T::PoolId> for Pallet<T> {
Self::is_valid_tranche_change(Some(&pool.tranches), tranches)?;
}

let now = Self::now();
let now = T::Time::now();

let update = ScheduledUpdateDetails {
changes: changes.clone(),
Expand Down Expand Up @@ -295,7 +295,7 @@ impl<T: Config> PoolMutate<T::AccountId, T::PoolId> for Pallet<T> {
let update =
ScheduledUpdate::<T>::try_get(pool_id).map_err(|_| Error::<T>::NoScheduledUpdate)?;

let now = Self::now();
let now = T::Time::now();
ensure!(
now >= update.submitted_at.ensure_add(T::MinUpdateDelay::get())?,
Error::<T>::ScheduledTimeHasNotPassed
Expand Down Expand Up @@ -392,7 +392,7 @@ impl<T: Config> ChangeGuard for Pallet<T> {

fn note(pool_id: Self::PoolId, change: Self::Change) -> Result<Self::ChangeId, DispatchError> {
let noted_change = NotedPoolChange {
submitted_time: Self::now(),
submitted_time: T::Time::now(),
change,
};

Expand Down Expand Up @@ -427,7 +427,7 @@ impl<T: Config> ChangeGuard for Pallet<T> {
allowed &= match requirement {
Requirement::NextEpoch => submitted_time < pool.epoch.last_closed,
Requirement::DelayTime(secs) => {
Self::now().saturating_sub(submitted_time) >= secs as u64
T::Time::now().saturating_sub(submitted_time) >= secs as u64
}
Requirement::BlockedByLockedRedemptions => true, // TODO: #1407
}
Expand Down
36 changes: 16 additions & 20 deletions pallets/pool-system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
#![feature(thread_local)]

use cfg_primitives::Moment;
use cfg_traits::{Permissions, PoolInspect, PoolMutate, PoolNAV, PoolReserve};
use cfg_traits::{Permissions, PoolInspect, PoolMutate, PoolNAV, PoolReserve, Seconds, TimeAsSecs};
use cfg_types::{
orders::SummarizedOrders,
permissions::{PermissionScope, PoolRole, Role},
Expand All @@ -26,7 +26,7 @@ use frame_support::{
ensure,
traits::{
fungibles::{Inspect, Mutate, Transfer},
ReservableCurrency, UnixTime,
ReservableCurrency,
},
transactional, BoundedVec, RuntimeDebug,
};
Expand Down Expand Up @@ -277,7 +277,7 @@ pub mod pallet {
type UpdateGuard: PoolUpdateGuard<
PoolDetails = PoolDetailsOf<Self>,
ScheduledUpdateDetails = ScheduledUpdateDetailsOf<Self>,
Moment = Moment,
Moment = Seconds,
>;

type AssetRegistry: OrmlMutate<
Expand All @@ -295,7 +295,7 @@ pub mod pallet {
type Permission: Permissions<
Self::AccountId,
Scope = PermissionScope<Self::PoolId, Self::CurrencyId>,
Role = Role<Self::TrancheId, Moment>,
Role = Role<Self::TrancheId, Seconds>,
Error = DispatchError,
>;

Expand All @@ -316,32 +316,32 @@ pub mod pallet {
Fulfillment = FulfillmentWithPrice<Self::BalanceRatio>,
>;

type Time: UnixTime;
type Time: TimeAsSecs;

/// Challenge time
#[pallet::constant]
type ChallengeTime: Get<<Self as frame_system::Config>::BlockNumber>;

/// Pool parameter defaults
#[pallet::constant]
type DefaultMinEpochTime: Get<u64>;
type DefaultMinEpochTime: Get<Seconds>;

#[pallet::constant]
type DefaultMaxNAVAge: Get<u64>;
type DefaultMaxNAVAge: Get<Seconds>;

/// Pool parameter bounds
#[pallet::constant]
type MinEpochTimeLowerBound: Get<u64>;
type MinEpochTimeLowerBound: Get<Seconds>;

#[pallet::constant]
type MinEpochTimeUpperBound: Get<u64>;
type MinEpochTimeUpperBound: Get<Seconds>;

#[pallet::constant]
type MaxNAVAgeUpperBound: Get<u64>;
type MaxNAVAgeUpperBound: Get<Seconds>;

/// Pool update settings
#[pallet::constant]
type MinUpdateDelay: Get<u64>;
type MinUpdateDelay: Get<Seconds>;

/// Max length for a tranche token name
#[pallet::constant]
Expand Down Expand Up @@ -595,7 +595,7 @@ pub mod pallet {
Error::<T>::InSubmissionPeriod
);

let now = Self::now();
let now = T::Time::now();
ensure!(
now.saturating_sub(pool.epoch.last_closed) >= pool.parameters.min_epoch_time,
Error::<T>::MinEpochTimeHasNotPassed
Expand Down Expand Up @@ -876,10 +876,6 @@ pub mod pallet {
}

impl<T: Config> Pallet<T> {
pub(crate) fn now() -> Moment {
T::Time::now().as_secs()
}

pub(crate) fn current_block() -> <T as frame_system::Config>::BlockNumber {
<frame_system::Pallet<T>>::block_number()
}
Expand Down Expand Up @@ -1036,7 +1032,7 @@ pub mod pallet {
}

if let Change::NewValue(tranches) = &changes.tranches {
let now = Self::now();
let now = T::Time::now();

pool.tranches.combine_with_mut_residual_top(
tranches.iter(),
Expand Down Expand Up @@ -1182,7 +1178,7 @@ pub mod pallet {
)?;

pool.tranches.rebalance_tranches(
Self::now(),
T::Time::now(),
pool.reserve.total,
epoch.nav,
tranche_ratios.as_slice(),
Expand All @@ -1202,7 +1198,7 @@ pub mod pallet {
let pool_account = PoolLocator { pool_id }.into_account_truncating();
Pool::<T>::try_mutate(pool_id, |pool| {
let pool = pool.as_mut().ok_or(Error::<T>::NoSuchPool)?;
let now = Self::now();
let now = T::Time::now();

pool.reserve.total.ensure_add_assign(amount)?;

Expand Down Expand Up @@ -1245,7 +1241,7 @@ pub mod pallet {
let pool_account = PoolLocator { pool_id }.into_account_truncating();
Pool::<T>::try_mutate(pool_id, |pool| {
let pool = pool.as_mut().ok_or(Error::<T>::NoSuchPool)?;
let now = Self::now();
let now = T::Time::now();

pool.reserve.total = pool
.reserve
Expand Down
18 changes: 9 additions & 9 deletions pallets/pool-system/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
use cfg_primitives::{Balance, BlockNumber, CollectionId, PoolId, TrancheId};
pub use cfg_primitives::{Moment, PoolEpochId, TrancheWeight};
pub use cfg_primitives::{PoolEpochId, TrancheWeight};
use cfg_traits::{
investments::{OrderManager, TrancheCurrency as TrancheCurrencyT},
Permissions as PermissionsT, PoolUpdateGuard, PreConditions,
Millis, Permissions as PermissionsT, PoolUpdateGuard, PreConditions, Seconds,
};
pub use cfg_types::fixed_point::{Quantity, Rate};
use cfg_types::{
Expand Down Expand Up @@ -74,19 +74,19 @@ frame_support::construct_runtime!(
parameter_types! {
pub const One: u64 = 1;
#[derive(Debug, Eq, PartialEq, scale_info::TypeInfo, Clone)]
pub const MinDelay: Moment = 0;
pub const MinDelay: Seconds = 0;
pub const MaxRoles: u32 = u32::MAX;
}

impl pallet_permissions::Config for Runtime {
type AdminOrigin = EnsureSignedBy<One, u64>;
type Editors = frame_support::traits::Everything;
type MaxRolesPerScope = MaxRoles;
type Role = Role<TrancheId, Moment>;
type Role = Role<TrancheId, Seconds>;
type RuntimeEvent = RuntimeEvent;
type Scope = PermissionScope<u64, CurrencyId>;
type Storage =
PermissionRoles<TimeProvider<Timestamp>, MinDelay, TrancheId, MaxTranches, Moment>;
PermissionRoles<TimeProvider<Timestamp>, MinDelay, TrancheId, MaxTranches, Seconds>;
type WeightInfo = ();
}

Expand Down Expand Up @@ -130,7 +130,7 @@ impl system::Config for Runtime {

impl pallet_timestamp::Config for Runtime {
type MinimumPeriod = ();
type Moment = Moment;
type Moment = Millis;
type OnTimestampSet = ();
type WeightInfo = ();
}
Expand Down Expand Up @@ -366,7 +366,7 @@ impl Contains<CurrencyId> for PoolCurrency {

pub struct UpdateGuard;
impl PoolUpdateGuard for UpdateGuard {
type Moment = Moment;
type Moment = Seconds;
type PoolDetails = PoolDetails<
CurrencyId,
TrancheCurrency,
Expand Down Expand Up @@ -507,7 +507,7 @@ pub fn next_block() {
next_block_after(12)
}

pub fn next_block_after(seconds: u64) {
pub fn next_block_after(seconds: Seconds) {
Timestamp::on_finalize(System::block_number());
System::on_finalize(System::block_number());
System::set_block_number(System::block_number() + 1);
Expand Down Expand Up @@ -542,7 +542,7 @@ pub fn test_nav_down(pool_id: u64, amount: Balance) {
);
}

pub fn test_nav_update(pool_id: u64, amount: Balance, now: Moment) {
pub fn test_nav_update(pool_id: u64, amount: Balance, now: Seconds) {
FakeNav::update(pool_id, amount, now)
}

Expand Down
24 changes: 12 additions & 12 deletions pallets/pool-system/src/pool_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

use cfg_primitives::Moment;
use cfg_traits::Seconds;
use cfg_types::{epoch::EpochState, pools::TrancheMetadata};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
Expand Down Expand Up @@ -94,7 +94,7 @@ where
MaxTranches: Get<u32>,
{
pub changes: PoolChanges<Rate, MaxTokenNameLength, MaxTokenSymbolLength, MaxTranches>,
pub submitted_at: Moment,
pub submitted_at: Seconds,
}

/// A representation of a pool identifier that can be converted to an account
Expand Down Expand Up @@ -142,9 +142,9 @@ pub enum PoolStatus {
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct PoolParameters {
/// Minimum duration for an epoch.
pub min_epoch_time: Moment,
pub min_epoch_time: Seconds,
/// Maximum time between the NAV update and the epoch closing.
pub max_nav_age: Moment,
pub max_nav_age: Seconds,
}

#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
Expand All @@ -157,8 +157,8 @@ where
pub tranches: Change<BoundedVec<TrancheUpdate<Rate>, MaxTranches>>,
pub tranche_metadata:
Change<BoundedVec<TrancheMetadata<MaxTokenNameLength, MaxTokenSymbolLength>, MaxTranches>>,
pub min_epoch_time: Change<Moment>,
pub max_nav_age: Change<Moment>,
pub min_epoch_time: Change<Seconds>,
pub max_nav_age: Change<Seconds>,
}

// NOTE: Can be removed once orml_traits::Change impls MaxEncodedLen
Expand All @@ -173,7 +173,7 @@ where
BoundedVec<TrancheUpdate<Rate>, MaxTranches>: MaxEncodedLen,
BoundedVec<TrancheMetadata<MaxTokenNameLength, MaxTokenSymbolLength>, MaxTranches>:
MaxEncodedLen,
Moment: MaxEncodedLen,
Seconds: MaxEncodedLen,
{
fn max_encoded_len() -> usize {
// The tranches (default bound)
Expand All @@ -184,7 +184,7 @@ where
MaxTranches,
>::max_encoded_len())
// The min epoc time and max nav age (default bounds)
.saturating_add(Moment::max_encoded_len().saturating_mul(2))
.saturating_add(Seconds::max_encoded_len().saturating_mul(2))
// From the `Change` enum which wraps all four fields of Self
.saturating_add(4)
}
Expand Down Expand Up @@ -216,9 +216,9 @@ pub struct PoolEssence<
/// The maximum allowed reserve on a given pool
pub max_reserve: Balance,
/// Maximum time between the NAV update and the epoch closing.
pub max_nav_age: Moment,
pub max_nav_age: Seconds,
/// Minimum duration for an epoch.
pub min_epoch_time: Moment,
pub min_epoch_time: Seconds,
/// Tranches on a pool
pub tranches:
Vec<TrancheEssence<TrancheCurrency, Rate, MaxTokenNameLength, MaxTokenSymbolLength>>,
Expand Down Expand Up @@ -256,7 +256,7 @@ impl<
Weight: Copy + From<u128>,
MaxTranches: Get<u32>,
{
pub fn start_next_epoch(&mut self, now: Moment) -> DispatchResult {
pub fn start_next_epoch(&mut self, now: Seconds) -> DispatchResult {
self.epoch.current.ensure_add_assign(One::one())?;
self.epoch.last_closed = now;
// TODO: Remove and set state rather to EpochClosing or similar
Expand Down Expand Up @@ -428,7 +428,7 @@ pub mod changes {
/// A PoolChangeProposal with extra information about when it was noted.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct NotedPoolChange<ChangeProposal: Into<PoolChangeProposal>> {
pub submitted_time: Moment,
pub submitted_time: Seconds,
pub change: ChangeProposal,
}
}
Expand Down
Loading