Skip to content

Commit

Permalink
pallet-loans ported
Browse files Browse the repository at this point in the history
  • Loading branch information
lemunozm committed Aug 5, 2024
1 parent 40cd54b commit ae9d070
Show file tree
Hide file tree
Showing 26 changed files with 166 additions and 164 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions libs/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ pub mod constants {
pub const SLOT_DURATION: Millis = MILLISECS_PER_BLOCK;

// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK.get() as BlockNumber);
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK.inner as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;

Expand All @@ -203,7 +203,7 @@ pub mod constants {
pub const SECONDS_PER_YEAR: Seconds = SECONDS_PER_DAY.mul_int(365);

/// Milliseconds per day
pub const MILLISECS_PER_DAY: Millis = Millis::from(SECONDS_PER_DAY.get() * 1000);
pub const MILLISECS_PER_DAY: Millis = Millis::from(SECONDS_PER_DAY.inner * 1000);

/// We assume that ~5% of the block weight is consumed by `on_initialize`
/// handlers. This is used to limit the maximal weight of a single
Expand Down
8 changes: 1 addition & 7 deletions libs/utils/src/num_wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use sp_std::{
#[derive(TypeInfo, Serialize, Deserialize, Encode, Decode, MaxEncodedLen)]
#[scale_info(skip_type_params(T, I))]
pub struct NumWrapper<T, I> {
inner: T,
pub inner: T,
_instance: PhantomData<I>,
}

Expand All @@ -42,12 +42,6 @@ impl<T, I> NumWrapper<T, I> {
}
}

impl<T: Copy, I> NumWrapper<T, I> {
pub const fn get(self) -> T {
self.inner
}
}

macro_rules! const_methods {
($t:ty) => {
impl<I> NumWrapper<$t, I> {
Expand Down
12 changes: 6 additions & 6 deletions libs/utils/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ pub type Millis<T> = NumWrapper<T, MillisId>;

impl<M: Div<Output = M> + From<u32> + Copy> Millis<M> {
pub fn into_seconds<S: TryFrom<M> + Bounded>(self) -> Seconds<S> {
let inner = self.get() / M::from(1000);
let inner = self.inner / M::from(1000);
Seconds::from(S::try_from(inner).unwrap_or(Bounded::max_value()))
}

pub fn into_days<D: TryFrom<M> + Bounded>(self) -> Days<D> {
let inner = self.get() / M::from(1000 * 24 * 3600);
let inner = self.inner / M::from(1000 * 24 * 3600);
Days::from(D::try_from(inner).unwrap_or(Bounded::max_value()))
}
}
Expand All @@ -29,7 +29,7 @@ pub type Seconds<T> = NumWrapper<T, SecondsId>;

impl<S: Copy> Seconds<S> {
pub fn into_millis<M: TryFrom<S> + From<u32> + Saturating + Bounded>(self) -> Millis<M> {
let inner = M::try_from(self.get())
let inner = M::try_from(self.inner)
.unwrap_or(Bounded::max_value())
.saturating_mul(M::from(1000));
Millis::from(inner)
Expand All @@ -38,7 +38,7 @@ impl<S: Copy> Seconds<S> {

impl<S: Div<Output = S> + From<u32> + Copy> Seconds<S> {
pub fn into_days<D: TryFrom<S> + Bounded>(self) -> Days<D> {
let inner = self.get() / S::from(24 * 3600);
let inner = self.inner / S::from(24 * 3600);
Days::from(D::try_from(inner).unwrap_or(Bounded::max_value()))
}
}
Expand All @@ -51,14 +51,14 @@ pub type Days<T> = NumWrapper<T, DaysId>;

impl<D: Copy> Days<D> {
pub fn into_millis<M: TryFrom<D> + From<u32> + Saturating + Bounded>(self) -> Millis<M> {
let inner = M::try_from(self.get())
let inner = M::try_from(self.inner)
.unwrap_or(Bounded::max_value())
.saturating_mul(M::from(1000 * 24 * 3600));
Millis::from(inner)
}

pub fn into_seconds<S: TryFrom<D> + From<u32> + Saturating + Bounded>(self) -> Seconds<S> {
let inner = S::try_from(self.get())
let inner = S::try_from(self.inner)
.unwrap_or(Bounded::max_value())
.saturating_mul(S::from(24 * 3600));
Seconds::from(inner)
Expand Down
7 changes: 3 additions & 4 deletions pallets/loans/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ use cfg_traits::{
benchmarking::FundedPoolBenchmarkHelper,
changes::ChangeGuard,
interest::{CompoundingSchedule, InterestAccrual, InterestRate},
Permissions, PoolWriteOffPolicyMutate, TimeAsSecs, ValueProvider,
time::UnixTimeSecs,
Permissions, PoolWriteOffPolicyMutate, ValueProvider,
};
use cfg_types::{
adjustments::Adjustment,
Expand Down Expand Up @@ -74,7 +75,7 @@ fn config_mocks() {
MockChangeGuard::mock_released(move |_, _| Ok(change.clone()));
Ok(sp_core::H256::default())
});
MockTimer::mock_now(|| 0);
MockTimer::mock_now(|| 0u32.into());
}

struct Helper<T>(sp_std::marker::PhantomData<T>);
Expand All @@ -90,7 +91,6 @@ where
AccountId = T::AccountId,
Balance = T::Balance,
>,
T::Moment: Default,
T::PriceRegistry: ValueProvider<(u32, T::PoolId), T::PriceId, Value = PriceOf<T>>,
{
fn prepare_benchmark() -> T::PoolId {
Expand Down Expand Up @@ -325,7 +325,6 @@ benchmarks! {
T::ItemId: From<u16>,
T::PriceId: From<u32>,
T::Pool: FundedPoolBenchmarkHelper<PoolId = T::PoolId, AccountId = T::AccountId, Balance = T::Balance>,
T::Moment: Default,
T::PriceRegistry: ValueProvider<(u32, T::PoolId), T::PriceId, Value = PriceOf<T>>,
}

Expand Down
3 changes: 2 additions & 1 deletion pallets/loans/src/entities/changes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use cfg_traits::{interest::InterestRate, Seconds};
use cfg_primitives::Seconds;
use cfg_traits::interest::InterestRate;
use frame_support::{pallet_prelude::RuntimeDebug, storage::bounded_vec::BoundedVec};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
Expand Down
2 changes: 1 addition & 1 deletion pallets/loans/src/entities/interest.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cfg_traits::{
interest::{InterestAccrual, InterestRate, RateCollection},
TimeAsSecs,
time::UnixTimeSecs,
};
use cfg_types::adjustments::Adjustment;
use frame_support::RuntimeDebugNoBound;
Expand Down
6 changes: 4 additions & 2 deletions pallets/loans/src/entities/loans.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use cfg_primitives::Seconds;
use cfg_traits::{
self,
interest::{InterestAccrual, InterestRate, RateCollection},
Seconds, TimeAsSecs,
time::UnixTimeSecs,
};
use cfg_types::adjustments::Adjustment;
use frame_support::{ensure, pallet_prelude::DispatchResult, RuntimeDebugNoBound};
Expand Down Expand Up @@ -598,7 +599,8 @@ impl<T: Config> TryFrom<(T::PoolId, ActiveLoan<T>)> for ActiveLoanInfo<T> {

/// Adds `with_linear_pricing` to ExternalPricing struct for migration to v4
pub mod v3 {
use cfg_traits::{interest::InterestRate, Seconds};
use cfg_primitives::Seconds;
use cfg_traits::interest::InterestRate;
use parity_scale_codec::{Decode, Encode};

use crate::{
Expand Down
7 changes: 3 additions & 4 deletions pallets/loans/src/entities/pricing/external.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use cfg_traits::{
self, data::DataRegistry, interest::InterestRate, IntoSeconds, Seconds, TimeAsSecs,
};
use cfg_primitives::Seconds;
use cfg_traits::{self, data::DataRegistry, interest::InterestRate, time::UnixTimeSecs};
use cfg_types::adjustments::Adjustment;
use frame_support::{self, ensure, pallet_prelude::RuntimeDebug, RuntimeDebugNoBound};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
Expand Down Expand Up @@ -329,7 +328,7 @@ impl<T: Config> ExternalActivePricing<T> {

/// Adds `with_linear_pricing` to ExternalPricing struct for migration to v4
pub mod v3 {
use cfg_traits::Seconds;
use cfg_primitives::Seconds;
use parity_scale_codec::{Decode, Encode};

use crate::{
Expand Down
3 changes: 2 additions & 1 deletion pallets/loans/src/entities/pricing/internal.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use cfg_primitives::Seconds;
use cfg_traits::{
interest::{InterestRate, RateCollection},
Seconds, TimeAsSecs,
time::UnixTimeSecs,
};
use cfg_types::adjustments::Adjustment;
use frame_support::{
Expand Down
14 changes: 6 additions & 8 deletions pallets/loans/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,14 @@ pub use weights::WeightInfo;

#[frame_support::pallet]
pub mod pallet {
use cfg_primitives::{Millis, Seconds};
use cfg_traits::{
self,
changes::ChangeGuard,
data::{DataCollection, DataRegistry},
interest::InterestAccrual,
IntoSeconds, Permissions, PoolInspect, PoolNAV, PoolReserve, PoolWriteOffPolicyMutate,
Seconds, TimeAsSecs,
time::UnixTimeSecs,
Permissions, PoolInspect, PoolNAV, PoolReserve, PoolWriteOffPolicyMutate,
};
use cfg_types::{
adjustments::Adjustment,
Expand Down Expand Up @@ -117,7 +118,7 @@ pub mod pallet {

pub type PortfolioInfoOf<T> = Vec<(<T as Config>::LoanId, ActiveLoanInfo<T>)>;
pub type AssetOf<T> = (<T as Config>::CollectionId, <T as Config>::ItemId);
pub type PriceOf<T> = (<T as Config>::Balance, <T as Config>::Moment);
pub type PriceOf<T> = (<T as Config>::Balance, Millis);

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

Expand Down Expand Up @@ -167,10 +168,7 @@ pub mod pallet {
type PerThing: Parameter + Member + PerThing + TypeInfo + MaxEncodedLen;

/// Fetching method for the time of the current block
type Time: TimeAsSecs;

/// Generic time type
type Moment: Parameter + Member + Copy + IntoSeconds;
type Time: UnixTimeSecs;

/// Used to mint, transfer, and inspect assets.
type NonFungible: Transfer<Self::AccountId>
Expand Down Expand Up @@ -1300,7 +1298,7 @@ pub mod pallet {

vec![
WriteOffRule::new(
[WriteOffTrigger::PrincipalOverdue(0)],
[WriteOffTrigger::PrincipalOverdue(0u32.into())],
T::Rate::zero(),
T::Rate::zero(),
);
Expand Down
16 changes: 8 additions & 8 deletions pallets/loans/src/tests/borrow_loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fn config_mocks(withdraw_amount: Balance) {
MockPrices::mock_get(|id, pool_id| {
assert_eq!(*pool_id, POOL_A);
match *id {
REGISTER_PRICE_ID => Ok((PRICE_VALUE, BLOCK_TIME_MS)),
REGISTER_PRICE_ID => Ok((PRICE_VALUE, PRICE_TIMESTAMP)),
_ => Err(PRICE_ID_NO_FOUND),
}
});
Expand Down Expand Up @@ -73,7 +73,7 @@ fn with_restriction_no_written_off() {
PrincipalInput::Internal(COLLATERAL_VALUE / 2)
));

advance_time(YEAR + DAY);
advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY);
util::write_off_loan(loan_id);

assert_noop!(
Expand Down Expand Up @@ -136,7 +136,7 @@ fn with_maturity_passed() {
new_test_ext().execute_with(|| {
let loan_id = util::create_loan(util::base_internal_loan());

advance_time(YEAR);
advance_time(SECONDS_PER_YEAR);

config_mocks(COLLATERAL_VALUE);
assert_noop!(
Expand Down Expand Up @@ -333,7 +333,7 @@ fn with_unregister_price_id_and_oracle_not_required() {
);

// Suddenty, the oracle set a value
MockPrices::mock_get(|_, _| Ok((PRICE_VALUE * 8, BLOCK_TIME_MS)));
MockPrices::mock_get(|_, _| Ok((PRICE_VALUE * 8, PRICE_TIMESTAMP)));

assert_eq!(
(QUANTITY).saturating_mul_int(PRICE_VALUE * 8),
Expand Down Expand Up @@ -552,11 +552,11 @@ fn twice_with_elapsed_time() {
));
assert_eq!(COLLATERAL_VALUE / 2, util::current_loan_debt(loan_id));

advance_time(YEAR / 2);
advance_time(SECONDS_PER_YEAR / 2);

assert_eq!(
util::current_debt_for(
util::interest_for(DEFAULT_INTEREST_RATE, YEAR / 2),
util::interest_for(DEFAULT_INTEREST_RATE, SECONDS_PER_YEAR / 2),
COLLATERAL_VALUE / 2,
),
util::current_loan_debt(loan_id)
Expand Down Expand Up @@ -633,7 +633,7 @@ mod cashflow {
let principal = COLLATERAL_VALUE / 2;
let acc_interest_rate_per_year = checked_pow(
util::default_interest_rate().per_sec().unwrap(),
SECONDS_PER_YEAR as usize,
SECONDS_PER_YEAR.inner as usize,
)
.unwrap();
let interest = acc_interest_rate_per_year.saturating_mul_int(principal) - principal;
Expand Down Expand Up @@ -669,7 +669,7 @@ mod cashflow {
let principal = amount.balance().unwrap();
let acc_interest_rate_per_year = checked_pow(
util::default_interest_rate().per_sec().unwrap(),
SECONDS_PER_YEAR as usize,
SECONDS_PER_YEAR.inner as usize,
)
.unwrap();

Expand Down
2 changes: 1 addition & 1 deletion pallets/loans/src/tests/close_loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ fn with_time_after_fully_repaid_internal() {
util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE));
util::repay_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE));

advance_time(YEAR);
advance_time(SECONDS_PER_YEAR);

assert_ok!(Loans::close(
RuntimeOrigin::signed(BORROWER),
Expand Down
4 changes: 2 additions & 2 deletions pallets/loans/src/tests/create_loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn config_mocks(pool_id: PoolId) {
MockPrices::mock_get(|id, pool_id| {
assert_eq!(*pool_id, POOL_A);
match *id {
REGISTER_PRICE_ID => Ok((PRICE_VALUE, BLOCK_TIME_MS)),
REGISTER_PRICE_ID => Ok((PRICE_VALUE, PRICE_TIMESTAMP)),
_ => Err("Should never be dispatched".into()),
}
});
Expand Down Expand Up @@ -91,7 +91,7 @@ fn with_wrong_schedule() {

let loan = LoanInfo {
schedule: RepaymentSchedule {
maturity: Maturity::fixed(now().as_secs()),
maturity: Maturity::fixed(now()),
interest_payments: InterestPayments::OnceAtMaturity,
pay_down_schedule: PayDownSchedule::None,
},
Expand Down
Loading

0 comments on commit ae9d070

Please sign in to comment.