Skip to content

Commit

Permalink
init tests for loans
Browse files Browse the repository at this point in the history
  • Loading branch information
lemunozm committed Oct 13, 2023
1 parent 2fb97d5 commit bf6269a
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 19 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.

2 changes: 1 addition & 1 deletion runtime/integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pallet-uniques = { git = "https://github.com/paritytech/substrate", default-feat
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38" }
pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38" }
pallet-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38" }

pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38" }

## Substrate-Primitives
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.38" }
Expand Down
47 changes: 47 additions & 0 deletions runtime/integration-tests/src/generic/cases/loans.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use cfg_primitives::{AccountId, Balance, CollectionId, ItemId, PoolId, CFG};
use frame_support::traits::Get;
use orml_traits::GetByKey;

use crate::{
generic::{
environment::{Blocks, Env},
envs::runtime_env::RuntimeEnv,
runtime::Runtime,
utils::{
self,
genesis::{self, Genesis, MUSD_CURRENCY_ID},
},
},
utils::accounts::Keyring,
};

const POOL_ADMIN: Keyring = Keyring::Admin;
const INVESTOR: Keyring = Keyring::Alice;
const BORROWER: Keyring = Keyring::Bob;

const FOR_FEES: Balance = 1 * CFG;

const POOL_A: PoolId = 23;
const NFT_A: (CollectionId, ItemId) = (1, ItemId(10));

fn borrow<T: Runtime>() {
let mut env = RuntimeEnv::<T>::from_storage(
Genesis::<T>::default()
.add(genesis::balances(T::ExistentialDeposit::get() + FOR_FEES))
.add(genesis::tokens(vec![(
MUSD_CURRENCY_ID,
T::ExistentialDeposits::get(&MUSD_CURRENCY_ID),
)]))
.add(genesis::assets(vec![MUSD_CURRENCY_ID]))
.storage(),
);

env.state_mut(|| {
utils::give_balance_to::<T>(POOL_ADMIN.id(), T::PoolDeposit::get());
utils::give_nft_to::<T>(BORROWER.id(), NFT_A);
});

env.state(|| {
//pallet_uniques::Pallet::<T>::
});
}
6 changes: 3 additions & 3 deletions runtime/integration-tests/src/generic/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ pub trait Env<T: Runtime> {
fn submit_now(
&mut self,
who: Keyring,
call: impl Into<T::RuntimeCall>,
call: impl Into<T::RuntimeCallExt>,
) -> Result<Balance, DispatchError>;

/// Submit an extrinsic mutating the state when the block is finalized
fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCall>) -> DispatchResult;
fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCallExt>) -> DispatchResult;

