Skip to content

Commit

Permalink
Merge pull request #5103 from ignazio-bovo/feature/crt-constraints-pr…
Browse files Browse the repository at this point in the history
…oposal

Feature/crt constraints proposal
  • Loading branch information
mnaamani committed Apr 3, 2024
2 parents d6d184b + 3dc4539 commit 4268f95
Show file tree
Hide file tree
Showing 29 changed files with 875 additions and 502 deletions.
5 changes: 3 additions & 2 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 chain-metadata.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion query-node/chain-metadata/2003.json

Large diffs are not rendered by default.

31 changes: 31 additions & 0 deletions runtime-modules/project-token/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,30 @@ benchmarks! {
where_clause {
where T: Config
}
// Worst case scenario:
// all parameters needs to be updated
update_token_constraints {
let parameters = TokenConstraints {
max_yearly_rate: Some(YearlyRate(Permill::from_percent(15))),
min_amm_slope: Some(100u32.into()),
min_sale_duration: Some(10u32.into()),
min_revenue_split_duration: Some(10u32.into()),
min_revenue_split_time_to_start: Some(10u32.into()),
sale_platform_fee: Some(Permill::from_percent(1)),
amm_buy_tx_fees: Some(Permill::from_percent(1)),
amm_sell_tx_fees: Some(Permill::from_percent(1)),
bloat_bond: Some(1000u32.into()),
};
let origin = RawOrigin::Root;
}: _(origin, parameters.clone())
verify {

assert_last_event::<T>(
RawEvent::TokenConstraintsUpdated(
parameters
).into()
)
}

// Worst case scenario:
// - source_accout.vesting_schedules.len() is T::MaxVestingSchedulesPerAccountPerToken
Expand Down Expand Up @@ -791,4 +815,11 @@ mod tests {
assert_ok!(Token::test_benchmark_sell_on_amm());
});
}

#[test]
fn test_update_token_constraints() {
build_test_externalities(GenesisConfigBuilder::new_empty().build()).execute_with(|| {
assert_ok!(Token::test_benchmark_update_token_constraints());
});
}
}
12 changes: 9 additions & 3 deletions runtime-modules/project-token/src/events.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#![allow(clippy::unused_unit)]

