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

feat: add freeze & unfreeze extrinsics #1947

Merged
merged 20 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions libs/types/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub enum PoolRole<TrancheId = [u8; 16]> {
LoanAdmin,
TrancheInvestor(TrancheId, Seconds),
PODReadAccess,
FrozenTrancheInvestor(TrancheId),
}

#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, TypeInfo, Debug)]
Expand Down Expand Up @@ -110,6 +111,12 @@ pub struct PermissionedCurrencyHolderInfo {
pub struct TrancheInvestorInfo<TrancheId> {
tranche_id: TrancheId,
permissioned_till: Seconds,
is_frozen: bool,
lemunozm marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Encode, Decode, TypeInfo, Debug, Clone, Eq, PartialEq, MaxEncodedLen)]
pub struct FrozenTrancheInvestorInfo<TrancheId> {
tranche_id: TrancheId,
}

#[derive(Encode, Decode, TypeInfo, Debug, Clone, Eq, PartialEq, MaxEncodedLen)]
Expand Down Expand Up @@ -214,6 +221,7 @@ where
PoolRole::PODReadAccess => {
self.pool_admin.contains(PoolAdminRoles::POD_READ_ACCESS)
}
PoolRole::FrozenTrancheInvestor(id) => self.tranche_investor.contains_frozen(id),
},
Role::PermissionedCurrencyRole(permissioned_currency_role) => {
match permissioned_currency_role {
Expand Down Expand Up @@ -255,6 +263,7 @@ where
PoolRole::PODReadAccess => {
Ok(self.pool_admin.remove(PoolAdminRoles::POD_READ_ACCESS))
}
PoolRole::FrozenTrancheInvestor(id) => self.tranche_investor.unfreeze(id),
},
Role::PermissionedCurrencyRole(permissioned_currency_role) => {
match permissioned_currency_role {
Expand Down Expand Up @@ -289,6 +298,7 @@ where
PoolRole::PODReadAccess => {
Ok(self.pool_admin.insert(PoolAdminRoles::POD_READ_ACCESS))
}
PoolRole::FrozenTrancheInvestor(id) => self.tranche_investor.freeze(id),
},
Role::PermissionedCurrencyRole(permissioned_currency_role) => {
match permissioned_currency_role {
Expand Down Expand Up @@ -410,6 +420,12 @@ where
})
}

pub fn contains_frozen(&self, tranche: TrancheId) -> bool {
self.info
.iter()
.any(|info| info.tranche_id == tranche && info.is_frozen)
}

#[allow(clippy::result_unit_err)]
pub fn remove(&mut self, tranche: TrancheId, delta: Seconds) -> Result<(), ()> {
if let Some(index) = self.info.iter().position(|info| info.tranche_id == tranche) {
Expand Down Expand Up @@ -443,10 +459,27 @@ where
.try_push(TrancheInvestorInfo {
tranche_id: tranche,
permissioned_till: validity,
is_frozen: false,
})
.map_err(|_| ())
}
}

#[allow(clippy::result_unit_err)]
pub fn freeze(&mut self, tranche: TrancheId) -> Result<(), ()> {
if let Some(investor) = self.info.iter_mut().find(|t| t.tranche_id == tranche) {
investor.is_frozen = true;
}
Ok(())
}

#[allow(clippy::result_unit_err)]
pub fn unfreeze(&mut self, tranche: TrancheId) -> Result<(), ()> {
if let Some(investor) = self.info.iter_mut().find(|t| t.tranche_id == tranche) {
investor.is_frozen = false;
}
Ok(())
}
}

