Files
biguint
chain_spec_builder
compact
fixed_point
fork_tree
frame_benchmarking
frame_benchmarking_cli
frame_election_provider_support
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_support_test
frame_support_test_pallet
frame_system
frame_system_benchmarking
frame_system_rpc_runtime_api
frame_try_runtime
multiply_by_rational
node_bench
node_browser_testing
node_cli
node_executor
node_inspect
node_primitives
node_rpc
node_rpc_client
node_runtime
node_template
node_template_runtime
node_testing
normalize
pallet_assets
pallet_atomic_swap
pallet_aura
pallet_authority_discovery
pallet_authorship
pallet_babe
pallet_balances
pallet_bounties
pallet_collective
pallet_contracts
pallet_contracts_primitives
pallet_contracts_proc_macro
pallet_contracts_rpc
pallet_contracts_rpc_runtime_api
pallet_democracy
pallet_election_provider_multi_phase
pallet_elections
pallet_elections_phragmen
pallet_example
pallet_example_offchain_worker
pallet_example_parallel
pallet_gilt
pallet_grandpa
pallet_identity
pallet_im_online
pallet_indices
pallet_lottery
pallet_membership
pallet_mmr
pallet_mmr_primitives
pallet_mmr_rpc
pallet_multisig
pallet_nicks
pallet_node_authorization
pallet_offences
pallet_offences_benchmarking
pallet_proxy
pallet_randomness_collective_flip
pallet_recovery
pallet_scheduler
pallet_scored_pool
pallet_session
pallet_session_benchmarking
pallet_society
pallet_staking
pallet_staking_reward_curve
pallet_staking_reward_fn
pallet_sudo
pallet_template
pallet_timestamp
pallet_tips
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
pallet_transaction_storage
pallet_treasury
pallet_uniques
pallet_utility
pallet_vesting
per_thing_rational
phragmen_balancing
phragmen_pjr
phragmms_balancing
reduce
remote_externalities
sc_allocator
sc_authority_discovery
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_babe_rpc
sc_consensus_epochs
sc_consensus_manual_seal
sc_consensus_pow
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_finality_grandpa_rpc
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_network_test
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_runtime_test
sc_service
sc_service_test
sc_state_db
sc_sync_state_rpc
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_pool
sc_transaction_pool_api
sp_api
sp_api_proc_macro
sp_application_crypto
sp_application_crypto_test
sp_arithmetic
sp_authority_discovery
sp_authorship
sp_block_builder
sp_blockchain
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_pow
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_maybe_compressed_blob
sp_npos_elections
sp_npos_elections_solution_type
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_runtime_interface_test
sp_runtime_interface_test_wasm
sp_runtime_interface_test_wasm_deprecated
sp_sandbox
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_test_primitives
sp_timestamp
sp_tracing
sp_transaction_pool
sp_transaction_storage_proof
sp_trie
sp_utils
sp_version
sp_version_proc_macro
sp_wasm_interface
subkey
substrate
substrate_browser_utils
substrate_build_script_utils
substrate_frame_cli
substrate_frame_rpc_support
substrate_frame_rpc_system
substrate_prometheus_endpoint
substrate_test_client
substrate_test_runtime
substrate_test_runtime_client
substrate_test_runtime_transaction_pool
substrate_test_utils
substrate_test_utils_derive
substrate_test_utils_test_crate
substrate_wasm_builder
test_runner
test_runner_example
try_runtime_cli
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// This file is part of Substrate.

// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Scored Pool Pallet
//!
//! The pallet maintains a scored membership pool. Each entity in the
//! pool can be attributed a `Score`. From this pool a set `Members`
//! is constructed. This set contains the `MemberCount` highest
//! scoring entities. Unscored entities are never part of `Members`.
//!
//! If an entity wants to be part of the pool a deposit is required.
//! The deposit is returned when the entity withdraws or when it
//! is removed by an entity with the appropriate authority.
//!
//! Every `Period` blocks the set of `Members` is refreshed from the
//! highest scoring members in the pool and, no matter if changes
//! occurred, `T::MembershipChanged::set_members_sorted` is invoked.
//! On first load `T::MembershipInitialized::initialize_members` is
//! invoked with the initial `Members` set.
//!
//! It is possible to withdraw candidacy/resign your membership at any
//! time. If an entity is currently a member, this results in removal
//! from the `Pool` and `Members`; the entity is immediately replaced
//! by the next highest scoring candidate in the pool, if available.
//!
//! - [`Config`]
//! - [`Call`]
//! - [`Pallet`]
//!
//! ## Interface
//!
//! ### Public Functions
//!
//! - `submit_candidacy` - Submit candidacy to become a member. Requires a deposit.
//! - `withdraw_candidacy` - Withdraw candidacy. Deposit is returned.
//! - `score` - Attribute a quantitative score to an entity.
//! - `kick` - Remove an entity from the pool and members. Deposit is returned.
//! - `change_member_count` - Changes the amount of candidates taken into `Members`.
//!
//! ## Usage
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_system::ensure_signed;
//! use pallet_scored_pool::{self as scored_pool};
//!
//! pub trait Config: scored_pool::Config {}
//!
//! decl_module! {
//! 	pub struct Module<T: Config> for enum Call where origin: T::Origin {
//! 		#[weight = 0]
//! 		pub fn candidate(origin) -> dispatch::DispatchResult {
//! 			let who = ensure_signed(origin)?;
//!
//! 			let _ = <scored_pool::Pallet<T>>::submit_candidacy(
//! 				T::Origin::from(Some(who.clone()).into())
//! 			);
//! 			Ok(())
//! 		}
//! 	}
//! }
//!
//! # fn main() { }
//! ```
//!
//! ## Dependencies
//!
//! This pallet depends on the [System pallet](../frame_system/index.html).

// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

use codec::FullCodec;
use frame_support::{
	ensure,
	traits::{ChangeMembers, Currency, Get, InitializeMembers, ReservableCurrency},
};
pub use pallet::*;
use sp_runtime::traits::{AtLeast32Bit, StaticLookup, Zero};
use sp_std::{fmt::Debug, prelude::*};

type BalanceOf<T, I> =
	<<T as Config<I>>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type PoolT<T, I> = Vec<(<T as frame_system::Config>::AccountId, Option<<T as Config<I>>::Score>)>;