use crate::types::{
AmmCurveOf, JoyBalanceOf, RevenueSplitId, TokenIssuanceParametersOf, TokenSaleId, TokenSaleOf,
TransferPolicyOf, ValidatedTransfersOf, YearlyRate,
AmmCurveOf, JoyBalanceOf, RevenueSplitId, TokenConstraintsOf, TokenIssuanceParametersOf,
TokenSaleId, TokenSaleOf, TransferPolicyOf, ValidatedTransfersOf, YearlyRate,
};
use common::MembershipTypes;
use frame_support::decl_event;
Expand All @@ -22,6 +22,7 @@ decl_event! {
ValidatedTransfers = ValidatedTransfersOf<T>,
TokenSale = TokenSaleOf<T>,
AmmCurve = AmmCurveOf<T>,
TokenConstraints = TokenConstraintsOf<T>

{
/// Token amount is transferred from src to dst
Expand Down Expand Up @@ -189,6 +190,11 @@ decl_event! {
/// Pallet Frozen status toggled
/// Params:
/// - new frozen status (true | false)
FrozenStatusUpdated(bool)
FrozenStatusUpdated(bool),

/// Governance parameters updated
/// Params:
/// - governance parameters
TokenConstraintsUpdated(TokenConstraints),
}
}
61 changes: 61 additions & 0 deletions runtime-modules/project-token/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ use traits::PalletToken;
use types::*;

pub mod weights;
pub use types::TokenConstraintsOf;
pub use weights::WeightInfo;

type WeightInfoToken<T> = <T as Config>::WeightInfo;
Expand Down Expand Up @@ -214,6 +215,66 @@ decl_module! {
/// Predefined errors.
type Error = Error<T>;

/// Allow Governance to Set constraints
/// Preconditions:
/// - origin is signed by `root`
/// PostConditions:
/// - governance parameters storage value set to the provided values
/// <weight>
///
/// ## Weight
/// `O (1)`
/// # </weight>
#[weight = WeightInfoToken::<T>::update_token_constraints()]
pub fn update_token_constraints(
origin,
parameters: TokenConstraintsOf<T>
) {
// update parameters via proposal
ensure_root(origin)?;

// == MUTATION SAFE ==

if let Some(new_max_yearly_rate) = parameters.max_yearly_rate {
MaxYearlyPatronageRate::put(new_max_yearly_rate);
}

if let Some(new_min_amm_slope) = parameters.min_amm_slope {
MinAmmSlopeParameter::<T>::put(new_min_amm_slope);
}

if let Some(new_min_sale_duration) = parameters.min_sale_duration {
MinSaleDuration::<T>::put(new_min_sale_duration);
}

if let Some(new_min_revenue_split_duration) = parameters.min_revenue_split_duration {
MinRevenueSplitDuration::<T>::put(new_min_revenue_split_duration);
}

if let Some(new_min_revenue_split_time_to_start) = parameters.min_revenue_split_time_to_start {
MinRevenueSplitTimeToStart::<T>::put(new_min_revenue_split_time_to_start);
}

if let Some(new_sale_platform_fee) = parameters.sale_platform_fee {
SalePlatformFee::put(new_sale_platform_fee);
}

if let Some(new_amm_buy_tx_fee) = parameters.amm_buy_tx_fees {
AmmBuyTxFees::put(new_amm_buy_tx_fee);
}

if let Some(new_amm_sell_tx_fee) = parameters.amm_sell_tx_fees {
AmmSellTxFees::put(new_amm_sell_tx_fee);
}

if let Some(new_bloat_bond) = parameters.bloat_bond {
BloatBond::<T>::put(new_bloat_bond);
}

Self::deposit_event(RawEvent::TokenConstraintsUpdated(parameters));

}

/// Allow to transfer from `src_member_id` account to the various `outputs` beneficiaries
/// in the specified amounts.
///
Expand Down
20 changes: 20 additions & 0 deletions runtime-modules/project-token/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use storage::{BagId, DataObjectCreationParameters};
use crate::{errors::Error, Config, RepayableBloatBondOf};

// trait "aliases"
// `BlockNumber` will be implemented as `u64` in the runtime configuration
pub trait BlockNumberTrait: Copy + AtLeast32BitUnsigned + Saturating + Default {}
impl<T: Copy + AtLeast32BitUnsigned + Saturating + Default> BlockNumberTrait for T {}

Expand All @@ -44,6 +45,21 @@ impl<T: BalanceTrait + FixedPointOperand + Sum> TokenBalanceTrait for T {}
pub trait JoyTokenBalanceTrait: BalanceTrait {}
impl<T: BalanceTrait> JoyTokenBalanceTrait for T {}

/// Parameer pack for governance constraints
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen)]
pub struct TokenConstraints<Balance, BlockNumber, JoyBalance> {
pub max_yearly_rate: Option<YearlyRate>,
pub min_amm_slope: Option<Balance>,
pub min_sale_duration: Option<BlockNumber>,
pub min_revenue_split_duration: Option<BlockNumber>,
pub min_revenue_split_time_to_start: Option<BlockNumber>,
pub sale_platform_fee: Option<Permill>,
pub amm_buy_tx_fees: Option<Permill>,
pub amm_sell_tx_fees: Option<Permill>,
pub bloat_bond: Option<JoyBalance>,
}

/// Source of tokens subject to vesting that were acquired by an account
/// either through purchase or during initial issuance
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -1677,3 +1693,7 @@ pub type AmmCurveOf<T> = AmmCurve<TokenBalanceOf<T>>;

/// Alias for the amm params
pub type AmmParamsOf<T> = AmmParams<TokenBalanceOf<T>>;

/// Alias for the governance parameters
pub type TokenConstraintsOf<T> =
TokenConstraints<TokenBalanceOf<T>, <T as frame_system::Config>::BlockNumber, JoyBalanceOf<T>>;
8 changes: 8 additions & 0 deletions runtime-modules/project-token/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub trait WeightInfo {
fn buy_on_amm_with_account_creation() -> Weight;
fn buy_on_amm_with_existing_account() -> Weight;
fn sell_on_amm() -> Weight;
fn update_token_constraints() -> Weight;
}

