mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-07-12 01:45:45 +00:00
669972a171
* remove extra whitespace Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * only emit rebag event on success * add doc explaining the term voter * revamp/simplify rebag test * ensure genesis accounts are placed into the correct nodes/bags * bond_extra implicitly rebags * types at top; doc public type * start sketching out adjustable thresholds * add integrity test for voter bag threshold requirements * get rid of BagIdx This reorganizes bag storage such that bags are always referred to by their upper threshold. This in turn means that adding and removing bags is cheaper; you only need to migrate certain voters, not all of them. * implement migration logic for when the threshold list changes * start sketching out threshold proc macros * further refine macro signatures * WIP: implement make_ratio macro * start rethinking the process of producing threshold lists The macro approach seems to be a non-starter; that only really works if we're throwing around numeric literals everywhere, and that's just not nice in this case. Instead, let's write helper functions and make it really easy to generate the tables in separate, permanent files, which humans can then edit. * write helper functions to emit voter bags module * WIP: demo generating voter bags for a realistic runtime This isn't yet done, becuase it seems to take a Very Long Time to run, and it really shouldn't. Need to look into that. Still, it's a lot closer than it was this morning. * rm unnecessary arg_enum * fix voter bags math Turns out that when you're working in exponential space, you need to divide, not subtract, in order to keep the math working properly. Also neaten up the output a little bit to make it easier to read. * add computed voter bags thresholds to node * fixup some docs * iter from large bags to small, fulfuilling the contract * make tests compile * add VoterBagThresholds to some configs * ensure that iteration covers all voters even with implied final bag * use sp_std::boxed::Box; * fix unused import * add some more voter bags tests * file_header.txt * integrity test to ensure min bag exceeds existential weight * add more debug assertions about node list length * rm unused imports * Kian enters * Update frame/election-provider-support/src/onchain.rs Co-authored-by: Zeke Mostov <32168567+emostov@users.noreply.github.com> * Suggestions for #9081 (Store voters in unsorted bags) (#9328) * Add some debug asserts to node::get and remove_node * Improve the debug asserts in remove_node * improve debug asserts * Space * Remove bad assertions * Tests: WIP take_works * Take test * Doc comment * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Test storage is cleaned up; * formatting * Switch to simpler thresholds * Update the storage cleanup test * Remove hardcoded values from benchmark to make it more robust * Fix tests to acces bags properly * Sanity check WIP; tests failing * Update sanity checks to be more correct * Improve storage cleanup tests * WIP remote_ext_tests * Some notes on next steps * Remove some stuff that was for remote-ext tests * Some more cleanup to reduce diff * More :clean: * Mo cleanin * small fix * A lot of changes from kian Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: kianenigma <kian@parity.io> * merge fallout * Run cargo +nightly fmt * Fix a bunch of stuff, remove not needed runtime arg of make-bags * add logs * Glue the new staking bags to the election snapshot (#9415) * Glue the new staking bags to the election snapshot * add CheckedRem (#9412) * add CheckedRem * fix * Run fmt * Test comment Co-authored-by: Xiliang Chen <xlchen1291@gmail.com> Co-authored-by: emostov <32168567+emostov@users.noreply.github.com> * Update node runtime with VoterSnapshotPerBlock * Unit test for pallet-staking unsorted bags feature (targets #9081) (#9422) * impl notional_bag_for_works * Add tests: insert_as_works & insert_works * Impl test: remove_works * Trivial cleaning * Add test: update_position_for_works * Write out edge case; probably can delete later * Add test: bags::get_works * Add test: remove_node_happy_path_works * Add test: remove_node_bad_paths_documented * WIP: voting_data_works * done * Improve test voting_data_works * Add comment * Fill out test basic_setup_works * Update: iteration_is_semi_sorted * Improve remove_works * Update update_position_for_works; create set_ledger_and_free_balance * Improve get_works * Improve storage clean up checks in remove test * Test: impl rebag_works + insert_and_remove_works * forgot file - Test: impl rebag_works + insert_and_remove_works * Small tweak * Update voter_bags test to reflect unused bags are removed * Unbond & Rebond: do_rebag * Prevent infinite loops with duplicate tail insert * Check iter.count on voter list in pre-migrate * undo strang fmt comment stuff * Add in todo Co-authored-by: kianenigma <kian@parity.io> * Try prepare for master merge * Reduce diff * Add comment for test to add * Add in code TODO for update_position efficiency updates * Initial impl compiles * impl StakingVoterListStub * Sample impl<T: Config> VoterListProvider<T> for VoterList<T> * impl VoterListProvider for voter-bags * WIP integrate pallet-voter-bags to staking mock * the trait `pallet_staking::pallet::pallet::Config` is not implemented for `mock::Test` * random * pushing my stuff * Mock working * WIP voter list tests * Add bag insert, remove tests * Add test for bag insert and remove * Add remaining tests for VoterList * Add tests for node * Add rebag works * Add rebag extrinsic tests * Rename to bags-list and name the list .. list! * Rename VoterBagThresholds => BagThresholds * Add test count_works * Test on_update_works * test sanity check * a round of test fixes * push a lot of changes * my last changes * all bags-list test work; fmt * Beautify some tests * Doc comment for bags-list * Add insert warnings * Setup initial benchmark * Wire up WeightInfo * is_terminal wip; everything broken! * Is terminal working * add TODOs for remove_node * clean up remoe_node * Fix all staking tests * retire VoterBagFor * commit * bring in stashed changes * save * bench pipeline works now, but I can't run stuff * sabe * benchmarks now run, but we have a failure * WIP: Wire up make_bags * bags-thresholds compiles * Fix most build issues * This will fix all the tests * move bag thresholds to bags-list * Move bag-thresholds bin to within pallet-bags * Remove some unnescary TODOs * Impl tets wrong_rebag_is_noop * assert remove is a noop with bad data * Assert integrity test panics * Return an error when inserting duplicates * Update to handle error in staking pallet when inserting to list * Test contains and on_insert error * Test re-nominate does not mess up list or count * Everything builds and works, only the benchmark... * fuck yeah benchmarks * more cleanup, more hardening. * use the bags list again * fix benhc * Some questions and changs for List::migration * Fix migration removed_bags and new_bags usage * Some trivial aesthetic changes * Some more trivial changes * tiny changes/ * mega rename * fix all tests and ci build * nit * Test and fix migration * nit * fmt * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * fmt * remove unused * make a few things pub * make node also pub.. for remote-ext test * Fix all tests again * Force bag changes in relevant benchmarks (targets #9507) (#9529) * force rebag for unbond, rebond, and bond_extra * nit * Improve utils * fmt * nits * Move generate_bags to its own pallet * Get runtime-benchmarks feature setup with prepare_on_update_benchmark * Withdraw unbonded kill working * Nominate bench working * some cleanup * WIP * update to check head pre & post conditions * Add some post condition verification stuff for on_remove * Update nominate * fmt * Improvements * Fix build * fix build with polkadot companion * Update frame/bags-list/src/list/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * move generate-bag from frame to utils * wip * refactor WIP * WIP save * Refactor working * some variable renaming * WIP: prepare to remove head checks * Finish MvP refactor * Some cleanup * Soem more cleanup * save * fix a lot of stuff * Update client/db/src/bench.rs Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> * Apply suggestions from code review * Apply suggestions from code review * Fix some issues that came from trying to merge comments on github * some small changes * simplify it Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: kianenigma <kian@parity.io> Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> * Build works * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Remove commented out debug assert * Remove some unused deps and some unused benchmarking stuff * Fix stakings ElectionDataProvider clear * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Improving staking pallet-bags-list migration * fix build and some comments; * comment * Reduce visibility in bags list components * make node.bag_upper only accesible to benchmarks * Address some feedback; comments updates * use nominator map comment * fix vec capacity debug assert * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * clarify VoterSnapshotPerBlock * Reduce diff on create_validators by wrapping with_seed * Some small improvements to staking benches * Soem comment updates * fix vec capacity debug assert ... for real this time * Reduce ListBags viz * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Remove supports_eq_unordered & Support eq_unordered * Update utils/frame/generate-bags/src/lib.rs Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Make total-issuance & minimium-balance CLI args; Dont use emptry ext * Improve docs for generate bags CLI args * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Don't use default bags weight in node runtime * Feature gating sanity_check not working * Feature gate sanity check by creating duplicate fns * Fix line wrapping * Document VoteWeightProvider * Make bags ext-builder not a module * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * use pallet_bags_list instead of crate in mock * Make get_bags test helper fn live in List * use remove_from_storage_unchecked for node removal * Remove count of ids removed in remove_many * Add node sanity check, improve list sanity check * Do a list sanity check after on_update * List::migrate: clean up debug assert, exit early when no change in thresholds * Improve public doc comments for pallet_bags_list::list::List * Improve public doc comments for pallet_bags_list::list::List * Update generate bags docs * Fix grammar in bags-list benchmark * Add benchmark case for `rebag` extrinsic * Add count parameter to List::clear; WIP adding MaxEncodedLen to list' * MaxEncodeLen + generate_storage_info not working for Bag or Node * Get MaxEncodeLen derive to work * Try to correctly feature gate SortedListProvider::clear * Use u32::MAX, not u32::max_value * Get up to nominators_quota noms * SortedListProvider::clear takes an Option * Eplicitly ignore SortedListProvider return value * Fix doc comment * Update node-runtime voter snapshot per block * Add test get_max_len_voters_even_if_some_nominators_are_slashed * Add test only_iterates_max_2_times_nominators_quota * Fix generate bags cargo.toml * use sp_std vec * Remove v8 migration hooks from pallet-staking * Update npos trait * Try respect line width * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Update frame/bags-list/src/benchmarks.rs * Unwrap try-runtime error; remove sortedlistprovider pre upgrade len check * trigger ci * restore * trigger ci * restore * trigger ci * revert * trigger ci * revert Co-authored-by: Peter Goodspeed-Niklaus <coriolinus@users.noreply.github.com> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Peter Goodspeed-Niklaus <peter.r.goodspeedniklaus@gmail.com> Co-authored-by: kianenigma <kian@parity.io> Co-authored-by: Xiliang Chen <xlchen1291@gmail.com> Co-authored-by: Parity Benchmarking Bot <admin@parity.io> Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
307 lines
11 KiB
Rust
307 lines
11 KiB
Rust
// This file is part of Substrate.
|
|
|
|
// Copyright (C) 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.
|
|
|
|
//! # Bags-List Pallet
|
|
//!
|
|
//! A semi-sorted list, where items hold an `AccountId` based on some `VoteWeight`. The `AccountId`
|
|
//! (`id` for short) might be synonym to a `voter` or `nominator` in some context, and `VoteWeight`
|
|
//! signifies the chance of each id being included in the final [`VoteWeightProvider::iter`].
|
|
//!
|
|
//! It implements [`sp_election_provider_support::SortedListProvider`] to provide a semi-sorted list
|
|
//! of accounts to another pallet. It needs some other pallet to give it some information about the
|
|
//! weights of accounts via [`sp_election_provider_support::VoteWeightProvider`].
|
|
//!
|
|
//! This pallet is not configurable at genesis. Whoever uses it should call appropriate functions of
|
|
//! the `SortedListProvider` (e.g. `on_insert`, or `regenerate`) at their genesis.
|
|
//!
|
|
//! # Goals
|
|
//!
|
|
//! The data structure exposed by this pallet aims to be optimized for:
|
|
//!
|
|
//! - insertions and removals.
|
|
//! - iteration over the top* N items by weight, where the precise ordering of items doesn't
|
|
//! particularly matter.
|
|
//!
|
|
//! # Details
|
|
//!
|
|
//! - items are kept in bags, which are delineated by their range of weight (See [`BagThresholds`]).
|
|
//! - for iteration, bags are chained together from highest to lowest and elements within the bag
|
|
//! are iterated from head to tail.
|
|
//! - items within a bag are iterated in order of insertion. Thus removing an item and re-inserting
|
|
//! it will worsen its position in list iteration; this reduces incentives for some types of spam
|
|
//! that involve consistently removing and inserting for better position. Further, ordering
|
|
//! granularity is thus dictated by range between each bag threshold.
|
|
//! - if an item's weight changes to a value no longer within the range of its current bag the
|
|
//! item's position will need to be updated by an external actor with rebag (update), or removal
|
|
//! and insertion.
|
|
|
|
#![cfg_attr(not(feature = "std"), no_std)]
|
|
|
|
use frame_election_provider_support::{SortedListProvider, VoteWeight, VoteWeightProvider};
|
|
use frame_system::ensure_signed;
|
|
use sp_std::prelude::*;
|
|
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
mod benchmarks;
|
|
|
|
mod list;
|
|
#[cfg(test)]
|
|
mod mock;
|
|
#[cfg(test)]
|
|
mod tests;
|
|
pub mod weights;
|
|
|
|
pub use pallet::*;
|
|
pub use weights::WeightInfo;
|
|
|
|
pub use list::Error;
|
|
use list::List;
|
|
|
|
pub(crate) const LOG_TARGET: &'static str = "runtime::bags_list";
|
|
|
|
// syntactic sugar for logging.
|
|
#[macro_export]
|
|
macro_rules! log {
|
|
($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
|
|
log::$level!(
|
|
target: crate::LOG_TARGET,
|
|
concat!("[{:?}] 👜", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
|
|
)
|
|
};
|
|
}
|
|
|
|
#[frame_support::pallet]
|
|
pub mod pallet {
|
|
use super::*;
|
|
use frame_support::pallet_prelude::*;
|
|
use frame_system::pallet_prelude::*;
|
|
|
|
#[pallet::pallet]
|
|
#[pallet::generate_store(pub(crate) trait Store)]
|
|
#[pallet::generate_storage_info]
|
|
pub struct Pallet<T>(_);
|
|
|
|
#[pallet::config]
|
|
pub trait Config: frame_system::Config {
|
|
/// The overarching event type.
|
|
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
|
|
|
|
/// Weight information for extrinsics in this pallet.
|
|
type WeightInfo: weights::WeightInfo;
|
|
|
|
/// Something that provides the weights of ids.
|
|
type VoteWeightProvider: VoteWeightProvider<Self::AccountId>;
|
|
|
|
/// The list of thresholds separating the various bags.
|
|
///
|
|
/// Ids are separated into unsorted bags according to their vote weight. This specifies the
|
|
/// thresholds separating the bags. An id's bag is the largest bag for which the id's weight
|
|
/// is less than or equal to its upper threshold.
|
|
///
|
|
/// When ids are iterated, higher bags are iterated completely before lower bags. This means
|
|
/// that iteration is _semi-sorted_: ids of higher weight tend to come before ids of lower
|
|
/// weight, but peer ids within a particular bag are sorted in insertion order.
|
|
///
|
|
/// # Expressing the constant
|
|
///
|
|
/// This constant must be sorted in strictly increasing order. Duplicate items are not
|
|
/// permitted.
|
|
///
|
|
/// There is an implied upper limit of `VoteWeight::MAX`; that value does not need to be
|
|
/// specified within the bag. For any two threshold lists, if one ends with
|
|
/// `VoteWeight::MAX`, the other one does not, and they are otherwise equal, the two lists
|
|
/// will behave identically.
|
|
///
|
|
/// # Calculation
|
|
///
|
|
/// It is recommended to generate the set of thresholds in a geometric series, such that
|
|
/// there exists some constant ratio such that `threshold[k + 1] == (threshold[k] *
|
|
/// constant_ratio).max(threshold[k] + 1)` for all `k`.
|
|
///
|
|
/// The helpers in the `/utils/frame/generate-bags` module can simplify this calculation.
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// - If `BagThresholds::get().is_empty()`, then all ids are put into the same bag, and
|
|
/// iteration is strictly in insertion order.
|
|
/// - If `BagThresholds::get().len() == 64`, and the thresholds are determined according to
|
|
/// the procedure given above, then the constant ratio is equal to 2.
|
|
/// - If `BagThresholds::get().len() == 200`, and the thresholds are determined according to
|
|
/// the procedure given above, then the constant ratio is approximately equal to 1.248.
|
|
/// - If the threshold list begins `[1, 2, 3, ...]`, then an id with weight 0 or 1 will fall
|
|
/// into bag 0, an id with weight 2 will fall into bag 1, etc.
|
|
///
|
|
/// # Migration
|
|
///
|
|
/// In the event that this list ever changes, a copy of the old bags list must be retained.
|
|
/// With that `List::migrate` can be called, which will perform the appropriate migration.
|
|
#[pallet::constant]
|
|
type BagThresholds: Get<&'static [VoteWeight]>;
|
|
}
|
|
|
|
/// How many ids are registered.
|
|
// NOTE: This is merely a counter for `ListNodes`. It should someday be replaced by the
|
|
// `CountedMaop` storage.
|
|
#[pallet::storage]
|
|
pub(crate) type CounterForListNodes<T> = StorageValue<_, u32, ValueQuery>;
|
|
|
|
/// A single node, within some bag.
|
|
///
|
|
/// Nodes store links forward and back within their respective bags.
|
|
#[pallet::storage]
|
|
pub(crate) type ListNodes<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, list::Node<T>>;
|
|
|
|
/// A bag stored in storage.
|
|
///
|
|
/// Stores a `Bag` struct, which stores head and tail pointers to itself.
|
|
#[pallet::storage]
|
|
pub(crate) type ListBags<T: Config> = StorageMap<_, Twox64Concat, VoteWeight, list::Bag<T>>;
|
|
|
|
#[pallet::event]
|
|
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
|
|
pub enum Event<T: Config> {
|
|
/// Moved an account from one bag to another. \[who, from, to\].
|
|
Rebagged(T::AccountId, VoteWeight, VoteWeight),
|
|
}
|
|
|
|
#[pallet::call]
|
|
impl<T: Config> Pallet<T> {
|
|
/// Declare that some `dislocated` account has, through rewards or penalties, sufficiently
|
|
/// changed its weight that it should properly fall into a different bag than its current
|
|
/// one.
|
|
///
|
|
/// Anyone can call this function about any potentially dislocated account.
|
|
///
|
|
/// Will never return an error; if `dislocated` does not exist or doesn't need a rebag, then
|
|
/// it is a noop and fees are still collected from `origin`.
|
|
#[pallet::weight(T::WeightInfo::rebag_non_terminal().max(T::WeightInfo::rebag_terminal()))]
|
|
pub fn rebag(origin: OriginFor<T>, dislocated: T::AccountId) -> DispatchResult {
|
|
ensure_signed(origin)?;
|
|
let current_weight = T::VoteWeightProvider::vote_weight(&dislocated);
|
|
let _ = Pallet::<T>::do_rebag(&dislocated, current_weight);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[pallet::hooks]
|
|
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
|
|
fn integrity_test() {
|
|
// ensure they are strictly increasing, this also implies that duplicates are detected.
|
|
assert!(
|
|
T::BagThresholds::get().windows(2).all(|window| window[1] > window[0]),
|
|
"thresholds must strictly increase, and have no duplicates",
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<T: Config> Pallet<T> {
|
|
/// Move an account from one bag to another, depositing an event on success.
|
|
///
|
|
/// If the account changed bags, returns `Some((from, to))`.
|
|
pub fn do_rebag(
|
|
account: &T::AccountId,
|
|
new_weight: VoteWeight,
|
|
) -> Option<(VoteWeight, VoteWeight)> {
|
|
// if no voter at that node, don't do anything.
|
|
// the caller just wasted the fee to call this.
|
|
let maybe_movement = list::Node::<T>::get(&account)
|
|
.and_then(|node| List::update_position_for(node, new_weight));
|
|
if let Some((from, to)) = maybe_movement {
|
|
Self::deposit_event(Event::<T>::Rebagged(account.clone(), from, to));
|
|
};
|
|
maybe_movement
|
|
}
|
|
|
|
/// Equivalent to `ListBags::get`, but public. Useful for tests in outside of this crate.
|
|
#[cfg(feature = "std")]
|
|
pub fn list_bags_get(weight: VoteWeight) -> Option<list::Bag<T>> {
|
|
ListBags::get(weight)
|
|
}
|
|
}
|
|
|
|
impl<T: Config> SortedListProvider<T::AccountId> for Pallet<T> {
|
|
type Error = Error;
|
|
|
|
fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
|
|
Box::new(List::<T>::iter().map(|n| n.id().clone()))
|
|
}
|
|
|
|
fn count() -> u32 {
|
|
CounterForListNodes::<T>::get()
|
|
}
|
|
|
|
fn contains(id: &T::AccountId) -> bool {
|
|
List::<T>::contains(id)
|
|
}
|
|
|
|
fn on_insert(id: T::AccountId, weight: VoteWeight) -> Result<(), Error> {
|
|
List::<T>::insert(id, weight)
|
|
}
|
|
|
|
fn on_update(id: &T::AccountId, new_weight: VoteWeight) {
|
|
Pallet::<T>::do_rebag(id, new_weight);
|
|
}
|
|
|
|
fn on_remove(id: &T::AccountId) {
|
|
List::<T>::remove(id)
|
|
}
|
|
|
|
fn regenerate(
|
|
all: impl IntoIterator<Item = T::AccountId>,
|
|
weight_of: Box<dyn Fn(&T::AccountId) -> VoteWeight>,
|
|
) -> u32 {
|
|
List::<T>::regenerate(all, weight_of)
|
|
}
|
|
|
|
#[cfg(feature = "std")]
|
|
fn sanity_check() -> Result<(), &'static str> {
|
|
List::<T>::sanity_check()
|
|
}
|
|
|
|
#[cfg(not(feature = "std"))]
|
|
fn sanity_check() -> Result<(), &'static str> {
|
|
Ok(())
|
|
}
|
|
|
|
fn clear(maybe_count: Option<u32>) -> u32 {
|
|
List::<T>::clear(maybe_count)
|
|
}
|
|
|
|
#[cfg(feature = "runtime-benchmarks")]
|
|
fn weight_update_worst_case(who: &T::AccountId, is_increase: bool) -> VoteWeight {
|
|
use frame_support::traits::Get as _;
|
|
let thresholds = T::BagThresholds::get();
|
|
let node = list::Node::<T>::get(who).unwrap();
|
|
let current_bag_idx = thresholds
|
|
.iter()
|
|
.chain(sp_std::iter::once(&VoteWeight::MAX))
|
|
.position(|w| w == &node.bag_upper())
|
|
.unwrap();
|
|
|
|
if is_increase {
|
|
let next_threshold_idx = current_bag_idx + 1;
|
|
assert!(thresholds.len() > next_threshold_idx);
|
|
thresholds[next_threshold_idx]
|
|
} else {
|
|
assert!(current_bag_idx != 0);
|
|
let prev_threshold_idx = current_bag_idx - 1;
|
|
thresholds[prev_threshold_idx]
|
|
}
|
|
}
|
|
}
|