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: emission proposal type #41

Merged
merged 4 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ gen-spec-file env: gen-base-spec

@echo "Spec file generated at: tmp/spec/{{env}}.json"

run-benchmarks:
cargo build -r --features runtime-benchmarks
# ./target/release/torus-node benchmark pallet --pallet pallet_torus0 --chain dev --extrinsic "*" --steps 50 --repeat 20 --output pallets/torus0/src/weights.rs --template=./.maintain/frame-weight-template.hbs
./target/release/torus-node benchmark pallet --pallet pallet_governance --chain dev --extrinsic "*" --steps 50 --repeat 20 --output pallets/governance/src/weights.rs --template=./.maintain/frame-weight-template.hbs
./target/release/torus-node benchmark pallet --pallet pallet_emission0 --chain dev --extrinsic "*" --steps 50 --repeat 20 --output pallets/emission0/src/weights.rs --template=./.maintain/frame-weight-template.hbs


# Github Actions

run-workflows:
Expand Down
3 changes: 3 additions & 0 deletions pallets/emission0/src/benchmarks.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use pallet_governance_api::GovernanceApi;
use pallet_torus0_api::Torus0Api;
use polkadot_sdk::{
frame_benchmarking::{account, benchmarks},
Expand All @@ -12,6 +13,8 @@ benchmarks! {
let module_key: T::AccountId = account("ModuleKey", 0, 2);
let module_key2: T::AccountId = account("ModuleKey2", 0, 3);

<T::Governance>::set_allocator(&module_key2);

<T::Torus>::force_register_agent(&module_key, vec![], vec![], vec![])?;
<T::Torus>::force_register_agent(&module_key2, vec![], vec![], vec![])?;

Expand Down
46 changes: 27 additions & 19 deletions pallets/emission0/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 43.0.0
//! DATE: 2025-01-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `Luizs-MacBook-Pro.local`, CPU: `<UNKNOWN>`
//! HOSTNAME: `MacBook-Pro-de-Joao.local`, CPU: `<UNKNOWN>`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024`

// Executed Command:
// ./target/release/torus-node
// benchmark
// pallet
// --chain
// dev
// --pallet
// pallet_emission0
// --chain
// dev
// --extrinsic
// *
// --steps
Expand Down Expand Up @@ -46,8 +46,12 @@ pub trait WeightInfo {
/// Weights for `pallet_emission0` using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `Governance::Allocators` (r:1 w:0)
/// Proof: `Governance::Allocators` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `MaxEncodedLen`)
/// Storage: `Emission0::MaxAllowedWeights` (r:1 w:0)
/// Proof: `Emission0::MaxAllowedWeights` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`)
/// Storage: `Emission0::WeightControlDelegation` (r:1 w:0)
/// Proof: `Emission0::WeightControlDelegation` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`)
/// Storage: `Torus0::Agents` (r:2 w:0)
/// Proof: `Torus0::Agents` (`max_values`: None, `max_size`: Some(849), added: 3324, mode: `MaxEncodedLen`)
/// Storage: `Torus0::StakedBy` (r:1 w:0)
Expand All @@ -58,11 +62,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `Emission0::ConsensusMembers` (`max_values`: None, `max_size`: Some(4294967295), added: 2474, mode: `MaxEncodedLen`)
fn set_weights() -> Weight {
// Proof Size summary in bytes:
// Measured: `277`
// Measured: `339`
// Estimated: `7638`
// Minimum execution time: 18_000_000 picoseconds.
Weight::from_parts(20_000_000, 7638)
.saturating_add(T::DbWeight::get().reads(6_u64))
// Minimum execution time: 33_000_000 picoseconds.
Weight::from_parts(34_000_000, 7638)
.saturating_add(T::DbWeight::get().reads(8_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: `Torus0::Agents` (r:2 w:0)
Expand All @@ -73,8 +77,8 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Proof Size summary in bytes:
// Measured: `168`
// Estimated: `7638`
// Minimum execution time: 12_000_000 picoseconds.
Weight::from_parts(12_000_000, 7638)
// Minimum execution time: 17_000_000 picoseconds.
Weight::from_parts(18_000_000, 7638)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
Expand All @@ -84,17 +88,21 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Proof Size summary in bytes:
// Measured: `199`
// Estimated: `3529`
// Minimum execution time: 7_000_000 picoseconds.
Weight::from_parts(8_000_000, 3529)
// Minimum execution time: 10_000_000 picoseconds.
Weight::from_parts(11_000_000, 3529)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
}

// For backwards compatibility and tests.
impl WeightInfo for () {
/// Storage: `Governance::Allocators` (r:1 w:0)
/// Proof: `Governance::Allocators` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `MaxEncodedLen`)
/// Storage: `Emission0::MaxAllowedWeights` (r:1 w:0)
/// Proof: `Emission0::MaxAllowedWeights` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`)
/// Storage: `Emission0::WeightControlDelegation` (r:1 w:0)
/// Proof: `Emission0::WeightControlDelegation` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`)
/// Storage: `Torus0::Agents` (r:2 w:0)
/// Proof: `Torus0::Agents` (`max_values`: None, `max_size`: Some(849), added: 3324, mode: `MaxEncodedLen`)
/// Storage: `Torus0::StakedBy` (r:1 w:0)
Expand All @@ -105,11 +113,11 @@ impl WeightInfo for () {
/// Proof: `Emission0::ConsensusMembers` (`max_values`: None, `max_size`: Some(4294967295), added: 2474, mode: `MaxEncodedLen`)
fn set_weights() -> Weight {
// Proof Size summary in bytes:
// Measured: `277`
// Measured: `339`
// Estimated: `7638`
// Minimum execution time: 18_000_000 picoseconds.
Weight::from_parts(20_000_000, 7638)
.saturating_add(RocksDbWeight::get().reads(6_u64))
// Minimum execution time: 33_000_000 picoseconds.
Weight::from_parts(34_000_000, 7638)
.saturating_add(RocksDbWeight::get().reads(8_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: `Torus0::Agents` (r:2 w:0)
Expand All @@ -120,8 +128,8 @@ impl WeightInfo for () {
// Proof Size summary in bytes:
// Measured: `168`
// Estimated: `7638`
// Minimum execution time: 12_000_000 picoseconds.
Weight::from_parts(12_000_000, 7638)
// Minimum execution time: 17_000_000 picoseconds.
Weight::from_parts(18_000_000, 7638)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
Expand All @@ -131,8 +139,8 @@ impl WeightInfo for () {
// Proof Size summary in bytes:
// Measured: `199`
// Estimated: `3529`
// Minimum execution time: 7_000_000 picoseconds.
Weight::from_parts(8_000_000, 3529)
// Minimum execution time: 10_000_000 picoseconds.
Weight::from_parts(11_000_000, 3529)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
Expand Down
2 changes: 2 additions & 0 deletions pallets/governance/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ pub trait GovernanceApi<AccountId> {
fn is_whitelisted(key: &AccountId) -> bool;

fn ensure_allocator(key: &AccountId) -> DispatchResult;

fn set_allocator(key: &AccountId);
}
14 changes: 12 additions & 2 deletions pallets/governance/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn create_application<T: Config>(module_key: &T::AccountId) {
let min_data_len = T::MinApplicationDataLength::get();
let data = vec![0; min_data_len as usize];

application::submit_application::<T>(module_key.clone(), module_key.clone(), data)
application::submit_application::<T>(module_key.clone(), module_key.clone(), data, false)
.expect("failed to submit application");
}

Expand Down Expand Up @@ -66,7 +66,7 @@ benchmarks! {

let min_data_len = T::MinApplicationDataLength::get();
let data = vec![0; min_data_len as usize];
}: _(RawOrigin::Signed(module_key.clone()), module_key.clone(), data)
}: _(RawOrigin::Signed(module_key.clone()), module_key.clone(), data, false)

accept_application {
let module_key: T::AccountId = account("ModuleKey", 0, 2);
Expand Down Expand Up @@ -193,4 +193,14 @@ benchmarks! {
disable_vote_delegation {
let module_key: T::AccountId = account("ModuleKey", 0, 2);
}: _(RawOrigin::Signed(module_key))

add_emission_proposal {
let module_key: T::AccountId = account("ModuleKey", 0, 2);
let data = vec![0];

let config = crate::GlobalGovernanceConfig::<T>::get();
let cost = config.proposal_cost;
let _ = <T as crate::Config>::Currency::deposit_creating(&module_key, cost);

}: _(RawOrigin::Signed(module_key.clone()), Percent::from_parts(40), Percent::from_parts(40), data)
}
23 changes: 23 additions & 0 deletions pallets/governance/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,23 @@ pub mod pallet {
let delegator = ensure_signed(origin)?;
voting::disable_delegation::<T>(delegator)
}

#[pallet::call_index(17)]
#[pallet::weight((<T as Config>::WeightInfo::add_emission_proposal(), DispatchClass::Normal, Pays::Yes))]
pub fn add_emission_proposal(
origin: OriginFor<T>,
recycling_percentage: Percent,
treasury_percentage: Percent,
data: Vec<u8>,
) -> DispatchResult {
let proposer = ensure_signed(origin)?;
proposal::add_emission_proposal::<T>(
proposer,
recycling_percentage,
treasury_percentage,
data,
)
}
}

#[pallet::event]
Expand Down Expand Up @@ -425,6 +442,8 @@ pub mod pallet {
InvalidMinWeightControlFee,
/// Invalid minimum staking fee in proposal
InvalidMinStakingFee,
/// Invalid params given to Emission proposal
InvalidEmissionProposalData,
}
}

Expand All @@ -444,4 +463,8 @@ impl<T: Config> pallet_governance_api::GovernanceApi<T::AccountId> for Pallet<T>
fn ensure_allocator(key: &T::AccountId) -> DispatchResult {
crate::roles::ensure_allocator::<T>(key)
}

fn set_allocator(key: &T::AccountId) {
crate::Allocators::<T>::insert(key, ());
}
}
76 changes: 62 additions & 14 deletions pallets/governance/src/proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use codec::{Decode, Encode, MaxEncodedLen};
use polkadot_sdk::frame_election_provider_support::Get;
use polkadot_sdk::frame_support::traits::Currency;
use polkadot_sdk::frame_support::traits::WithdrawReasons;
use polkadot_sdk::polkadot_sdk_frame::traits::CheckedAdd;
use polkadot_sdk::sp_runtime::SaturatedConversion;
use polkadot_sdk::sp_std::{collections::btree_set::BTreeSet, vec::Vec};
use polkadot_sdk::{
Expand All @@ -24,7 +25,7 @@ use substrate_fixed::types::I92F36;

pub type ProposalId = u64;

#[derive(DebugNoBound, TypeInfo, Decode, Encode, MaxEncodedLen)]
#[derive(Clone, DebugNoBound, TypeInfo, Decode, Encode, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct Proposal<T: crate::Config> {
pub id: ProposalId,
Expand All @@ -44,6 +45,13 @@ impl<T: crate::Config> Proposal<T> {
matches!(self.status, ProposalStatus::Open { .. })
}

pub fn execution_block(&self) -> Block {
match self.data {
ProposalData::Emission { .. } => self.creation_block + 21_600,
_ => self.expiration_block,
}
}

/// Marks a proposal as accepted and overrides the storage value.
pub fn accept(
mut self,
Expand Down Expand Up @@ -250,11 +258,15 @@ impl<T: crate::Config> GlobalParamsData<T> {
}
}

#[derive(DebugNoBound, TypeInfo, Decode, Encode, MaxEncodedLen, PartialEq, Eq)]
#[derive(Clone, DebugNoBound, TypeInfo, Decode, Encode, MaxEncodedLen, PartialEq, Eq)]
#[scale_info(skip_type_params(T))]
pub enum ProposalData<T: crate::Config> {
GlobalParams(GlobalParamsData<T>),
GlobalCustom,
Emission {
recycling_percentage: Percent,
treasury_percentage: Percent,
},
TransferDaoTreasury {
account: AccountIdOf<T>,
amount: BalanceOf<T>,
Expand All @@ -265,6 +277,7 @@ impl<T: crate::Config> ProposalData<T> {
#[must_use]
pub fn required_stake(&self) -> Percent {
match self {
Self::Emission { .. } => Percent::from_parts(10),
Self::GlobalCustom | Self::TransferDaoTreasury { .. } => Percent::from_parts(50),
Self::GlobalParams { .. } => Percent::from_parts(40),
}
Expand Down Expand Up @@ -312,6 +325,27 @@ pub fn add_dao_treasury_transfer_proposal<T: crate::Config>(
add_proposal::<T>(proposer, data, metadata)
}

pub fn add_emission_proposal<T: crate::Config>(
proposer: AccountIdOf<T>,
recycling_percentage: Percent,
treasury_percentage: Percent,
metadata: Vec<u8>,
) -> DispatchResult {
ensure!(
recycling_percentage
.checked_add(&treasury_percentage)
.is_some(),
crate::Error::<T>::InvalidEmissionProposalData
);

let data = ProposalData::<T>::Emission {
recycling_percentage,
treasury_percentage,
};

add_proposal::<T>(proposer, data, metadata)
}

fn add_proposal<T: crate::Config>(
proposer: AccountIdOf<T>,
data: ProposalData<T>,
Expand Down Expand Up @@ -442,14 +476,38 @@ fn tick_proposal<T: crate::Config>(
*stake_for = stake_for_sum;
*stake_against = stake_against_sum;
}
Proposals::<T>::set(proposal.id, Some(proposal));
Proposals::<T>::set(proposal.id, Some(proposal.clone()));
}

if block_number < proposal.execution_block() {
return Ok(());
}

let total_stake = stake_for_sum.saturating_add(stake_against_sum);
let minimal_stake_to_execute =
get_minimal_stake_to_execute_with_percentage::<T>(proposal.data.required_stake());

if total_stake >= minimal_stake_to_execute {
create_unrewarded_proposal::<T>(proposal.id, block_number, votes_for, votes_against);
if stake_against_sum > stake_for_sum {
proposal.refuse(block_number, stake_for_sum, stake_against_sum)
} else {
proposal.accept(block_number, stake_for_sum, stake_against_sum)
}
} else if block_number >= proposal.expiration_block {
create_unrewarded_proposal::<T>(proposal.id, block_number, votes_for, votes_against);
proposal.expire(block_number)
} else {
Ok(())
}
}

fn create_unrewarded_proposal<T: crate::Config>(
proposal_id: u64,
block_number: Block,
votes_for: Vec<(AccountIdOf<T>, BalanceOf<T>)>,
votes_against: Vec<(AccountIdOf<T>, BalanceOf<T>)>,
) {
let mut reward_votes_for = BoundedBTreeMap::new();
for (key, value) in votes_for {
reward_votes_for
Expand All @@ -469,23 +527,13 @@ fn tick_proposal<T: crate::Config>(
}

UnrewardedProposals::<T>::insert(
proposal.id,
proposal_id,
UnrewardedProposal::<T> {
block: block_number,
votes_for: reward_votes_for,
votes_against: reward_votes_against,
},
);

if total_stake >= minimal_stake_to_execute {
if stake_against_sum > stake_for_sum {
proposal.refuse(block_number, stake_for_sum, stake_against_sum)
} else {
proposal.accept(block_number, stake_for_sum, stake_against_sum)
}
} else {
proposal.expire(block_number)
}
}

#[inline]
Expand Down
Loading