lib.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. //! # Proposals engine module
  2. //! Proposals `engine` module for the Joystream platform. Version 2.
  3. //! The main component of the proposals system. Provides methods and extrinsics to create and
  4. //! vote for proposals, inspired by Parity **Democracy module**.
  5. //!
  6. //! ## Overview
  7. //! Proposals `engine` module provides an abstract mechanism to work with proposals: creation, voting,
  8. //! execution, canceling, etc. Proposal execution demands serialized _Dispatchable_ proposal code.
  9. //! It could be any _Dispatchable_ + _Parameter_ type, but most likely, it would be serialized (via
  10. //! Parity _codec_ crate) extrisic call. A proposal stage can be described by its [status](./enum.ProposalStatus.html).
  11. //!
  12. //! ## Proposal lifecycle
  13. //! When a proposal passes [checks](./struct.Module.html#method.ensure_create_proposal_parameters_are_valid)
  14. //! for its [parameters](./struct.ProposalParameters.html) - it can be [created](./struct.Module.html#method.create_proposal).
  15. //! The newly created proposal has _Active_ status. The proposal can be voted on or canceled during its
  16. //! _voting period_. Votes can be [different](./enum.VoteKind.html). When the proposal gets enough votes
  17. //! to be slashed or approved or _voting period_ ends - the proposal becomes _Finalized_. If the proposal
  18. //! got approved and _grace period_ passed - the `engine` module tries to execute the proposal.
  19. //! The final [approved status](./enum.ApprovedProposalStatus.html) of the proposal defines
  20. //! an overall proposal outcome.
  21. //!
  22. //! ### Notes
  23. //!
  24. //! - The proposal can be [vetoed](./struct.Module.html#method.veto_proposal)
  25. //! anytime before the proposal execution by the _sudo_.
  26. //! - When the proposal is created with some stake - refunding on proposal finalization with
  27. //! different statuses should be accomplished from the external handler from the _stake module_
  28. //! (_StakingEventsHandler_). Such a handler should call
  29. //! [refund_proposal_stake](./struct.Module.html#method.refund_proposal_stake) callback function.
  30. //! - If the _council_ got reelected during the proposal _voting period_ the external handler calls
  31. //! [reset_active_proposals](./trait.Module.html#method.reset_active_proposals) function and
  32. //! all voting results get cleared.
  33. //!
  34. //! ### Important abstract types to be implemented
  35. //! Proposals `engine` module has several abstractions to be implemented in order to work correctly.
  36. //! - _VoterOriginValidator_ - ensure valid voter identity. Voters should have permissions to vote:
  37. //! they should be council members.
  38. //! - [VotersParameters](./trait.VotersParameters.html) - defines total voter number, which is
  39. //! the council size
  40. //! - _ProposerOriginValidator_ - ensure valid proposer identity. Proposers should have permissions
  41. //! to create a proposal: they should be members of the Joystream.
  42. //! - [StakeHandlerProvider](./trait.StakeHandlerProvider.html) - defines an interface for the staking.
  43. //!
  44. //! A full list of the abstractions can be found [here](./trait.Trait.html).
  45. //!
  46. //! ### Supported extrinsics
  47. //! - [vote](./struct.Module.html#method.vote) - registers a vote for the proposal
  48. //! - [cancel_proposal](./struct.Module.html#method.cancel_proposal) - cancels the proposal (can be canceled only by owner)
  49. //! - [veto_proposal](./struct.Module.html#method.veto_proposal) - vetoes the proposal
  50. //!
  51. //! ### Public API
  52. //! - [create_proposal](./struct.Module.html#method.create_proposal) - creates proposal using provided parameters
  53. //! - [ensure_create_proposal_parameters_are_valid](./struct.Module.html#method.ensure_create_proposal_parameters_are_valid) - ensures that we can create the proposal
  54. //! - [refund_proposal_stake](./struct.Module.html#method.refund_proposal_stake) - a callback for _StakingHandlerEvents_
  55. //! - [reset_active_proposals](./trait.Module.html#method.reset_active_proposals) - resets voting results for active proposals
  56. //!
  57. //! ## Usage
  58. //!
  59. //! ```
  60. //! use frame_support::{decl_module, print};
  61. //! use system::ensure_signed;
  62. //! use codec::Encode;
  63. //! use pallet_proposals_engine::{self as engine, ProposalParameters};
  64. //!
  65. //! pub trait Trait: engine::Trait + membership::Trait {}
  66. //!
  67. //! decl_module! {
  68. //! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
  69. //! #[weight = 10_000_000]
  70. //! fn executable_proposal(origin) {
  71. //! print("executed!");
  72. //! }
  73. //!
  74. //! #[weight = 10_000_000]
  75. //! pub fn create_spending_proposal(
  76. //! origin,
  77. //! proposer_id: T::MemberId,
  78. //! ) {
  79. //! let account_id = ensure_signed(origin)?;
  80. //! let parameters = ProposalParameters::default();
  81. //! let title = b"Spending proposal".to_vec();
  82. //! let description = b"We need to spend some tokens to support the working group lead."
  83. //! .to_vec();
  84. //! let encoded_proposal_code = <Call<T>>::executable_proposal().encode();
  85. //!
  86. //! <engine::Module<T>>::ensure_create_proposal_parameters_are_valid(
  87. //! &parameters,
  88. //! &title,
  89. //! &description,
  90. //! None,
  91. //! &account_id,
  92. //! )?;
  93. //! <engine::Module<T>>::create_proposal(
  94. //! account_id,
  95. //! proposer_id,
  96. //! parameters,
  97. //! title,
  98. //! description,
  99. //! None,
  100. //! encoded_proposal_code
  101. //! )?;
  102. //! }
  103. //! }
  104. //! }
  105. //! # fn main() {}
  106. //! ```
  107. // Ensure we're `no_std` when compiling for Wasm.
  108. #![cfg_attr(not(feature = "std"), no_std)]
  109. // Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
  110. //#![warn(missing_docs)]
  111. use crate::types::ApprovedProposalData;
  112. use types::FinalizedProposalData;
  113. use types::ProposalStakeManager;
  114. pub use types::{
  115. ActiveStake, ApprovedProposalStatus, FinalizationData, Proposal, ProposalDecisionStatus,
  116. ProposalParameters, ProposalStatus, VotingResults,
  117. };
  118. pub use types::{BalanceOf, CurrencyOf, NegativeImbalance};
  119. pub use types::{DefaultStakeHandlerProvider, StakeHandler, StakeHandlerProvider};
  120. pub use types::{ProposalCodeDecoder, ProposalExecutable};
  121. pub use types::{VoteKind, VotersParameters};
  122. pub(crate) mod types;
  123. #[cfg(test)]
  124. mod tests;
  125. use codec::Decode;
  126. use frame_support::dispatch::{DispatchError, DispatchResult, UnfilteredDispatchable};
  127. use frame_support::storage::IterableStorageMap;
  128. use frame_support::traits::{Currency, Get};
  129. use frame_support::{
  130. decl_error, decl_event, decl_module, decl_storage, ensure, print, Parameter, StorageDoubleMap,
  131. };
  132. use sp_arithmetic::traits::{SaturatedConversion, Zero};
  133. use sp_std::vec::Vec;
  134. use system::{ensure_root, RawOrigin};
  135. use common::origin::ActorOriginValidator;
  136. type MemberId<T> = <T as membership::Trait>::MemberId;
  137. /// Proposals engine trait.
  138. pub trait Trait:
  139. system::Trait + pallet_timestamp::Trait + stake::Trait + membership::Trait + balances::Trait
  140. {
  141. /// Engine event type.
  142. type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
  143. /// Validates proposer id and origin combination
  144. type ProposerOriginValidator: ActorOriginValidator<
  145. Self::Origin,
  146. MemberId<Self>,
  147. Self::AccountId,
  148. >;
  149. /// Validates voter id and origin combination
  150. type VoterOriginValidator: ActorOriginValidator<Self::Origin, MemberId<Self>, Self::AccountId>;
  151. /// Provides data for voting. Defines maximum voters count for the proposal.
  152. type TotalVotersCounter: VotersParameters;
  153. /// Proposal Id type
  154. type ProposalId: From<u32> + Parameter + Default + Copy;
  155. /// Provides stake logic implementation. Can be used to mock stake logic.
  156. type StakeHandlerProvider: StakeHandlerProvider<Self>;
  157. /// The fee is applied when cancel the proposal. A fee would be slashed (burned).
  158. type CancellationFee: Get<BalanceOf<Self>>;
  159. /// The fee is applied when the proposal gets rejected. A fee would be slashed (burned).
  160. type RejectionFee: Get<BalanceOf<Self>>;
  161. /// Defines max allowed proposal title length.
  162. type TitleMaxLength: Get<u32>;
  163. /// Defines max allowed proposal description length.
  164. type DescriptionMaxLength: Get<u32>;
  165. /// Defines max simultaneous active proposals number.
  166. type MaxActiveProposalLimit: Get<u32>;
  167. /// Proposals executable code. Can be instantiated by external module Call enum members.
  168. type DispatchableCallCode: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + Default;
  169. }
  170. decl_event!(
  171. /// Proposals engine events
  172. pub enum Event<T>
  173. where
  174. <T as Trait>::ProposalId,
  175. MemberId = MemberId<T>,
  176. <T as system::Trait>::BlockNumber,
  177. <T as system::Trait>::AccountId,
  178. <T as stake::Trait>::StakeId,
  179. {
  180. /// Emits on proposal creation.
  181. /// Params:
  182. /// - Member id of a proposer.
  183. /// - Id of a newly created proposal after it was saved in storage.
  184. ProposalCreated(MemberId, ProposalId),
  185. /// Emits on proposal status change.
  186. /// Params:
  187. /// - Id of a updated proposal.
  188. /// - New proposal status
  189. ProposalStatusUpdated(ProposalId, ProposalStatus<BlockNumber, StakeId, AccountId>),
  190. /// Emits on voting for the proposal
  191. /// Params:
  192. /// - Voter - member id of a voter.
  193. /// - Id of a proposal.
  194. /// - Kind of vote.
  195. Voted(MemberId, ProposalId, VoteKind),
  196. }
  197. );
  198. decl_error! {
  199. /// Engine module predefined errors
  200. pub enum Error for Module<T: Trait>{
  201. /// Proposal cannot have an empty title"
  202. EmptyTitleProvided,
  203. /// Proposal cannot have an empty body
  204. EmptyDescriptionProvided,
  205. /// Title is too long
  206. TitleIsTooLong,
  207. /// Description is too long
  208. DescriptionIsTooLong,
  209. /// The proposal does not exist
  210. ProposalNotFound,
  211. /// Proposal is finalized already
  212. ProposalFinalized,
  213. /// The proposal have been already voted on
  214. AlreadyVoted,
  215. /// Not an author
  216. NotAuthor,
  217. /// Max active proposals number exceeded
  218. MaxActiveProposalNumberExceeded,
  219. /// Stake cannot be empty with this proposal
  220. EmptyStake,
  221. /// Stake should be empty for this proposal
  222. StakeShouldBeEmpty,
  223. /// Stake differs from the proposal requirements
  224. StakeDiffersFromRequired,
  225. /// Approval threshold cannot be zero
  226. InvalidParameterApprovalThreshold,
  227. /// Slashing threshold cannot be zero
  228. InvalidParameterSlashingThreshold,
  229. /// Require root origin in extrinsics
  230. RequireRootOrigin,
  231. /// Insufficient balance for operation.
  232. InsufficientBalance,
  233. }
  234. }
  235. // Storage for the proposals engine module
  236. decl_storage! {
  237. pub trait Store for Module<T: Trait> as ProposalEngine{
  238. /// Map proposal by its id.
  239. pub Proposals get(fn proposals): map hasher(blake2_128_concat)
  240. T::ProposalId => ProposalOf<T>;
  241. /// Count of all proposals that have been created.
  242. pub ProposalCount get(fn proposal_count): u32;
  243. /// Map proposal executable code by proposal id.
  244. pub DispatchableCallCode get(fn proposal_codes): map hasher(blake2_128_concat)
  245. T::ProposalId => Vec<u8>;
  246. /// Count of active proposals.
  247. pub ActiveProposalCount get(fn active_proposal_count): u32;
  248. /// Ids of proposals that are open for voting (have not been finalized yet).
  249. pub ActiveProposalIds get(fn active_proposal_ids): map hasher(blake2_128_concat)
  250. T::ProposalId=> ();
  251. /// Ids of proposals that were approved and theirs grace period was not expired.
  252. pub PendingExecutionProposalIds get(fn pending_proposal_ids): map hasher(blake2_128_concat)
  253. T::ProposalId=> ();
  254. /// Double map for preventing duplicate votes. Should be cleaned after usage.
  255. pub VoteExistsByProposalByVoter get(fn vote_by_proposal_by_voter):
  256. double_map hasher(blake2_128_concat) T::ProposalId, hasher(blake2_128_concat) MemberId<T> => VoteKind;
  257. /// Map proposal id by stake id. Required by StakingEventsHandler callback call
  258. pub StakesProposals get(fn stakes_proposals): map hasher(blake2_128_concat)
  259. T::StakeId => T::ProposalId;
  260. }
  261. }
  262. decl_module! {
  263. /// 'Proposal engine' substrate module
  264. pub struct Module<T: Trait> for enum Call where origin: T::Origin {
  265. /// Predefined errors
  266. type Error = Error<T>;
  267. /// Emits an event. Default substrate implementation.
  268. fn deposit_event() = default;
  269. /// Exports const - the fee is applied when cancel the proposal. A fee would be slashed (burned).
  270. const CancellationFee: BalanceOf<T> = T::CancellationFee::get();
  271. /// Exports const - the fee is applied when the proposal gets rejected. A fee would be slashed (burned).
  272. const RejectionFee: BalanceOf<T> = T::RejectionFee::get();
  273. /// Exports const - max allowed proposal title length.
  274. const TitleMaxLength: u32 = T::TitleMaxLength::get();
  275. /// Exports const - max allowed proposal description length.
  276. const DescriptionMaxLength: u32 = T::DescriptionMaxLength::get();
  277. /// Exports const - max simultaneous active proposals number.
  278. const MaxActiveProposalLimit: u32 = T::MaxActiveProposalLimit::get();
  279. /// Vote extrinsic. Conditions: origin must allow votes.
  280. #[weight = 10_000_000] // TODO: adjust weight
  281. pub fn vote(origin, voter_id: MemberId<T>, proposal_id: T::ProposalId, vote: VoteKind) {
  282. T::VoterOriginValidator::ensure_actor_origin(
  283. origin,
  284. voter_id,
  285. )?;
  286. ensure!(<Proposals<T>>::contains_key(proposal_id), Error::<T>::ProposalNotFound);
  287. let mut proposal = Self::proposals(proposal_id);
  288. ensure!(matches!(proposal.status, ProposalStatus::Active{..}), Error::<T>::ProposalFinalized);
  289. let did_not_vote_before = !<VoteExistsByProposalByVoter<T>>::contains_key(
  290. proposal_id,
  291. voter_id,
  292. );
  293. ensure!(did_not_vote_before, Error::<T>::AlreadyVoted);
  294. proposal.voting_results.add_vote(vote.clone());
  295. // mutation
  296. <Proposals<T>>::insert(proposal_id, proposal);
  297. <VoteExistsByProposalByVoter<T>>::insert(proposal_id, voter_id, vote.clone());
  298. Self::deposit_event(RawEvent::Voted(voter_id, proposal_id, vote));
  299. }
  300. /// Cancel a proposal by its original proposer.
  301. #[weight = 10_000_000] // TODO: adjust weight
  302. pub fn cancel_proposal(origin, proposer_id: MemberId<T>, proposal_id: T::ProposalId) {
  303. T::ProposerOriginValidator::ensure_actor_origin(
  304. origin,
  305. proposer_id,
  306. )?;
  307. ensure!(<Proposals<T>>::contains_key(proposal_id), Error::<T>::ProposalNotFound);
  308. let proposal = Self::proposals(proposal_id);
  309. ensure!(proposer_id == proposal.proposer_id, Error::<T>::NotAuthor);
  310. ensure!(matches!(proposal.status, ProposalStatus::Active{..}), Error::<T>::ProposalFinalized);
  311. // mutation
  312. Self::finalize_proposal(proposal_id, ProposalDecisionStatus::Canceled);
  313. }
  314. /// Veto a proposal. Must be root.
  315. #[weight = 10_000_000] // TODO: adjust weight
  316. pub fn veto_proposal(origin, proposal_id: T::ProposalId) {
  317. ensure_root(origin)?;
  318. ensure!(<Proposals<T>>::contains_key(proposal_id), Error::<T>::ProposalNotFound);
  319. let proposal = Self::proposals(proposal_id);
  320. // mutation
  321. if <PendingExecutionProposalIds<T>>::contains_key(proposal_id) {
  322. Self::veto_pending_execution_proposal(proposal_id, proposal);
  323. } else {
  324. ensure!(matches!(proposal.status, ProposalStatus::Active{..}), Error::<T>::ProposalFinalized);
  325. Self::finalize_proposal(proposal_id, ProposalDecisionStatus::Vetoed);
  326. }
  327. }
  328. /// Block finalization. Perform voting period check, vote result tally, approved proposals
  329. /// grace period checks, and proposal execution.
  330. fn on_finalize(_n: T::BlockNumber) {
  331. let finalized_proposals = Self::get_finalized_proposals();
  332. // mutation
  333. // Check vote results. Approved proposals with zero grace period will be
  334. // transitioned to the PendingExecution status.
  335. for proposal_data in finalized_proposals {
  336. <Proposals<T>>::insert(proposal_data.proposal_id, proposal_data.proposal);
  337. Self::finalize_proposal(proposal_data.proposal_id, proposal_data.status);
  338. }
  339. let executable_proposals =
  340. Self::get_approved_proposal_with_expired_grace_period();
  341. // Execute approved proposals with expired grace period
  342. for approved_proosal in executable_proposals {
  343. Self::execute_proposal(approved_proosal);
  344. }
  345. }
  346. }
  347. }
  348. impl<T: Trait> Module<T> {
  349. /// Create proposal. Requires 'proposal origin' membership.
  350. pub fn create_proposal(
  351. account_id: T::AccountId,
  352. proposer_id: MemberId<T>,
  353. parameters: ProposalParameters<T::BlockNumber, types::BalanceOf<T>>,
  354. title: Vec<u8>,
  355. description: Vec<u8>,
  356. stake_balance: Option<types::BalanceOf<T>>,
  357. encoded_dispatchable_call_code: Vec<u8>,
  358. ) -> Result<T::ProposalId, DispatchError> {
  359. Self::ensure_create_proposal_parameters_are_valid(
  360. &parameters,
  361. &title,
  362. &description,
  363. stake_balance,
  364. &account_id,
  365. )?;
  366. // checks passed
  367. // mutation
  368. let next_proposal_count_value = Self::proposal_count() + 1;
  369. let new_proposal_id = next_proposal_count_value;
  370. let proposal_id = T::ProposalId::from(new_proposal_id);
  371. // Check stake_balance for value and create stake if value exists, else take None
  372. // If create_stake() returns error - return error from extrinsic
  373. let stake_id_result = stake_balance
  374. .map(|stake_amount| {
  375. ProposalStakeManager::<T>::create_stake(stake_amount, account_id.clone())
  376. })
  377. .transpose()?;
  378. let mut stake_data = None;
  379. if let Some(stake_id) = stake_id_result {
  380. stake_data = Some(ActiveStake {
  381. stake_id,
  382. source_account_id: account_id,
  383. });
  384. <StakesProposals<T>>::insert(stake_id, proposal_id);
  385. }
  386. let new_proposal = Proposal {
  387. created_at: Self::current_block(),
  388. parameters,
  389. title,
  390. description,
  391. proposer_id,
  392. status: ProposalStatus::Active(stake_data),
  393. voting_results: VotingResults::default(),
  394. };
  395. <Proposals<T>>::insert(proposal_id, new_proposal);
  396. <DispatchableCallCode<T>>::insert(proposal_id, encoded_dispatchable_call_code);
  397. <ActiveProposalIds<T>>::insert(proposal_id, ());
  398. ProposalCount::put(next_proposal_count_value);
  399. Self::increase_active_proposal_counter();
  400. Self::deposit_event(RawEvent::ProposalCreated(proposer_id, proposal_id));
  401. Ok(proposal_id)
  402. }
  403. /// Performs all checks for the proposal creation:
  404. /// - title, body lengths
  405. /// - max active proposal
  406. /// - provided parameters: approval_threshold_percentage and slashing_threshold_percentage > 0
  407. /// - provided stake balance and parameters.required_stake are valid
  408. pub fn ensure_create_proposal_parameters_are_valid(
  409. parameters: &ProposalParameters<T::BlockNumber, types::BalanceOf<T>>,
  410. title: &[u8],
  411. description: &[u8],
  412. stake_balance: Option<types::BalanceOf<T>>,
  413. stake_account_id: &T::AccountId,
  414. ) -> DispatchResult {
  415. ensure!(!title.is_empty(), Error::<T>::EmptyTitleProvided);
  416. ensure!(
  417. title.len() as u32 <= T::TitleMaxLength::get(),
  418. Error::<T>::TitleIsTooLong
  419. );
  420. ensure!(
  421. !description.is_empty(),
  422. Error::<T>::EmptyDescriptionProvided
  423. );
  424. ensure!(
  425. description.len() as u32 <= T::DescriptionMaxLength::get(),
  426. Error::<T>::DescriptionIsTooLong
  427. );
  428. ensure!(
  429. (Self::active_proposal_count()) < T::MaxActiveProposalLimit::get(),
  430. Error::<T>::MaxActiveProposalNumberExceeded
  431. );
  432. ensure!(
  433. parameters.approval_threshold_percentage > 0,
  434. Error::<T>::InvalidParameterApprovalThreshold
  435. );
  436. ensure!(
  437. parameters.slashing_threshold_percentage > 0,
  438. Error::<T>::InvalidParameterSlashingThreshold
  439. );
  440. // check stake parameters
  441. if let Some(required_stake) = parameters.required_stake {
  442. if let Some(staked_balance) = stake_balance {
  443. ensure!(
  444. required_stake == staked_balance,
  445. Error::<T>::StakeDiffersFromRequired
  446. );
  447. } else {
  448. return Err(Error::<T>::EmptyStake.into());
  449. }
  450. ensure!(
  451. types::Balances::<T>::usable_balance(stake_account_id).saturated_into::<u128>()
  452. >= required_stake.saturated_into::<u128>(),
  453. Error::<T>::InsufficientBalance
  454. );
  455. }
  456. if stake_balance.is_some() && parameters.required_stake.is_none() {
  457. return Err(Error::<T>::StakeShouldBeEmpty.into());
  458. }
  459. Ok(())
  460. }
  461. /// Callback from StakingEventsHandler. Refunds unstaked imbalance back to the source account.
  462. /// There can be a lot of invariant breaks in the scope of this proposal.
  463. /// Such situations are handled by adding error messages to the log.
  464. pub fn refund_proposal_stake(stake_id: T::StakeId, imbalance: NegativeImbalance<T>) {
  465. if <StakesProposals<T>>::contains_key(stake_id) {
  466. let proposal_id = Self::stakes_proposals(stake_id);
  467. if <Proposals<T>>::contains_key(proposal_id) {
  468. let proposal = Self::proposals(proposal_id);
  469. if let ProposalStatus::Active(active_stake_result) = proposal.status {
  470. if let Some(active_stake) = active_stake_result {
  471. let refunding_result = CurrencyOf::<T>::resolve_into_existing(
  472. &active_stake.source_account_id,
  473. imbalance,
  474. );
  475. if refunding_result.is_err() {
  476. print("Broken invariant: cannot refund");
  477. }
  478. }
  479. } else {
  480. print("Broken invariant: proposal status is not Active");
  481. }
  482. } else {
  483. print("Broken invariant: proposal doesn't exist");
  484. }
  485. } else {
  486. print("Broken invariant: stake doesn't exist");
  487. }
  488. }
  489. /// Resets voting results for active proposals.
  490. /// Possible application includes new council elections.
  491. pub fn reset_active_proposals() {
  492. <ActiveProposalIds<T>>::iter().for_each(|(proposal_id, _)| {
  493. <Proposals<T>>::mutate(proposal_id, |proposal| {
  494. proposal.reset_proposal();
  495. <VoteExistsByProposalByVoter<T>>::remove_prefix(&proposal_id);
  496. });
  497. });
  498. }
  499. }
  500. impl<T: Trait> Module<T> {
  501. // Wrapper-function over system::block_number()
  502. fn current_block() -> T::BlockNumber {
  503. <system::Module<T>>::block_number()
  504. }
  505. // Enumerates through active proposals. Tally Voting results.
  506. // Returns proposals with finalized status and id
  507. fn get_finalized_proposals() -> Vec<FinalizedProposal<T>> {
  508. // Enumerate active proposals id and gather finalization data.
  509. // Skip proposals with unfinished voting.
  510. <ActiveProposalIds<T>>::iter()
  511. .filter_map(|(proposal_id, _)| {
  512. // load current proposal
  513. let proposal = Self::proposals(proposal_id);
  514. // Calculates votes, takes in account voting period expiration.
  515. // If voting process is in progress, then decision status is None.
  516. let decision_status = proposal.define_proposal_decision_status(
  517. T::TotalVotersCounter::total_voters_count(),
  518. Self::current_block(),
  519. );
  520. // map to FinalizedProposalData if decision for the proposal is made or return None
  521. decision_status.map(|status| FinalizedProposalData {
  522. proposal_id,
  523. proposal,
  524. status,
  525. finalized_at: Self::current_block(),
  526. })
  527. })
  528. .collect() // compose output vector
  529. }
  530. // Veto approved proposal during its grace period. Saves a new proposal status and removes
  531. // proposal id from the 'PendingExecutionProposalIds'
  532. fn veto_pending_execution_proposal(proposal_id: T::ProposalId, proposal: ProposalOf<T>) {
  533. <PendingExecutionProposalIds<T>>::remove(proposal_id);
  534. let vetoed_proposal_status = ProposalStatus::finalized(
  535. ProposalDecisionStatus::Vetoed,
  536. None,
  537. None,
  538. Self::current_block(),
  539. );
  540. <Proposals<T>>::insert(
  541. proposal_id,
  542. Proposal {
  543. status: vetoed_proposal_status,
  544. ..proposal
  545. },
  546. );
  547. }
  548. // Executes approved proposal code
  549. fn execute_proposal(approved_proposal: ApprovedProposal<T>) {
  550. let proposal_code = Self::proposal_codes(approved_proposal.proposal_id);
  551. let proposal_code_result = T::DispatchableCallCode::decode(&mut &proposal_code[..]);
  552. let approved_proposal_status = match proposal_code_result {
  553. Ok(proposal_code) => {
  554. if let Err(dispatch_error) =
  555. proposal_code.dispatch_bypass_filter(T::Origin::from(RawOrigin::Root))
  556. {
  557. ApprovedProposalStatus::failed_execution(Self::parse_dispatch_error(
  558. dispatch_error.error,
  559. ))
  560. } else {
  561. ApprovedProposalStatus::Executed
  562. }
  563. }
  564. Err(error) => ApprovedProposalStatus::failed_execution(error.what()),
  565. };
  566. let proposal_execution_status = approved_proposal
  567. .finalisation_status_data
  568. .create_approved_proposal_status(approved_proposal_status);
  569. let mut proposal = approved_proposal.proposal;
  570. proposal.status = proposal_execution_status.clone();
  571. <Proposals<T>>::insert(approved_proposal.proposal_id, proposal);
  572. Self::deposit_event(RawEvent::ProposalStatusUpdated(
  573. approved_proposal.proposal_id,
  574. proposal_execution_status,
  575. ));
  576. <PendingExecutionProposalIds<T>>::remove(&approved_proposal.proposal_id);
  577. }
  578. // Performs all actions on proposal finalization:
  579. // - clean active proposal cache
  580. // - update proposal status fields (status, finalized_at)
  581. // - add to pending execution proposal cache if approved
  582. // - slash and unstake proposal stake if stake exists
  583. // - decrease active proposal counter
  584. // - fire an event
  585. // It prints an error message in case of an attempt to finalize the non-active proposal.
  586. fn finalize_proposal(proposal_id: T::ProposalId, decision_status: ProposalDecisionStatus) {
  587. Self::decrease_active_proposal_counter();
  588. <ActiveProposalIds<T>>::remove(&proposal_id.clone());
  589. let mut proposal = Self::proposals(proposal_id);
  590. if let ProposalStatus::Active(active_stake) = proposal.status.clone() {
  591. if let ProposalDecisionStatus::Approved { .. } = decision_status {
  592. <PendingExecutionProposalIds<T>>::insert(proposal_id, ());
  593. }
  594. // deal with stakes if necessary
  595. let slash_balance =
  596. Self::calculate_slash_balance(&decision_status, &proposal.parameters);
  597. let slash_and_unstake_result =
  598. Self::slash_and_unstake(active_stake.clone(), slash_balance);
  599. // create finalized proposal status with error if any
  600. let new_proposal_status = ProposalStatus::finalized(
  601. decision_status,
  602. slash_and_unstake_result.err(),
  603. active_stake,
  604. Self::current_block(),
  605. );
  606. proposal.status = new_proposal_status.clone();
  607. <Proposals<T>>::insert(proposal_id, proposal);
  608. Self::deposit_event(RawEvent::ProposalStatusUpdated(
  609. proposal_id,
  610. new_proposal_status,
  611. ));
  612. } else {
  613. print("Broken invariant: proposal cannot be non-active during the finalisation");
  614. }
  615. }
  616. // Slashes the stake and perform unstake only in case of existing stake
  617. fn slash_and_unstake(
  618. current_stake_data: Option<ActiveStake<T::StakeId, T::AccountId>>,
  619. slash_balance: BalanceOf<T>,
  620. ) -> Result<(), &'static str> {
  621. // only if stake exists
  622. if let Some(stake_data) = current_stake_data {
  623. if !slash_balance.is_zero() {
  624. ProposalStakeManager::<T>::slash(stake_data.stake_id, slash_balance)?;
  625. }
  626. ProposalStakeManager::<T>::remove_stake(stake_data.stake_id)?;
  627. }
  628. Ok(())
  629. }
  630. // Calculates required slash based on finalization ProposalDecisionStatus and proposal parameters.
  631. // Method visibility allows testing.
  632. pub(crate) fn calculate_slash_balance(
  633. decision_status: &ProposalDecisionStatus,
  634. proposal_parameters: &ProposalParameters<T::BlockNumber, types::BalanceOf<T>>,
  635. ) -> types::BalanceOf<T> {
  636. match decision_status {
  637. ProposalDecisionStatus::Rejected | ProposalDecisionStatus::Expired => {
  638. T::RejectionFee::get()
  639. }
  640. ProposalDecisionStatus::Approved { .. } | ProposalDecisionStatus::Vetoed => {
  641. BalanceOf::<T>::zero()
  642. }
  643. ProposalDecisionStatus::Canceled => T::CancellationFee::get(),
  644. ProposalDecisionStatus::Slashed => proposal_parameters
  645. .required_stake
  646. .clone()
  647. .unwrap_or_else(BalanceOf::<T>::zero), // stake if set or zero
  648. }
  649. }
  650. // Enumerates approved proposals and checks their grace period expiration
  651. fn get_approved_proposal_with_expired_grace_period() -> Vec<ApprovedProposal<T>> {
  652. <PendingExecutionProposalIds<T>>::iter()
  653. .filter_map(|(proposal_id, _)| {
  654. let proposal = Self::proposals(proposal_id);
  655. if proposal.is_grace_period_expired(Self::current_block()) {
  656. // this should be true, because it was tested inside is_grace_period_expired()
  657. if let ProposalStatus::Finalized(finalisation_data) = proposal.status.clone() {
  658. Some(ApprovedProposalData {
  659. proposal_id,
  660. proposal,
  661. finalisation_status_data: finalisation_data,
  662. })
  663. } else {
  664. None
  665. }
  666. } else {
  667. None
  668. }
  669. })
  670. .collect()
  671. }
  672. // Increases active proposal counter.
  673. fn increase_active_proposal_counter() {
  674. let next_active_proposal_count_value = Self::active_proposal_count() + 1;
  675. ActiveProposalCount::put(next_active_proposal_count_value);
  676. }
  677. // Decreases active proposal counter down to zero. Decreasing below zero has no effect.
  678. fn decrease_active_proposal_counter() {
  679. let current_active_proposal_counter = Self::active_proposal_count();
  680. if current_active_proposal_counter > 0 {
  681. let next_active_proposal_count_value = current_active_proposal_counter - 1;
  682. ActiveProposalCount::put(next_active_proposal_count_value);
  683. };
  684. }
  685. // Parse dispatchable execution result.
  686. fn parse_dispatch_error(error: DispatchError) -> &'static str {
  687. match error {
  688. DispatchError::BadOrigin => error.into(),
  689. DispatchError::Other(msg) => msg,
  690. DispatchError::CannotLookup => error.into(),
  691. DispatchError::Module {
  692. index: _,
  693. error: _,
  694. message: msg,
  695. } => msg.unwrap_or("Dispatch error."),
  696. }
  697. }
  698. }
  699. // Simplification of the 'FinalizedProposalData' type
  700. type FinalizedProposal<T> = FinalizedProposalData<
  701. <T as Trait>::ProposalId,
  702. <T as system::Trait>::BlockNumber,
  703. MemberId<T>,
  704. types::BalanceOf<T>,
  705. <T as stake::Trait>::StakeId,
  706. <T as system::Trait>::AccountId,
  707. >;
  708. // Simplification of the 'ApprovedProposalData' type
  709. type ApprovedProposal<T> = ApprovedProposalData<
  710. <T as Trait>::ProposalId,
  711. <T as system::Trait>::BlockNumber,
  712. MemberId<T>,
  713. types::BalanceOf<T>,
  714. <T as stake::Trait>::StakeId,
  715. <T as system::Trait>::AccountId,
  716. >;
  717. // Simplification of the 'Proposal' type
  718. type ProposalOf<T> = Proposal<
  719. <T as system::Trait>::BlockNumber,
  720. MemberId<T>,
  721. types::BalanceOf<T>,
  722. <T as stake::Trait>::StakeId,
  723. <T as system::Trait>::AccountId,
  724. >;