From 7f9b9914863b00171bfe6138343bd9088cd490bf Mon Sep 17 00:00:00 2001 From: lemunozm Date: Mon, 5 Aug 2024 14:45:37 +0200 Subject: [PATCH] pallet-loans ported --- Cargo.lock | 1 + libs/primitives/src/lib.rs | 4 +-- libs/utils/src/num_wrapper.rs | 8 +---- libs/utils/src/time.rs | 12 +++---- pallets/loans/src/benchmarking.rs | 7 ++-- pallets/loans/src/entities/changes.rs | 3 +- pallets/loans/src/entities/interest.rs | 2 +- pallets/loans/src/entities/loans.rs | 6 ++-- .../loans/src/entities/pricing/external.rs | 7 ++-- .../loans/src/entities/pricing/internal.rs | 3 +- pallets/loans/src/lib.rs | 14 ++++---- pallets/loans/src/tests/borrow_loan.rs | 16 ++++----- pallets/loans/src/tests/close_loan.rs | 2 +- pallets/loans/src/tests/create_loan.rs | 4 +-- pallets/loans/src/tests/mock.rs | 27 ++++++-------- pallets/loans/src/tests/mod.rs | 4 +-- pallets/loans/src/tests/mutate_loan.rs | 12 +++---- pallets/loans/src/tests/policy.rs | 22 ++++++------ .../loans/src/tests/portfolio_valuation.rs | 34 +++++++++--------- pallets/loans/src/tests/repay_loan.rs | 24 ++++++------- pallets/loans/src/tests/transfer_debt.rs | 6 ++-- pallets/loans/src/tests/util.rs | 18 +++++----- pallets/loans/src/tests/write_off_loan.rs | 36 +++++++++---------- pallets/loans/src/types/cashflow.rs | 20 +++++++---- pallets/loans/src/types/policy.rs | 34 +++++++++++------- pallets/loans/src/types/valuation.rs | 4 +-- 26 files changed, 166 insertions(+), 164 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aecabf0d3c..ce0f7e3562 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8199,6 +8199,7 @@ name = "pallet-interest-accrual" version = "0.1.0" dependencies = [ "bitflags 1.3.2", + "cfg-mocks", "cfg-primitives", "cfg-traits", "cfg-types", diff --git a/libs/primitives/src/lib.rs b/libs/primitives/src/lib.rs index b0c5a5af21..981f3392c4 100644 --- a/libs/primitives/src/lib.rs +++ b/libs/primitives/src/lib.rs @@ -193,7 +193,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; @@ -206,7 +206,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 diff --git a/libs/utils/src/num_wrapper.rs b/libs/utils/src/num_wrapper.rs index 6a1a7c33ae..3466fd46ca 100644 --- a/libs/utils/src/num_wrapper.rs +++ b/libs/utils/src/num_wrapper.rs @@ -29,7 +29,7 @@ use sp_std::{ #[derive(TypeInfo, Serialize, Deserialize, Encode, Decode, MaxEncodedLen)] #[scale_info(skip_type_params(T, I))] pub struct NumWrapper { - inner: T, + pub inner: T, _instance: PhantomData, } @@ -42,12 +42,6 @@ impl NumWrapper { } } -impl NumWrapper { - pub const fn get(self) -> T { - self.inner - } -} - macro_rules! const_methods { ($t:ty) => { impl NumWrapper<$t, I> { diff --git a/libs/utils/src/time.rs b/libs/utils/src/time.rs index e8b8febff3..5d45d788ba 100644 --- a/libs/utils/src/time.rs +++ b/libs/utils/src/time.rs @@ -11,12 +11,12 @@ pub type Millis = NumWrapper; impl + From + Copy> Millis { pub fn into_seconds + Bounded>(self) -> Seconds { - 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 + Bounded>(self) -> Days { - 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())) } } @@ -29,7 +29,7 @@ pub type Seconds = NumWrapper; impl Seconds { pub fn into_millis + From + Saturating + Bounded>(self) -> Millis { - 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) @@ -38,7 +38,7 @@ impl Seconds { impl + From + Copy> Seconds { pub fn into_days + Bounded>(self) -> Days { - 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())) } } @@ -51,14 +51,14 @@ pub type Days = NumWrapper; impl Days { pub fn into_millis + From + Saturating + Bounded>(self) -> Millis { - 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 + From + Saturating + Bounded>(self) -> Seconds { - 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) diff --git a/pallets/loans/src/benchmarking.rs b/pallets/loans/src/benchmarking.rs index b893fef06c..92d1369362 100644 --- a/pallets/loans/src/benchmarking.rs +++ b/pallets/loans/src/benchmarking.rs @@ -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, @@ -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(sp_std::marker::PhantomData); @@ -90,7 +91,6 @@ where AccountId = T::AccountId, Balance = T::Balance, >, - T::Moment: Default, T::PriceRegistry: ValueProvider<(u32, T::PoolId), T::PriceId, Value = PriceOf>, { fn prepare_benchmark() -> T::PoolId { @@ -325,7 +325,6 @@ benchmarks! { T::ItemId: From, T::PriceId: From, T::Pool: FundedPoolBenchmarkHelper, - T::Moment: Default, T::PriceRegistry: ValueProvider<(u32, T::PoolId), T::PriceId, Value = PriceOf>, } diff --git a/pallets/loans/src/entities/changes.rs b/pallets/loans/src/entities/changes.rs index eff6cd3ee4..7edb9b3635 100644 --- a/pallets/loans/src/entities/changes.rs +++ b/pallets/loans/src/entities/changes.rs @@ -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; diff --git a/pallets/loans/src/entities/interest.rs b/pallets/loans/src/entities/interest.rs index d826346c23..9e08076b2a 100644 --- a/pallets/loans/src/entities/interest.rs +++ b/pallets/loans/src/entities/interest.rs @@ -1,6 +1,6 @@ use cfg_traits::{ interest::{InterestAccrual, InterestRate, RateCollection}, - TimeAsSecs, + time::UnixTimeSecs, }; use cfg_types::adjustments::Adjustment; use frame_support::RuntimeDebugNoBound; diff --git a/pallets/loans/src/entities/loans.rs b/pallets/loans/src/entities/loans.rs index b9cb593740..af52a189ea 100644 --- a/pallets/loans/src/entities/loans.rs +++ b/pallets/loans/src/entities/loans.rs @@ -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}; @@ -598,7 +599,8 @@ impl TryFrom<(T::PoolId, ActiveLoan)> for ActiveLoanInfo { /// 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::{ diff --git a/pallets/loans/src/entities/pricing/external.rs b/pallets/loans/src/entities/pricing/external.rs index 00d15a7532..a08c67946c 100644 --- a/pallets/loans/src/entities/pricing/external.rs +++ b/pallets/loans/src/entities/pricing/external.rs @@ -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}; @@ -329,7 +328,7 @@ impl ExternalActivePricing { /// 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::{ diff --git a/pallets/loans/src/entities/pricing/internal.rs b/pallets/loans/src/entities/pricing/internal.rs index 10ea0d779a..75c1aad09d 100644 --- a/pallets/loans/src/entities/pricing/internal.rs +++ b/pallets/loans/src/entities/pricing/internal.rs @@ -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::{ diff --git a/pallets/loans/src/lib.rs b/pallets/loans/src/lib.rs index f3c3bceae7..1329c22c34 100644 --- a/pallets/loans/src/lib.rs +++ b/pallets/loans/src/lib.rs @@ -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, @@ -117,7 +118,7 @@ pub mod pallet { pub type PortfolioInfoOf = Vec<(::LoanId, ActiveLoanInfo)>; pub type AssetOf = (::CollectionId, ::ItemId); - pub type PriceOf = (::Balance, ::Moment); + pub type PriceOf = (::Balance, Millis); const STORAGE_VERSION: StorageVersion = StorageVersion::new(4); @@ -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 @@ -1300,7 +1298,7 @@ pub mod pallet { vec![ WriteOffRule::new( - [WriteOffTrigger::PrincipalOverdue(0)], + [WriteOffTrigger::PrincipalOverdue(0u32.into())], T::Rate::zero(), T::Rate::zero(), ); diff --git a/pallets/loans/src/tests/borrow_loan.rs b/pallets/loans/src/tests/borrow_loan.rs index ad3cf70651..c283beda05 100644 --- a/pallets/loans/src/tests/borrow_loan.rs +++ b/pallets/loans/src/tests/borrow_loan.rs @@ -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), } }); @@ -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!( @@ -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!( @@ -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), @@ -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) @@ -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; @@ -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(); diff --git a/pallets/loans/src/tests/close_loan.rs b/pallets/loans/src/tests/close_loan.rs index 307603e4a0..d9d3645696 100644 --- a/pallets/loans/src/tests/close_loan.rs +++ b/pallets/loans/src/tests/close_loan.rs @@ -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), diff --git a/pallets/loans/src/tests/create_loan.rs b/pallets/loans/src/tests/create_loan.rs index 37b87acdf9..1035e704e8 100644 --- a/pallets/loans/src/tests/create_loan.rs +++ b/pallets/loans/src/tests/create_loan.rs @@ -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()), } }); @@ -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, }, diff --git a/pallets/loans/src/tests/mock.rs b/pallets/loans/src/tests/mock.rs index ee381f73a6..99d56e380b 100644 --- a/pallets/loans/src/tests/mock.rs +++ b/pallets/loans/src/tests/mock.rs @@ -11,18 +11,17 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use std::time::Duration; - use cfg_mocks::{ pallet_mock_change_guard, pallet_mock_data, pallet_mock_permissions, pallet_mock_pools, }; -use cfg_traits::Millis; +use cfg_primitives::{Millis, Seconds}; +use cfg_traits::time::UnixTimeSecs; use cfg_types::permissions::PermissionScope; use frame_support::{ derive_impl, traits::{ tokens::nonfungibles::{Create, Mutate}, - AsEnsureOriginWithArg, Hooks, UnixTime, + AsEnsureOriginWithArg, Hooks, }, }; use frame_system::{EnsureRoot, EnsureSigned}; @@ -34,11 +33,7 @@ use sp_runtime::{DispatchError, FixedU128}; use crate::{entities::changes::Change, pallet as pallet_loans}; -pub const BLOCK_TIME: Duration = Duration::from_secs(10); -pub const YEAR: Duration = Duration::from_secs(365 * 24 * 3600); -pub const DAY: Duration = Duration::from_secs(24 * 3600); - -pub const BLOCK_TIME_MS: u64 = BLOCK_TIME.as_millis() as u64; +pub const INITIAL_TIME: Seconds = Seconds::from(10); pub const ASSET_COLLECTION_OWNER: AccountId = 1; pub const BORROWER: AccountId = 1; @@ -75,6 +70,7 @@ pub const PRICE_VALUE: Balance = 980; pub const NOTIONAL: Balance = 1000; pub const QUANTITY: Quantity = Quantity::from_rational(12, 1); pub const CHANGE_ID: ChangeId = H256::repeat_byte(0x42); +pub const PRICE_TIMESTAMP: Millis = Millis::from(10000); pub const MAX_PRICE_VARIATION: Rate = Rate::from_rational(1, 100); pub const PRICE_ID_NO_FOUND: DispatchError = DispatchError::Other("Price ID not found"); @@ -121,7 +117,7 @@ impl frame_system::Config for Runtime { } impl cfg_mocks::time::pallet::Config for Runtime { - type Moment = Millis; + type Moment = Seconds; } #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] @@ -199,7 +195,6 @@ impl pallet_loans::Config for Runtime { type LoanId = LoanId; type MaxActiveLoansPerPool = MaxActiveLoansPerPool; type MaxWriteOffPolicySize = MaxWriteOffPolicySize; - type Moment = Millis; type NonFungible = Uniques; type PerThing = Perbill; type Permissions = MockPermissions; @@ -218,7 +213,7 @@ impl pallet_loans::Config for Runtime { pub fn new_test_ext() -> sp_io::TestExternalities { let mut ext = System::externalities(); ext.execute_with(|| { - MockTimer::mock_now(|| BLOCK_TIME.as_millis() as u64); + MockTimer::mock_now(|| INITIAL_TIME); Uniques::create_collection(&COLLECTION_A, &BORROWER, &ASSET_COLLECTION_OWNER).unwrap(); Uniques::mint_into(&COLLECTION_A, &ASSET_AA.1, &BORROWER).unwrap(); @@ -232,12 +227,12 @@ pub fn new_test_ext() -> sp_io::TestExternalities { ext } -pub fn now() -> Duration { - ::now() +pub fn now() -> Seconds { + MockTimer::now_secs() } -pub fn advance_time(elapsed: Duration) { +pub fn advance_time(elapsed: Seconds) { let before = now(); - MockTimer::mock_now(move || (before + elapsed).as_millis() as u64); + MockTimer::mock_now(move || before + elapsed); InterestAccrual::on_initialize(0); } diff --git a/pallets/loans/src/tests/mod.rs b/pallets/loans/src/tests/mod.rs index 01ebc3b8ae..bfa5839bc4 100644 --- a/pallets/loans/src/tests/mod.rs +++ b/pallets/loans/src/tests/mod.rs @@ -1,7 +1,5 @@ -use std::time::Duration; - use cfg_mocks::pallet_mock_data::util::MockDataCollection; -use cfg_primitives::{SECONDS_PER_DAY, SECONDS_PER_YEAR}; +use cfg_primitives::{Seconds, SECONDS_PER_DAY, SECONDS_PER_YEAR}; use cfg_traits::interest::{CompoundingSchedule, InterestRate}; use cfg_types::permissions::{PermissionScope, PoolRole, Role}; use frame_support::{assert_noop, assert_ok, storage::bounded_vec::BoundedVec}; diff --git a/pallets/loans/src/tests/mutate_loan.rs b/pallets/loans/src/tests/mutate_loan.rs index 7f4d5f2e83..beb6c833b6 100644 --- a/pallets/loans/src/tests/mutate_loan.rs +++ b/pallets/loans/src/tests/mutate_loan.rs @@ -147,7 +147,7 @@ mod wrong_mutation { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(0)); - let mutation = LoanMutation::MaturityExtension(YEAR.as_secs()); + let mutation = LoanMutation::MaturityExtension(SECONDS_PER_YEAR); config_mocks(loan_id, &mutation); assert_noop!( @@ -211,8 +211,8 @@ fn with_successful_mutation_application() { let loan = LoanInfo { schedule: RepaymentSchedule { maturity: Maturity::Fixed { - date: (now() + YEAR).as_secs(), - extension: YEAR.as_secs(), + date: now() + SECONDS_PER_YEAR, + extension: SECONDS_PER_YEAR, }, interest_payments: InterestPayments::OnceAtMaturity, pay_down_schedule: PayDownSchedule::None, @@ -242,10 +242,10 @@ fn with_successful_mutation_application() { // LoanMutation::InterestPayments(..), No changes, only one variant // LoanMutation::PayDownSchedule(..), No changes, only one variant LoanMutation::Maturity(Maturity::Fixed { - date: (now() + YEAR * 2).as_secs(), - extension: (YEAR * 2).as_secs(), + date: now() + SECONDS_PER_YEAR * 2, + extension: SECONDS_PER_YEAR * 2, }), - LoanMutation::MaturityExtension(YEAR.as_secs()), + LoanMutation::MaturityExtension(SECONDS_PER_YEAR), LoanMutation::InterestRate(InterestRate::Fixed { rate_per_year: Rate::from_float(0.5), compounding: CompoundingSchedule::Secondly, diff --git a/pallets/loans/src/tests/policy.rs b/pallets/loans/src/tests/policy.rs index ef2c0a4198..1e99f2f771 100644 --- a/pallets/loans/src/tests/policy.rs +++ b/pallets/loans/src/tests/policy.rs @@ -10,7 +10,7 @@ fn config_mocks(pool_id: PoolId, policy: &BoundedVec, MaxWrit MockPrices::mock_get(|id, pool_id| { assert_eq!(*pool_id, POOL_A); assert_eq!(*id, REGISTER_PRICE_ID); - Ok((PRICE_VALUE, BLOCK_TIME_MS)) + Ok((PRICE_VALUE, PRICE_TIMESTAMP)) }); MockChangeGuard::mock_note({ let policy = policy.clone(); @@ -98,7 +98,7 @@ fn with_wrong_loan_mutation_change() { fn with_successful_overwriting() { new_test_ext().execute_with(|| { let policy: BoundedVec<_, _> = vec![WriteOffRule::new( - [WriteOffTrigger::PrincipalOverdue(1)], + [WriteOffTrigger::PrincipalOverdue(1u32.into())], Rate::from_float(POLICY_PERCENTAGE), Rate::from_float(POLICY_PENALTY), )] @@ -131,7 +131,7 @@ fn with_price_outdated() { util::borrow_loan(loan_id, PrincipalInput::External(amount)); let policy: BoundedVec<_, _> = vec![WriteOffRule::new( - [WriteOffTrigger::PriceOutdated(10)], + [WriteOffTrigger::PriceOutdated(10u32.into())], Rate::from_float(POLICY_PERCENTAGE), Rate::from_float(POLICY_PENALTY), )] @@ -150,13 +150,13 @@ fn with_price_outdated() { CHANGE_ID )); - advance_time(Duration::from_secs(9)); + advance_time(Seconds::from(9)); assert_noop!( Loans::write_off(RuntimeOrigin::signed(ANY), POOL_A, loan_id), Error::::NoValidWriteOffRule ); - advance_time(Duration::from_secs(1)); + advance_time(Seconds::from(9)); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), POOL_A, @@ -181,25 +181,25 @@ fn with_success() { let policy: BoundedVec<_, _> = vec![ WriteOffRule::new( - [WriteOffTrigger::PriceOutdated(10)], + [WriteOffTrigger::PriceOutdated(10u32.into())], Rate::from_float(0.8), Rate::from_float(0.8), ), WriteOffRule::new( [ - WriteOffTrigger::PrincipalOverdue(1), - WriteOffTrigger::PriceOutdated(0), + WriteOffTrigger::PrincipalOverdue(1u32.into()), + WriteOffTrigger::PriceOutdated(0u32.into()), ], Rate::from_float(0.2), Rate::from_float(0.2), ), WriteOffRule::new( - [WriteOffTrigger::PrincipalOverdue(4)], + [WriteOffTrigger::PrincipalOverdue(4u32.into())], Rate::from_float(0.5), Rate::from_float(0.5), ), WriteOffRule::new( - [WriteOffTrigger::PrincipalOverdue(9)], + [WriteOffTrigger::PrincipalOverdue(9u32.into())], Rate::from_float(0.3), Rate::from_float(0.9), ), @@ -216,7 +216,7 @@ fn with_success() { )); // Check if a loan is correctly writen off - advance_time(YEAR + DAY * 10); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY * 10); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), POOL_A, diff --git a/pallets/loans/src/tests/portfolio_valuation.rs b/pallets/loans/src/tests/portfolio_valuation.rs index a6887adde4..2f1de8bac3 100644 --- a/pallets/loans/src/tests/portfolio_valuation.rs +++ b/pallets/loans/src/tests/portfolio_valuation.rs @@ -5,14 +5,14 @@ fn config_mocks() { MockPrices::mock_get(move |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), } }); MockPrices::mock_collection(|pool_id| { assert_eq!(*pool_id, POOL_A); Ok(MockDataCollection::new(|id| match *id { - REGISTER_PRICE_ID => Ok((PRICE_VALUE, BLOCK_TIME_MS)), + REGISTER_PRICE_ID => Ok((PRICE_VALUE, PRICE_TIMESTAMP)), _ => Err(PRICE_ID_NO_FOUND), })) }); @@ -59,7 +59,7 @@ fn without_active_loans() { ..util::base_internal_loan() }); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); config_mocks(); update_portfolio(); @@ -88,7 +88,7 @@ fn with_active_loans() { update_portfolio(); expected_portfolio(valuation); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); update_portfolio(); expected_portfolio(util::current_loan_pv(loan_1) + util::current_loan_pv(loan_2)); @@ -109,7 +109,7 @@ fn with_active_written_off_loans() { util::borrow_loan(loan_2, PrincipalInput::Internal(COLLATERAL_VALUE)); util::repay_loan(loan_2, PrincipalInput::Internal(COLLATERAL_VALUE / 4)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); util::write_off_loan(loan_1); util::write_off_loan(loan_2); @@ -134,16 +134,16 @@ fn filled_and_cleaned() { util::borrow_loan(loan_2, PrincipalInput::Internal(COLLATERAL_VALUE)); util::repay_loan(loan_2, PrincipalInput::Internal(COLLATERAL_VALUE / 2)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); util::write_off_loan(loan_1); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); util::repay_loan(loan_1, PrincipalInput::External(amount)); util::repay_loan(loan_2, PrincipalInput::Internal(COLLATERAL_VALUE / 2)); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); config_mocks(); update_portfolio(); @@ -162,7 +162,7 @@ fn exact_and_inexact_matches() { let loan_1 = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_1, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); config_mocks(); update_portfolio(); @@ -188,7 +188,7 @@ fn with_unregister_price_id_and_oracle_not_required() { let amount = ExternalAmount::new(QUANTITY, PRICE_VALUE); util::borrow_loan(loan_1, PrincipalInput::External(amount.clone())); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); // This is affected by the linear_accrual_price() computation. let price_value_after_half_year = PRICE_VALUE + (NOTIONAL - PRICE_VALUE) / 2; @@ -201,7 +201,7 @@ fn with_unregister_price_id_and_oracle_not_required() { const MARKET_PRICE_VALUE: Balance = 999; MockPrices::mock_collection(|_| { Ok(MockDataCollection::new(|_| { - Ok((MARKET_PRICE_VALUE, BLOCK_TIME_MS)) + Ok((MARKET_PRICE_VALUE, PRICE_TIMESTAMP)) })) }); let price_value_after_half_year = MARKET_PRICE_VALUE + (NOTIONAL - MARKET_PRICE_VALUE) / 2; @@ -216,7 +216,7 @@ fn empty_portfolio_with_current_timestamp() { new_test_ext().execute_with(|| { assert_eq!( PortfolioValuation::::get(POOL_A).last_updated(), - now().as_secs() + now() ); }); } @@ -241,12 +241,12 @@ fn no_linear_pricing_either_settlement_or_oracle() { util::borrow_loan(loan_1, PrincipalInput::External(amount.clone())); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); const MARKET_PRICE_VALUE: Balance = 999; MockPrices::mock_collection(|_| { Ok(MockDataCollection::new(|_| { - Ok((MARKET_PRICE_VALUE, BLOCK_TIME_MS)) + Ok((MARKET_PRICE_VALUE, PRICE_TIMESTAMP)) })) }); @@ -263,7 +263,7 @@ fn no_linear_pricing_either_settlement_or_oracle() { MockPrices::mock_collection(|_| { Ok(MockDataCollection::new(|_| { - Ok((MARKET_PRICE_VALUE, BLOCK_TIME_MS)) + Ok((MARKET_PRICE_VALUE, PRICE_TIMESTAMP)) })) }); update_portfolio(); @@ -313,11 +313,11 @@ fn internal_oustanding_debt_with_no_maturity() { update_portfolio(); expected_portfolio(pv); - advance_time(YEAR); + advance_time(SECONDS_PER_YEAR); update_portfolio(); expected_portfolio( - Rate::from_float(util::interest_for(DEFAULT_INTEREST_RATE, YEAR)) + Rate::from_float(util::interest_for(DEFAULT_INTEREST_RATE, SECONDS_PER_YEAR)) .checked_mul_int(COLLATERAL_VALUE) .unwrap(), ); diff --git a/pallets/loans/src/tests/repay_loan.rs b/pallets/loans/src/tests/repay_loan.rs index 5177a0dcdf..7aa50f1e41 100644 --- a/pallets/loans/src/tests/repay_loan.rs +++ b/pallets/loans/src/tests/repay_loan.rs @@ -16,7 +16,7 @@ pub fn config_mocks_with_price(deposit_amount: Balance, price: Balance) { MockPrices::mock_get(move |id, pool_id| { assert_eq!(*pool_id, POOL_A); match *id { - REGISTER_PRICE_ID => Ok((price, BLOCK_TIME_MS)), + REGISTER_PRICE_ID => Ok((price, PRICE_TIMESTAMP)), _ => Err(PRICE_ID_NO_FOUND), } }); @@ -94,7 +94,7 @@ fn has_been_written_off() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); util::write_off_loan(loan_id); config_mocks(util::current_loan_debt(loan_id)); @@ -494,11 +494,11 @@ fn twice_internal_with_elapsed_time() { }, )); - 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) @@ -555,11 +555,11 @@ fn twice_external_with_elapsed_time() { }, )); - 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), (QUANTITY / 2.into()).saturating_mul_int(NOTIONAL), ), util::current_loan_debt(loan_id) @@ -611,7 +611,7 @@ fn current_debt_rate_no_increase_if_fully_repaid() { }); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); config_mocks(util::current_loan_debt(loan_id)); assert_ok!(Loans::repay( @@ -625,7 +625,7 @@ fn current_debt_rate_no_increase_if_fully_repaid() { }, )); - advance_time(YEAR); + advance_time(SECONDS_PER_YEAR); assert_eq!(0, util::current_loan_debt(loan_id)); }); @@ -942,11 +942,11 @@ fn with_external_pricing() { assert_eq!(current_price(), PRICE_VALUE); // In the middle of the line - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); assert_eq!(current_price(), PRICE_VALUE + (NOTIONAL - PRICE_VALUE) / 2); // BEFORE: the loan not yet overdue - advance_time(YEAR / 2 - DAY); + advance_time(SECONDS_PER_YEAR / 2 - SECONDS_PER_DAY); assert_ok!(Loans::repay( RuntimeOrigin::signed(BORROWER), POOL_A, @@ -956,7 +956,7 @@ fn with_external_pricing() { assert!(current_price() < NOTIONAL); // EXACT: the loan is just at matuyrity date - advance_time(DAY); + advance_time(SECONDS_PER_DAY); assert_ok!(Loans::repay( RuntimeOrigin::signed(BORROWER), @@ -967,7 +967,7 @@ fn with_external_pricing() { assert_eq!(current_price(), NOTIONAL); // AFTER: the loan overpassing maturity date - advance_time(DAY); + advance_time(SECONDS_PER_DAY); assert_ok!(Loans::repay( RuntimeOrigin::signed(BORROWER), diff --git a/pallets/loans/src/tests/transfer_debt.rs b/pallets/loans/src/tests/transfer_debt.rs index 59c2a13d88..4371060101 100644 --- a/pallets/loans/src/tests/transfer_debt.rs +++ b/pallets/loans/src/tests/transfer_debt.rs @@ -11,7 +11,7 @@ fn config_mocks( MockPrices::mock_get(|id, pool_id| { assert_eq!(*id, REGISTER_PRICE_ID); assert_eq!(*pool_id, POOL_A); - Ok((PRICE_VALUE, BLOCK_TIME_MS)) + Ok((PRICE_VALUE, PRICE_TIMESTAMP)) }); MockPrices::mock_register_id(|id, pool_id| { assert_eq!(*pool_id, POOL_A); @@ -247,7 +247,7 @@ fn with_mismatch_external_internal_amounts() { MockPrices::mock_get(|id, pool_id| { assert_eq!(*id, REGISTER_PRICE_ID); assert_eq!(*pool_id, POOL_A); - Ok((PRICE_VALUE, BLOCK_TIME_MS)) + Ok((PRICE_VALUE, PRICE_TIMESTAMP)) }); assert_noop!( Loans::propose_transfer_debt( @@ -316,7 +316,7 @@ fn with_mismatch_external_external_amounts() { MockPrices::mock_get(|id, pool_id| { assert_eq!(*id, REGISTER_PRICE_ID); assert_eq!(*pool_id, POOL_A); - Ok((PRICE_VALUE, BLOCK_TIME_MS)) + Ok((PRICE_VALUE, PRICE_TIMESTAMP)) }); assert_noop!( Loans::propose_transfer_debt( diff --git a/pallets/loans/src/tests/util.rs b/pallets/loans/src/tests/util.rs index 4bd83467c6..d947f673a1 100644 --- a/pallets/loans/src/tests/util.rs +++ b/pallets/loans/src/tests/util.rs @@ -50,8 +50,8 @@ pub fn current_loan_pv(loan_id: LoanId) -> Balance { get_loan(loan_id).present_value(POOL_A).unwrap() } -pub fn interest_for(rate: f64, elapsed: Duration) -> f64 { - (1.0 + rate / YEAR.as_secs() as f64).powi(elapsed.as_secs() as i32) +pub fn interest_for(rate: f64, elapsed: Seconds) -> f64 { + (1.0 + rate / SECONDS_PER_YEAR.inner as f64).powi(elapsed.inner as i32) } pub fn current_debt_for(interest: f64, balance: Balance) -> Balance { @@ -121,8 +121,8 @@ pub fn base_internal_loan() -> LoanInfo { LoanInfo { schedule: RepaymentSchedule { maturity: Maturity::Fixed { - date: (now() + YEAR).as_secs(), - extension: (YEAR / 2).as_secs(), + date: now() + SECONDS_PER_YEAR, + extension: SECONDS_PER_YEAR / 2, }, interest_payments: InterestPayments::OnceAtMaturity, pay_down_schedule: PayDownSchedule::None, @@ -150,7 +150,7 @@ pub fn base_external_pricing() -> ExternalPricing { pub fn base_external_loan() -> LoanInfo { LoanInfo { schedule: RepaymentSchedule { - maturity: Maturity::fixed((now() + YEAR).as_secs()), + maturity: Maturity::fixed(now() + SECONDS_PER_YEAR), interest_payments: InterestPayments::OnceAtMaturity, pay_down_schedule: PayDownSchedule::None, }, @@ -172,7 +172,7 @@ pub fn create_loan_by(loan: LoanInfo, borrower: AccountId) -> LoanId { MockPermissions::mock_has(|_, _, _| true); MockPools::mock_pool_exists(|_| true); MockPools::mock_account_for(|_| POOL_A_ACCOUNT); - MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, BLOCK_TIME_MS))); + MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, PRICE_TIMESTAMP))); Loans::create(RuntimeOrigin::signed(borrower), POOL_A, loan).expect("successful creation"); @@ -186,7 +186,7 @@ pub fn create_loan_by(loan: LoanInfo, borrower: AccountId) -> LoanId { pub fn borrow_loan(loan_id: LoanId, borrow_amount: PrincipalInput) { MockPools::mock_withdraw(|_, _, _| Ok(())); - MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, BLOCK_TIME_MS))); + MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, PRICE_TIMESTAMP))); MockPrices::mock_register_id(|_, _| Ok(())); Loans::borrow( @@ -204,7 +204,7 @@ pub fn borrow_loan(loan_id: LoanId, borrow_amount: PrincipalInput) { pub fn repay_loan(loan_id: LoanId, repay_amount: PrincipalInput) { MockPools::mock_deposit(|_, _, _| Ok(())); - MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, BLOCK_TIME_MS))); + MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, PRICE_TIMESTAMP))); Loans::repay( RuntimeOrigin::signed(borrower(loan_id)), @@ -224,7 +224,7 @@ pub fn repay_loan(loan_id: LoanId, repay_amount: PrincipalInput) { pub fn write_off_loan(loan_id: LoanId) { set_up_policy(POLICY_PERCENTAGE, POLICY_PENALTY); - MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, BLOCK_TIME_MS))); + MockPrices::mock_get(|_, _| Ok((PRICE_VALUE, PRICE_TIMESTAMP))); Loans::write_off(RuntimeOrigin::signed(ANY), POOL_A, loan_id).expect("successful write off"); diff --git a/pallets/loans/src/tests/write_off_loan.rs b/pallets/loans/src/tests/write_off_loan.rs index 47d3b172ce..1af14e6f01 100644 --- a/pallets/loans/src/tests/write_off_loan.rs +++ b/pallets/loans/src/tests/write_off_loan.rs @@ -38,7 +38,7 @@ fn with_policy_but_not_overdue() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + BLOCK_TIME); + advance_time(SECONDS_PER_YEAR + INITIAL_TIME); // The loan maturity date has passed, but the policy can no be applied yet. assert_noop!( @@ -56,7 +56,7 @@ fn with_valid_maturity() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR / 2); + advance_time(SECONDS_PER_YEAR / 2); // The loan maturity date has no passed. assert_noop!( @@ -123,7 +123,7 @@ fn with_wrong_permission() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); config_mocks(); assert_noop!( @@ -147,7 +147,7 @@ fn with_success() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), @@ -165,7 +165,7 @@ fn with_admin_success() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); config_mocks(); @@ -215,7 +215,7 @@ fn with_admin_less_than_policy() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); config_mocks(); @@ -253,7 +253,7 @@ fn with_policy_change_after() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), @@ -296,7 +296,7 @@ fn with_policy_change_after_admin() { util::set_up_policy(POLICY_PERCENTAGE, POLICY_PENALTY); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), @@ -322,7 +322,7 @@ fn with_percentage_applied_internal() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); let pv = util::current_loan_pv(loan_id); @@ -349,12 +349,12 @@ fn with_percentage_applied_external() { let amount = ExternalAmount::new(QUANTITY, PRICE_VALUE); util::borrow_loan(loan_id, PrincipalInput::External(amount)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); MockPrices::mock_get(|id, pool_id| { assert_eq!(*pool_id, POOL_A); assert_eq!(*id, REGISTER_PRICE_ID); - Ok((PRICE_VALUE, BLOCK_TIME_MS)) + Ok((PRICE_VALUE, PRICE_TIMESTAMP)) }); let pv = util::current_loan_pv(loan_id); @@ -380,7 +380,7 @@ fn with_penalty_applied() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); assert_ok!(Loans::write_off( RuntimeOrigin::signed(ANY), @@ -391,13 +391,13 @@ fn with_penalty_applied() { // Modify an interest rate doesn't have effect in the same instant assert_eq!( util::current_debt_for( - util::interest_for(DEFAULT_INTEREST_RATE, YEAR + DAY), + util::interest_for(DEFAULT_INTEREST_RATE, SECONDS_PER_YEAR + SECONDS_PER_DAY), COLLATERAL_VALUE, ), util::current_loan_debt(loan_id) ); - advance_time(YEAR); + advance_time(SECONDS_PER_YEAR); // Because of math arithmetic preccission, // we get a difference that makes the test fail @@ -405,8 +405,8 @@ fn with_penalty_applied() { assert_eq!( util::current_debt_for( - util::interest_for(DEFAULT_INTEREST_RATE, YEAR + DAY) - * util::interest_for(DEFAULT_INTEREST_RATE + POLICY_PENALTY, YEAR), + util::interest_for(DEFAULT_INTEREST_RATE, SECONDS_PER_YEAR + SECONDS_PER_DAY) + * util::interest_for(DEFAULT_INTEREST_RATE + POLICY_PENALTY, SECONDS_PER_YEAR), COLLATERAL_VALUE, ) - precission_error, util::current_loan_debt(loan_id) @@ -420,7 +420,7 @@ fn fully() { let loan_id = util::create_loan(util::base_internal_loan()); util::borrow_loan(loan_id, PrincipalInput::Internal(COLLATERAL_VALUE)); - advance_time(YEAR + DAY); + advance_time(SECONDS_PER_YEAR + SECONDS_PER_DAY); config_mocks(); assert_ok!(Loans::admin_write_off( @@ -433,7 +433,7 @@ fn fully() { assert_eq!(0, util::current_loan_pv(loan_id)); - advance_time(YEAR); + advance_time(SECONDS_PER_YEAR); assert_eq!(0, util::current_loan_pv(loan_id)); }); diff --git a/pallets/loans/src/types/cashflow.rs b/pallets/loans/src/types/cashflow.rs index 4b5021a5c3..e5836c3178 100644 --- a/pallets/loans/src/types/cashflow.rs +++ b/pallets/loans/src/types/cashflow.rs @@ -11,7 +11,8 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_traits::{interest::InterestRate, Seconds}; +use cfg_primitives::Seconds; +use cfg_traits::interest::InterestRate; use frame_support::pallet_prelude::RuntimeDebug; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; @@ -40,7 +41,10 @@ pub enum Maturity { impl Maturity { pub fn fixed(date: Seconds) -> Self { - Self::Fixed { date, extension: 0 } + Self::Fixed { + date, + extension: Seconds::from(0), + } } pub fn date(&self) -> Option { @@ -207,11 +211,13 @@ pub mod tests { min: u32, sec: u32, ) -> Seconds { - from_ymd(year, month, day) - .and_hms_opt(hour, min, sec) - .unwrap() - .and_utc() - .timestamp() as Seconds + Seconds::from( + from_ymd(year, month, day) + .and_hms_opt(hour, min, sec) + .unwrap() + .and_utc() + .timestamp() as u64, + ) } pub fn last_secs_from_ymd(year: i32, month: u32, day: u32) -> Seconds { diff --git a/pallets/loans/src/types/policy.rs b/pallets/loans/src/types/policy.rs index 3cd5501b84..a6786b54f7 100644 --- a/pallets/loans/src/types/policy.rs +++ b/pallets/loans/src/types/policy.rs @@ -11,7 +11,7 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_traits::Seconds; +use cfg_primitives::Seconds; use frame_support::{pallet_prelude::RuntimeDebug, storage::bounded_btree_set::BoundedBTreeSet}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; @@ -200,8 +200,8 @@ mod tests { #[test] fn same_trigger_kinds() { let triggers: BoundedBTreeSet = BTreeSet::from_iter([ - UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(1)), - UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(2)), + UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(1u32.into())), + UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(2u32.into())), ]) .try_into() .unwrap(); @@ -212,8 +212,8 @@ mod tests { #[test] fn different_trigger_kinds() { let triggers: BoundedBTreeSet = BTreeSet::from_iter([ - UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(1)), - UniqueWriteOffTrigger(WriteOffTrigger::PriceOutdated(1)), + UniqueWriteOffTrigger(WriteOffTrigger::PrincipalOverdue(1u32.into())), + UniqueWriteOffTrigger(WriteOffTrigger::PriceOutdated(1u32.into())), ]) .try_into() .unwrap(); @@ -224,18 +224,18 @@ mod tests { #[test] fn find_correct_rule() { let rules = [ - WriteOffRule::new([WriteOffTrigger::PriceOutdated(0)], 5, 1), - WriteOffRule::new([WriteOffTrigger::PriceOutdated(1)], 7, 1), - WriteOffRule::new([WriteOffTrigger::PriceOutdated(2)], 7, 2), // <= - WriteOffRule::new([WriteOffTrigger::PriceOutdated(3)], 3, 4), - WriteOffRule::new([WriteOffTrigger::PriceOutdated(4)], 9, 1), + WriteOffRule::new([WriteOffTrigger::PriceOutdated(0u32.into())], 5, 1), + WriteOffRule::new([WriteOffTrigger::PriceOutdated(1u32.into())], 7, 1), + WriteOffRule::new([WriteOffTrigger::PriceOutdated(2u32.into())], 7, 2), // <= + WriteOffRule::new([WriteOffTrigger::PriceOutdated(3u32.into())], 3, 4), + WriteOffRule::new([WriteOffTrigger::PriceOutdated(4u32.into())], 9, 1), ]; let expected = rules[2].clone(); assert_ok!( find_rule(rules.into_iter(), |trigger| match trigger { - WriteOffTrigger::PriceOutdated(secs) => Ok(*secs <= 3), + WriteOffTrigger::PriceOutdated(secs) => Ok(*secs <= 3u32.into()), _ => unreachable!(), }), Some(expected) @@ -244,7 +244,11 @@ mod tests { #[test] fn find_err_rule() { - let rules = [WriteOffRule::new([WriteOffTrigger::PriceOutdated(0)], 5, 1)]; + let rules = [WriteOffRule::new( + [WriteOffTrigger::PriceOutdated(0u32.into())], + 5, + 1, + )]; assert_err!( find_rule(rules.into_iter(), |trigger| match trigger { @@ -256,7 +260,11 @@ mod tests { #[test] fn find_none_rule() { - let rules = [WriteOffRule::new([WriteOffTrigger::PriceOutdated(0)], 5, 1)]; + let rules = [WriteOffRule::new( + [WriteOffTrigger::PriceOutdated(0u32.into())], + 5, + 1, + )]; assert_ok!( find_rule(rules.into_iter(), |trigger| match trigger { diff --git a/pallets/loans/src/types/valuation.rs b/pallets/loans/src/types/valuation.rs index 0bd9b7330f..6269ca5b77 100644 --- a/pallets/loans/src/types/valuation.rs +++ b/pallets/loans/src/types/valuation.rs @@ -11,8 +11,8 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_primitives::SECONDS_PER_YEAR; -use cfg_traits::{interest::InterestRate, Seconds}; +use cfg_primitives::{Seconds, SECONDS_PER_YEAR}; +use cfg_traits::interest::InterestRate; use frame_support::{ pallet_prelude::RuntimeDebug, traits::tokens::{self},