/// The enum is supplied when refreshing the members set.
/// Depending on the enum variant the corresponding associated
/// type function will be invoked.
enum ChangeReceiver {
	/// Should call `T::MembershipInitialized`.
	MembershipInitialized,
	/// Should call `T::MembershipChanged`.
	MembershipChanged,
}

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::{pallet_prelude::*, traits::EnsureOrigin, weights::Weight};
	use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
	use sp_runtime::traits::MaybeSerializeDeserialize;

	#[pallet::pallet]
	#[pallet::generate_store(pub(super) trait Store)]
	pub struct Pallet<T, I = ()>(_);

	#[pallet::config]
	pub trait Config<I: 'static = ()>: frame_system::Config {
		/// The currency used for deposits.
		type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;

		/// The score attributed to a member or candidate.
		type Score: AtLeast32Bit
			+ Clone
			+ Copy
			+ Default
			+ FullCodec
			+ MaybeSerializeDeserialize
			+ Debug;

		/// The overarching event type.
		type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;

		// The deposit which is reserved from candidates if they want to
		// start a candidacy. The deposit gets returned when the candidacy is
		// withdrawn or when the candidate is kicked.
		#[pallet::constant]
		type CandidateDeposit: Get<BalanceOf<Self, I>>;

		/// Every `Period` blocks the `Members` are filled with the highest scoring
		/// members in the `Pool`.
		#[pallet::constant]
		type Period: Get<Self::BlockNumber>;

		/// The receiver of the signal for when the membership has been initialized.
		/// This happens pre-genesis and will usually be the same as `MembershipChanged`.
		/// If you need to do something different on initialization, then you can change
		/// this accordingly.
		type MembershipInitialized: InitializeMembers<Self::AccountId>;

		/// The receiver of the signal for when the members have changed.
		type MembershipChanged: ChangeMembers<Self::AccountId>;

		/// Allows a configurable origin type to set a score to a candidate in the pool.
		type ScoreOrigin: EnsureOrigin<Self::Origin>;

		/// Required origin for removing a member (though can always be Root).
		/// Configurable origin which enables removing an entity. If the entity
		/// is part of the `Members` it is immediately replaced by the next
		/// highest scoring candidate, if available.
		type KickOrigin: EnsureOrigin<Self::Origin>;
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config<I>, I: 'static = ()> {
		/// The given member was removed. See the transaction for who.
		MemberRemoved,
		/// An entity has issued a candidacy. See the transaction for who.
		CandidateAdded,
		/// An entity withdrew candidacy. See the transaction for who.
		CandidateWithdrew,
		/// The candidacy was forcefully removed for an entity.
		/// See the transaction for who.
		CandidateKicked,
		/// A score was attributed to the candidate.
		/// See the transaction for who.
		CandidateScored,
	}

	/// Error for the scored-pool pallet.
	#[pallet::error]
	pub enum Error<T, I = ()> {
		/// Already a member.
		AlreadyInPool,
		/// Index out of bounds.
		InvalidIndex,
		/// Index does not match requested account.
		WrongAccountIndex,
	}

	/// The current pool of candidates, stored as an ordered Vec
	/// (ordered descending by score, `None` last, highest first).
	#[pallet::storage]
	#[pallet::getter(fn pool)]
	pub(crate) type Pool<T: Config<I>, I: 'static = ()> = StorageValue<_, PoolT<T, I>, ValueQuery>;

	/// A Map of the candidates. The information in this Map is redundant
	/// to the information in the `Pool`. But the Map enables us to easily
	/// check if a candidate is already in the pool, without having to
	/// iterate over the entire pool (the `Pool` is not sorted by
	/// `T::AccountId`, but by `T::Score` instead).
	#[pallet::storage]
	#[pallet::getter(fn candidate_exists)]
	pub(crate) type CandidateExists<T: Config<I>, I: 'static = ()> =
		StorageMap<_, Twox64Concat, T::AccountId, bool, ValueQuery>;

	/// The current membership, stored as an ordered Vec.
	#[pallet::storage]
	#[pallet::getter(fn members)]
	pub(crate) type Members<T: Config<I>, I: 'static = ()> =
		StorageValue<_, Vec<T::AccountId>, ValueQuery>;

	/// Size of the `Members` set.
	#[pallet::storage]
	#[pallet::getter(fn member_count)]
	pub(crate) type MemberCount<T, I = ()> = StorageValue<_, u32, ValueQuery>;

	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
		pub pool: PoolT<T, I>,
		pub member_count: u32,
	}

	#[cfg(feature = "std")]
	impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
		fn default() -> Self {
			Self { pool: Default::default(), member_count: Default::default() }
		}
	}

	#[pallet::genesis_build]
	impl<T: Config<I>, I: 'static> GenesisBuild<T, I> for GenesisConfig<T, I> {
		fn build(&self) {
			let mut pool = self.pool.clone();

			// reserve balance for each candidate in the pool.
			// panicking here is ok, since this just happens one time, pre-genesis.
			pool.iter().for_each(|(who, _)| {
				T::Currency::reserve(&who, T::CandidateDeposit::get())
					.expect("balance too low to create candidacy");
				<CandidateExists<T, I>>::insert(who, true);
			});

			// Sorts the `Pool` by score in a descending order. Entities which
			// have a score of `None` are sorted to the beginning of the vec.
			pool.sort_by_key(|(_, maybe_score)| Reverse(maybe_score.unwrap_or_default()));

			<MemberCount<T, I>>::put(self.member_count);
			<Pool<T, I>>::put(&pool);
			<Pallet<T, I>>::refresh_members(pool, ChangeReceiver::MembershipInitialized);
		}
	}

	#[pallet::hooks]
	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
		/// Every `Period` blocks the `Members` set is refreshed from the
		/// highest scoring members in the pool.
		fn on_initialize(n: T::BlockNumber) -> Weight {
			if n % T::Period::get() == Zero::zero() {
				let pool = <Pool<T, I>>::get();
				<Pallet<T, I>>::refresh_members(pool, ChangeReceiver::MembershipChanged);
			}
			0
		}
	}

	#[pallet::call]
	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Add `origin` to the pool of candidates.
		///
		/// This results in `CandidateDeposit` being reserved from
		/// the `origin` account. The deposit is returned once
		/// candidacy is withdrawn by the candidate or the entity
		/// is kicked by `KickOrigin`.
		///
		/// The dispatch origin of this function must be signed.
		///
		/// The `index` parameter of this function must be set to
		/// the index of the transactor in the `Pool`.
		#[pallet::weight(0)]
		pub fn submit_candidacy(origin: OriginFor<T>) -> DispatchResult {
			let who = ensure_signed(origin)?;
			ensure!(!<CandidateExists<T, I>>::contains_key(&who), Error::<T, I>::AlreadyInPool);

			let deposit = T::CandidateDeposit::get();
			T::Currency::reserve(&who, deposit)?;

			// can be inserted as last element in pool, since entities with
			// `None` are always sorted to the end.
			<Pool<T, I>>::append((who.clone(), Option::<<T as Config<I>>::Score>::None));

			<CandidateExists<T, I>>::insert(&who, true);

			Self::deposit_event(Event::<T, I>::CandidateAdded);
			Ok(())
		}

		/// An entity withdraws candidacy and gets its deposit back.
		///
		/// If the entity is part of the `Members`, then the highest member
		/// of the `Pool` that is not currently in `Members` is immediately
		/// placed in the set instead.
		///
		/// The dispatch origin of this function must be signed.
		///
		/// The `index` parameter of this function must be set to
		/// the index of the transactor in the `Pool`.
		#[pallet::weight(0)]
		pub fn withdraw_candidacy(origin: OriginFor<T>, index: u32) -> DispatchResult {
			let who = ensure_signed(origin)?;

			let pool = <Pool<T, I>>::get();
			Self::ensure_index(&pool, &who, index)?;

			Self::remove_member(pool, who, index)?;
			Self::deposit_event(Event::<T, I>::CandidateWithdrew);
			Ok(())
		}

		/// Kick a member `who` from the set.
		///
		/// May only be called from `T::KickOrigin`.
		///
		/// The `index` parameter of this function must be set to
		/// the index of `dest` in the `Pool`.
		#[pallet::weight(0)]
		pub fn kick(
			origin: OriginFor<T>,
			dest: <T::Lookup as StaticLookup>::Source,
			index: u32,
		) -> DispatchResult {
			T::KickOrigin::ensure_origin(origin)?;

			let who = T::Lookup::lookup(dest)?;

			let pool = <Pool<T, I>>::get();
			Self::ensure_index(&pool, &who, index)?;

			Self::remove_member(pool, who, index)?;
			Self::deposit_event(Event::<T, I>::CandidateKicked);
			Ok(())
		}

		/// Score a member `who` with `score`.
		///
		/// May only be called from `T::ScoreOrigin`.
		///
		/// The `index` parameter of this function must be set to
		/// the index of the `dest` in the `Pool`.
		#[pallet::weight(0)]
		pub fn score(
			origin: OriginFor<T>,
			dest: <T::Lookup as StaticLookup>::Source,
			index: u32,
			score: T::Score,
		) -> DispatchResult {
			T::ScoreOrigin::ensure_origin(origin)?;

			let who = T::Lookup::lookup(dest)?;

			let mut pool = <Pool<T, I>>::get();
			Self::ensure_index(&pool, &who, index)?;

			pool.remove(index as usize);

			// we binary search the pool (which is sorted descending by score).
			// if there is already an element with `score`, we insert
			// right before that. if not, the search returns a location
			// where we can insert while maintaining order.
			let item = (who, Some(score.clone()));
			let location = pool
				.binary_search_by_key(&Reverse(score), |(_, maybe_score)| {
					Reverse(maybe_score.unwrap_or_default())
				})
				.unwrap_or_else(|l| l);
			pool.insert(location, item);

			<Pool<T, I>>::put(&pool);
			Self::deposit_event(Event::<T, I>::CandidateScored);
			Ok(())
		}

		/// Dispatchable call to change `MemberCount`.
		///
		/// This will only have an effect the next time a refresh happens
		/// (this happens each `Period`).
		///
		/// May only be called from root.
		#[pallet::weight(0)]
		pub fn change_member_count(origin: OriginFor<T>, count: u32) -> DispatchResult {
			ensure_root(origin)?;
			MemberCount::<T, I>::put(&count);
			Ok(())
		}
	}
}