/// Weights for project_token using the Substrate node and recommended hardware.
Expand All @@ -64,6 +65,10 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Proof: Token PalletFrozen (max_values: Some(1), max_size: Some(1), added: 496, mode: MaxEncodedLen)
// Storage: Membership MembershipById (r:25 w:0)
// Proof: Membership MembershipById (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen)
fn update_token_constraints() -> Weight {
Weight::from_parts(0, 0)
}
// Storage: Membership MembershipById (r:2 w:0)
// Storage: Token TokenInfoById (r:1 w:1)
// Proof: Token TokenInfoById (max_values: None, max_size: Some(352), added: 2827, mode: MaxEncodedLen)
// Storage: Token AccountInfoByTokenAndMember (r:25 w:25)
Expand Down Expand Up @@ -331,4 +336,7 @@ impl WeightInfo for () {
fn sell_on_amm() -> Weight {
Weight::from_parts(0, 0)
}
fn update_token_constraints() -> Weight {
Weight::from_parts(0, 0)
}
}
2 changes: 2 additions & 0 deletions runtime-modules/proposals/codex/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ token = { package = 'pallet-project-token', default-features = false, path = '..
frame-benchmarking = { package = 'frame-benchmarking', default-features = false, git = 'https://github.com/joystream/substrate.git', rev = '1d0eefca86ef31b9e7727df01a6ed23ad65491e9', optional = true }

[dev-dependencies]
storage = { package = 'pallet-storage', default-features = false, path = '../../storage' }
sp-io = { package = 'sp-io', default-features = false, git = 'https://github.com/joystream/substrate.git', rev = '1d0eefca86ef31b9e7727df01a6ed23ad65491e9' }
sp-core = { package = 'sp-core', default-features = false, git = 'https://github.com/joystream/substrate.git', rev = '1d0eefca86ef31b9e7727df01a6ed23ad65491e9' }
sp-staking = { package = 'sp-staking', default-features = false, git = 'https://github.com/joystream/substrate.git', rev = '1d0eefca86ef31b9e7727df01a6ed23ad65491e9' }
Expand Down Expand Up @@ -75,6 +76,7 @@ std = [
'membership/std',
'content/std',
'token/std',
'storage/std',
'staking/std',
'scale-info/std',
'frame-election-provider-support/std',
Expand Down
14 changes: 8 additions & 6 deletions runtime-modules/proposals/codex/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ use working_group::{
const SEED: u32 = 0;
const MAX_KILOBYTES_METADATA: u32 = 100;

pub type BalanceOf<T> = <T as balances::Config>::Balance;

fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
let events = System::<T>::events();
let system_event: <T as frame_system::Config>::RuntimeEvent = generic_event.into();
Expand Down Expand Up @@ -65,7 +67,7 @@ fn member_funded_account<T: Config + membership::Config>() -> (T::AccountId, T::
let handle = handle_from_id(member_id.saturated_into());

// Give balance for buying membership
let _ = Balances::<T>::make_free_balance_be(&account_id, T::Balance::max_value());
let _ = Balances::<T>::make_free_balance_be(&account_id, BalanceOf::<T>::max_value());

let params = membership::BuyMembershipParameters {
root_account: account_id.clone(),
Expand All @@ -77,7 +79,7 @@ fn member_funded_account<T: Config + membership::Config>() -> (T::AccountId, T::

Membership::<T>::buy_membership(RawOrigin::Signed(account_id.clone()).into(), params).unwrap();

let _ = Balances::<T>::make_free_balance_be(&account_id, T::Balance::max_value());
let _ = Balances::<T>::make_free_balance_be(&account_id, BalanceOf::<T>::max_value());

Membership::<T>::add_staking_account_candidate(
RawOrigin::Signed(account_id.clone()).into(),
Expand Down Expand Up @@ -872,15 +874,15 @@ benchmarks! {
size: u64::MAX,
ipfs_content_id: Vec::from_iter((0..(i * 1000)).map(|v| u8::MAX))
},
expected_data_size_fee: u128::MAX.saturated_into::<T::Balance>(),
expected_data_object_state_bloat_bond: u128::MAX.saturated_into::<T::Balance>()
expected_data_size_fee: u128::MAX.saturated_into::<BalanceOf::<T>>(),
expected_data_object_state_bloat_bond: u128::MAX.saturated_into::<BalanceOf::<T>>()
};
let proposal_details = ProposalDetails::UpdateChannelPayouts(
content::UpdateChannelPayoutsParameters::<T> {
commitment: Some(commitment),
payload: Some(payload),
min_cashout_allowed: Some(u128::MAX.saturated_into::<T::Balance>()),
max_cashout_allowed: Some(u128::MAX.saturated_into::<T::Balance>()),
min_cashout_allowed: Some(u128::MAX.saturated_into::<BalanceOf::<T>>()),
max_cashout_allowed: Some(u128::MAX.saturated_into::<BalanceOf::<T>>()),
channel_cashouts_enabled: Some(true),
}
);
Expand Down
21 changes: 21 additions & 0 deletions runtime-modules/proposals/codex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pub trait Config:
+ proposals_discussion::Config
+ common::membership::MembershipTypes
+ staking::Config
+ token::Config
+ proposals_engine::Config
+ working_group::Config<ForumWorkingGroupInstance>
+ working_group::Config<StorageWorkingGroupInstance>
Expand Down Expand Up @@ -281,6 +282,11 @@ pub trait Config:
ProposalParameters<Self::BlockNumber, BalanceOf<Self>>,
>;

/// `Update pallet project token` proposal parameters
type UpdateTokenPalletTokenConstraints: Get<
ProposalParameters<Self::BlockNumber, BalanceOf<Self>>,
>;

/// `Decrease Council Budget` proposal parameters
type DecreaseCouncilBudgetProposalParameters: Get<
ProposalParameters<Self::BlockNumber, BalanceOf<Self>>,
Expand Down Expand Up @@ -520,6 +526,9 @@ decl_module! {
const SetPalletFozenStatusProposalParameters:
ProposalParameters<T::BlockNumber, BalanceOf<T>> = T::SetPalletFozenStatusProposalParameters::get();

/// pallet token governance parameters proposal
const UpdateTokenPalletTokenConstraints:
ProposalParameters<T::BlockNumber, BalanceOf<T>> = T::UpdateTokenPalletTokenConstraints::get();

/// Create a proposal, the type of proposal depends on the `proposal_details` variant
///
Expand Down Expand Up @@ -891,6 +900,9 @@ impl<T: Config> Module<T> {
ProposalDetails::SetPalletFozenStatus(..) => {
// Note: No checks for this proposal for now
}
ProposalDetails::UpdateTokenPalletTokenConstraints(..) => {
// Note: No checks for this proposal for now
}
ProposalDetails::DecreaseCouncilBudget(reduction_amount) => {
ensure!(
!(*reduction_amount).is_zero(),
Expand Down Expand Up @@ -967,6 +979,9 @@ impl<T: Config> Module<T> {
ProposalDetails::SetPalletFozenStatus(..) => {
T::SetPalletFozenStatusProposalParameters::get()
}
ProposalDetails::UpdateTokenPalletTokenConstraints(..) => {
T::UpdateTokenPalletTokenConstraints::get()
}
ProposalDetails::DecreaseCouncilBudget(..) => {
T::DecreaseCouncilBudgetProposalParameters::get()
}
Expand Down Expand Up @@ -1137,6 +1152,12 @@ impl<T: Config> Module<T> {
to_kb(description_length.saturated_into()),
)
}
ProposalDetails::UpdateTokenPalletTokenConstraints(..) => {
WeightInfoCodex::<T>::create_proposal_update_token_pallet_governance_parameters(
to_kb(title_length.saturated_into()),
to_kb(description_length.saturated_into()),
)
}
ProposalDetails::DecreaseCouncilBudget(..) => {
WeightInfoCodex::<T>::create_proposal_decrease_council_budget(
to_kb(title_length.saturated_into()),
Expand Down
Loading

0 comments on commit 4268f95

Please sign in to comment.