/// Pass any number of blocks
fn pass(&mut self, blocks: Blocks<T>) {
Expand Down Expand Up @@ -123,7 +123,7 @@ pub mod utils {
/// To create and submit an extrinsic, see `submit()`
pub fn create_extrinsic<T: Runtime>(
who: Keyring,
call: impl Into<T::RuntimeCall>,
call: impl Into<T::RuntimeCallExt>,
nonce: Index,
) -> <T::Block as Block>::Extrinsic {
let runtime_call = call.into();
Expand Down
4 changes: 2 additions & 2 deletions runtime/integration-tests/src/generic/envs/fudge_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ impl<T: Runtime + FudgeSupport> Env<T> for FudgeEnv<T> {
fn submit_now(
&mut self,
_who: Keyring,
_call: impl Into<T::RuntimeCall>,
_call: impl Into<T::RuntimeCallExt>,
) -> Result<Balance, DispatchError> {
unimplemented!("FudgeEnv does not support submit_now() try submit_later()")
}

fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCall>) -> DispatchResult {
fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCallExt>) -> DispatchResult {
let nonce = *self.nonce_storage.entry(who).or_default();

let extrinsic = self.state(|| utils::create_extrinsic::<T>(who, call, nonce));
Expand Down
10 changes: 5 additions & 5 deletions runtime/integration-tests/src/generic/envs/runtime_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::{
/// without the usage of a client.
pub struct RuntimeEnv<T: Runtime> {
ext: Rc<RefCell<sp_io::TestExternalities>>,
pending_extrinsics: Vec<(Keyring, T::RuntimeCall)>,
pending_extrinsics: Vec<(Keyring, T::RuntimeCallExt)>,
_config: PhantomData<T>,
}

Expand All @@ -53,7 +53,7 @@ impl<T: Runtime> Env<T> for RuntimeEnv<T> {
fn submit_now(
&mut self,
who: Keyring,
call: impl Into<T::RuntimeCall>,
call: impl Into<T::RuntimeCallExt>,
) -> Result<Balance, DispatchError> {
let extrinsic = self.state(|| {
let nonce = frame_system::Pallet::<T>::account(who.to_account_id()).nonce;
Expand All @@ -74,7 +74,7 @@ impl<T: Runtime> Env<T> for RuntimeEnv<T> {
Ok(fee)
}

fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCall>) -> DispatchResult {
fn submit_later(&mut self, who: Keyring, call: impl Into<T::RuntimeCallExt>) -> DispatchResult {
self.pending_extrinsics.push((who, call.into()));
Ok(())
}
Expand Down Expand Up @@ -145,7 +145,7 @@ impl<T: Runtime> RuntimeEnv<T> {
}
}

fn cumulus_inherent(i: BlockNumber) -> T::RuntimeCall {
fn cumulus_inherent(i: BlockNumber) -> T::RuntimeCallExt {
let mut inherent_data = InherentData::default();

let sproof_builder = RelayStateSproofBuilder::default();
Expand Down Expand Up @@ -176,7 +176,7 @@ impl<T: Runtime> RuntimeEnv<T> {
.into()
}

fn timestamp_inherent(timestamp: u64) -> T::RuntimeCall {
fn timestamp_inherent(timestamp: u64) -> T::RuntimeCallExt {
let mut inherent_data = InherentData::default();

let timestamp_inherent = Timestamp::new(timestamp);
Expand Down
5 changes: 2 additions & 3 deletions runtime/integration-tests/src/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ pub mod envs {
pub mod runtime_env;
}
pub mod runtime;
pub mod utils {
pub mod genesis;
}
pub mod utils;

// Test cases
mod cases {
mod example;
mod loans;
}

use runtime::{Runtime, RuntimeKind};
Expand Down
101 changes: 96 additions & 5 deletions runtime/integration-tests/src/generic/utils/genesis.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
use std::{collections::BTreeMap, marker::PhantomData};

use cfg_primitives::Balance;
use cfg_types::tokens::{AssetMetadata, CurrencyId, CustomMetadata};
use codec::Encode;
use frame_support::traits::GenesisBuild;
use sp_runtime::Storage;

use crate::generic::runtime::Runtime;
use crate::{generic::runtime::Runtime, utils::accounts::default_accounts};

#[derive(Default)]
pub struct Genesis {
pub struct Genesis<T> {
storage: Storage,
_config: PhantomData<T>,
}

impl<T> Default for Genesis<T> {
fn default() -> Self {
Self {
storage: Default::default(),
_config: Default::default(),
}
}
}

impl Genesis {
pub fn add<T: Runtime>(mut self, builder: impl GenesisBuild<T>) -> Genesis {
impl<T: Runtime> Genesis<T> {
pub fn add(mut self, builder: impl GenesisBuild<T>) -> Self {
builder.assimilate_storage(&mut self.storage).unwrap();
self
}
Expand All @@ -18,3 +32,80 @@ impl Genesis {
self.storage
}
}

pub fn balances<T: Runtime>(balance: Balance) -> impl GenesisBuild<T> {
pallet_balances::GenesisConfig::<T> {
balances: default_accounts()
.into_iter()
.map(|keyring| (keyring.id(), balance))
.collect(),
}
}

pub fn tokens<T: Runtime>(values: Vec<(CurrencyId, Balance)>) -> impl GenesisBuild<T> {
orml_tokens::GenesisConfig::<T> {
balances: default_accounts()
.into_iter()
.map(|keyring| {
values
.clone()
.into_iter()
.map(|(curency_id, balance)| (keyring.id(), curency_id, balance))
.collect::<Vec<_>>()
})
.flatten()
.collect(),
}
}

pub const MUSD_DECIMALS: u32 = 6;
pub const MUSD_UNIT: Balance = 10u128.pow(MUSD_DECIMALS);
pub const MUSD_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(1);

pub const AUSD_DECIMALS: u32 = 12;
pub const AUSD_UNIT: Balance = 10u128.pow(AUSD_DECIMALS);
pub const AUSD_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(2);

pub fn assets<T: Runtime>(currency_ids: Vec<CurrencyId>) -> impl GenesisBuild<T> {
let assets = BTreeMap::from([
(
MUSD_CURRENCY_ID,
AssetMetadata {
decimals: MUSD_DECIMALS,
name: "Mock USD".as_bytes().to_vec(),
symbol: "MUSD".as_bytes().to_vec(),
existential_deposit: 0,
location: None,
additional: CustomMetadata {
pool_currency: true,
..Default::default()
},
}
.encode(),
),
(
AUSD_CURRENCY_ID,
AssetMetadata {
decimals: 12,
name: "Acala Dollar".as_bytes().to_vec(),
symbol: "AUSD".as_bytes().to_vec(),
existential_deposit: 0,
location: None,
additional: CustomMetadata {
pool_currency: true,
..Default::default()
},
}
.encode(),
),
// Add new currencies here
]);

orml_asset_registry::GenesisConfig::<T> {
assets: currency_ids
.into_iter()
.map(|id| (id, assets.get(&id).unwrap().clone()))
.collect(),
last_asset_id: Default::default(), // It seems deprecated
}
}
84 changes: 84 additions & 0 deletions runtime/integration-tests/src/generic/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Divide this utilties into files when they grow

use cfg_primitives::{Balance, CollectionId, ItemId, Moment, PoolId, TrancheId};
use cfg_types::{
permissions::{PermissionScope, PoolRole, Role},
tokens::CurrencyId,
};
use frame_system::RawOrigin;
use sp_runtime::{traits::StaticLookup, AccountId32};
pub mod genesis;

use crate::generic::runtime::Runtime;

pub fn give_nft_to<T: Runtime>(
dest: AccountId32,
(collection_id, item_id): (CollectionId, ItemId),
) {
pallet_uniques::Pallet::<T>::force_create(
RawOrigin::Root.into(),
collection_id,
T::Lookup::unlookup(dest.clone()),
true,
)
.unwrap();

pallet_uniques::Pallet::<T>::mint(
RawOrigin::Signed(dest.clone()).into(),
collection_id,
item_id,
T::Lookup::unlookup(dest),
)
.unwrap()
}

pub fn give_balance_to<T: Runtime>(dest: AccountId32, amount: Balance) {
let data = pallet_balances::Account::<T>::get(dest.clone());
pallet_balances::Pallet::<T>::set_balance(
RawOrigin::Root.into(),
T::Lookup::unlookup(dest),
data.free + amount,
data.reserved,
)
.unwrap();
}

pub fn give_token_to<T: Runtime>(dest: AccountId32, currency_id: CurrencyId, amount: Balance) {
let data = orml_tokens::Accounts::<T>::get(dest.clone(), currency_id);
orml_tokens::Pallet::<T>::set_balance(
RawOrigin::Root.into(),
T::Lookup::unlookup(dest),
currency_id,
data.free + amount,
data.reserved,
)
.unwrap();
}

pub fn give_investor_role<T: Runtime>(
investor: AccountId32,
pool_id: PoolId,
tranche_id: TrancheId,
) {
let role = Role::PoolRole(PoolRole::TrancheInvestor(tranche_id, Moment::MAX));
pallet_permissions::Pallet::<T>::add(
RawOrigin::Root.into(),
role,
investor,
PermissionScope::Pool(pool_id),
role,
)
.unwrap();
}

pub fn give_borrower_role<T: Runtime>(borrower: AccountId32, pool_id: PoolId) {
let role = Role::PoolRole(PoolRole::Borrower);
pallet_permissions::Pallet::<T>::add(
RawOrigin::Root.into(),
role,
borrower,
PermissionScope::Pool(pool_id),
role,
)
.unwrap();
}
5 changes: 5 additions & 0 deletions runtime/integration-tests/src/utils/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ impl Keyring {
self.public().0.into()
}

/// Shorter alias for `to_account_id()`
pub fn id(self) -> AccountId32 {
self.to_account_id()
}

pub fn sign(self, msg: &[u8]) -> Signature {
Pair::from(self).sign(msg)
}
Expand Down

0 comments on commit bf6269a

Please sign in to comment.