impl<T: Config<I>, I: 'static> Pallet<T, I> {
	/// Fetches the `MemberCount` highest scoring members from
	/// `Pool` and puts them into `Members`.
	///
	/// The `notify` parameter is used to deduct which associated
	/// type function to invoke at the end of the method.
	fn refresh_members(pool: PoolT<T, I>, notify: ChangeReceiver) {
		let count = MemberCount::<T, I>::get();

		let mut new_members: Vec<T::AccountId> = pool
			.into_iter()
			.filter(|(_, score)| score.is_some())
			.take(count as usize)
			.map(|(account_id, _)| account_id)
			.collect();
		new_members.sort();

		let old_members = <Members<T, I>>::get();
		<Members<T, I>>::put(&new_members);

		match notify {
			ChangeReceiver::MembershipInitialized =>
				T::MembershipInitialized::initialize_members(&new_members),
			ChangeReceiver::MembershipChanged =>
				T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]),
		}
	}

	/// Removes an entity `remove` at `index` from the `Pool`.
	///
	/// If the entity is a member it is also removed from `Members` and
	/// the deposit is returned.
	fn remove_member(
		mut pool: PoolT<T, I>,
		remove: T::AccountId,
		index: u32,
	) -> Result<(), Error<T, I>> {
		// all callers of this function in this pallet also check
		// the index for validity before calling this function.
		// nevertheless we check again here, to assert that there was
		// no mistake when invoking this sensible function.
		Self::ensure_index(&pool, &remove, index)?;

		pool.remove(index as usize);
		<Pool<T, I>>::put(&pool);

		// remove from set, if it was in there
		let members = <Members<T, I>>::get();
		if members.binary_search(&remove).is_ok() {
			Self::refresh_members(pool, ChangeReceiver::MembershipChanged);
		}

		<CandidateExists<T, I>>::remove(&remove);

		T::Currency::unreserve(&remove, T::CandidateDeposit::get());

		Self::deposit_event(Event::<T, I>::MemberRemoved);
		Ok(())
	}

	/// Checks if `index` is a valid number and if the element found
	/// at `index` in `Pool` is equal to `who`.
	fn ensure_index(pool: &PoolT<T, I>, who: &T::AccountId, index: u32) -> Result<(), Error<T, I>> {
		ensure!(index < pool.len() as u32, Error::<T, I>::InvalidIndex);

		let (index_who, _index_score) = &pool[index as usize];
		ensure!(index_who == who, Error::<T, I>::WrongAccountIndex);

		Ok(())
	}
}