#[cfg(test)]
Expand Down
7 changes: 7 additions & 0 deletions pallets/investments/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,13 @@ impl<T: Config> Pallet<T> {
who: T::AccountId,
investment_id: T::InvestmentId,
) -> DispatchResultWithPostInfo {
// Frozen investors must not be able to collect tranche tokens
T::PreConditions::check(OrderType::Investment {
who: who.clone(),
investment_id,
amount: Default::default(),
})?;

let _ = T::Accountant::info(investment_id).map_err(|_| Error::<T>::UnknownInvestment)?;
let (collected_investment, post_dispatch_info) = InvestOrders::<T>::try_mutate(
&who,
Expand Down
26 changes: 21 additions & 5 deletions pallets/investments/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use sp_std::{
};

pub use crate as pallet_investments;
use crate::OrderType;

pub type AccountId = u64;

Expand Down Expand Up @@ -134,18 +135,30 @@ impl pallet_investments::Config for Runtime {
type CollectedRedemptionHook = NoopCollectHook;
type InvestmentId = InvestmentId;
type MaxOutstandingCollects = MaxOutstandingCollect;
type PreConditions = Always;
type PreConditions = AlwaysWithOneException;
type RuntimeEvent = RuntimeEvent;
type Tokens = OrmlTokens;
type WeightInfo = ();
}

pub struct Always;
impl<T> PreConditions<T> for Always {
pub struct AlwaysWithOneException;
impl<T> PreConditions<T> for AlwaysWithOneException
where
T: Into<OrderType<AccountId, InvestmentId, Balance>> + Clone,
{
type Result = DispatchResult;

fn check(_: T) -> Self::Result {
Ok(())
fn check(order: T) -> Self::Result {
match order.clone().into() {
OrderType::Investment { who, .. } | OrderType::Redemption { who, .. }
if who == NOT_INVESTOR =>
{
Err(DispatchError::Other(
"PreCondition mock fails on u64::MAX account on purpose",
))
}
_ => Ok(()),
}
lemunozm marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down Expand Up @@ -188,6 +201,9 @@ pub const UNKNOWN_INVESTMENT: InvestmentId = (1, TRANCHE_ID_0);
/// The currency id for the AUSD token
pub const AUSD_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(1);

/// The account for which the pre-condition mock fails
pub(crate) const NOT_INVESTOR: u64 = u64::MAX;

impl TestExternalitiesBuilder {
// Build a genesis storage key/value store
pub(crate) fn build() -> TestExternalities {
Expand Down
21 changes: 21 additions & 0 deletions pallets/investments/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2955,3 +2955,24 @@ fn collecting_over_max_works() {
}
})
}

#[test]
fn collecting_investment_without_preconditions_fails() {
TestExternalitiesBuilder::build().execute_with(|| {
assert_noop!(
Investments::collect_investments(RuntimeOrigin::signed(NOT_INVESTOR), INVESTMENT_0_0),
DispatchError::Other("PreCondition mock fails on u64::MAX account on purpose")
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit - move this error to a const and use it in the mock and tests.

);
})
}

/// NOTE: Collecting redemptions does not check pre-conditions
Copy link
Contributor Author

Choose a reason for hiding this comment

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

#[test]
fn collecting_redemption_without_preconditions_success() {
TestExternalitiesBuilder::build().execute_with(|| {
assert_ok!(Investments::collect_redemptions(
RuntimeOrigin::signed(NOT_INVESTOR),
INVESTMENT_0_0
),);
})
}
134 changes: 53 additions & 81 deletions pallets/liquidity-pools/src/defensive_weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,122 +19,94 @@ pub trait WeightInfo {
fn update_member() -> Weight;
fn transfer() -> Weight;
fn set_domain_router() -> Weight;
fn add_currency() -> Weight;
fn allow_investment_currency() -> Weight;
fn disallow_investment_currency() -> Weight;
fn schedule_upgrade() -> Weight;
fn cancel_upgrade() -> Weight;
fn update_tranche_token_metadata() -> Weight;
fn freeze_investor() -> Weight;
fn unfreeze_investor() -> Weight;
}

// NOTE: We use temporary weights here. `execute_epoch` is by far our heaviest
// extrinsic. N denotes the number of tranches. 4 is quite heavy and
// should be enough.
const N: u64 = 4;

/// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
/// be replaced with real benchmark soon.

fn default_defensive_weight() -> Weight {
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
}
lemunozm marked this conversation as resolved.
Show resolved Hide resolved

impl WeightInfo for () {
fn set_domain_router() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn add_pool() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn add_tranche() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn update_token_price() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn update_member() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn transfer() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn schedule_upgrade() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn cancel_upgrade() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn update_tranche_token_metadata() -> Weight {
// NOTE: Defensive hardcoded weight taken from pool_system::execute_epoch. Will
// be replaced with real benchmark soon.
Weight::from_parts(124_979_771, 19974)
.saturating_add(Weight::from_parts(58_136_652, 0).saturating_mul(N))
.saturating_add(RocksDbWeight::get().reads(8))
.saturating_add(RocksDbWeight::get().reads((7_u64).saturating_mul(N)))
.saturating_add(RocksDbWeight::get().writes(8))
.saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(N)))
.saturating_add(Weight::from_parts(0, 17774).saturating_mul(N))
default_defensive_weight()
}

fn freeze_investor() -> Weight {
default_defensive_weight()
}

fn unfreeze_investor() -> Weight {
default_defensive_weight()
}

fn add_currency() -> Weight {
// Reads: 2x AssetRegistry
// Writes: MessageNonceStore, MessageQueue
RocksDbWeight::get().reads_writes(2, 2)
}

fn allow_investment_currency() -> Weight {
// Reads: 2x AssetRegistry
// Writes: MessageNonceStore, MessageQueue
RocksDbWeight::get().reads_writes(2, 2)
}

fn disallow_investment_currency() -> Weight {
// Reads: 2x AssetRegistry
// Writes: MessageNonceStore, MessageQueue
RocksDbWeight::get().reads_writes(2, 2)
}
}
23 changes: 7 additions & 16 deletions pallets/liquidity-pools/src/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,8 @@
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

use cfg_traits::{
investments::ForeignInvestment, liquidity_pools::OutboundMessageHandler, Permissions,
TimeAsSecs,
};
use cfg_types::{
domain_address::{Domain, DomainAddress},
permissions::{PermissionScope, PoolRole, Role},
};
use cfg_traits::{investments::ForeignInvestment, liquidity_pools::OutboundMessageHandler};
use cfg_types::domain_address::{Domain, DomainAddress};
use frame_support::{
ensure,
traits::{fungibles::Mutate, tokens::Preservation, OriginTrait},
Expand Down Expand Up @@ -69,14 +63,11 @@ where
let local_representation_of_receiver =
T::DomainAddressToAccountId::convert(receiver.clone());

ensure!(
T::Permission::has(
PermissionScope::Pool(pool_id),
local_representation_of_receiver.clone(),
Role::PoolRole(PoolRole::TrancheInvestor(tranche_id, T::Time::now())),
),
Error::<T>::UnauthorizedTransfer
);
Self::validate_investor_can_transfer(
local_representation_of_receiver.clone(),
pool_id,
tranche_id,
)?;

let invest_id = Self::derive_invest_id(pool_id, tranche_id)?;

Expand Down
Loading
Loading