mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-15 17:21:08 +00:00
Apply some clippy lints (#11154)
* Apply some clippy hints * Revert clippy ci changes * Update client/cli/src/commands/generate.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/cli/src/commands/inspect_key.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/db/src/bench.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/db/src/bench.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/service/src/client/block_rules.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/service/src/client/block_rules.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/network/src/transactions.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/network/src/protocol.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Revert due to missing `or_default` function. * Fix compilation and simplify code * Undo change that corrupts benchmark. * fix clippy * Update client/service/test/src/lib.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/state-db/src/noncanonical.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update client/state-db/src/noncanonical.rs remove leftovers! * Update client/tracing/src/logging/directives.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update utils/fork-tree/src/lib.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * added needed ref * Update frame/referenda/src/benchmarking.rs * Simplify byte-vec creation * let's just not overlap the ranges * Correction * cargo fmt * Update utils/frame/benchmarking-cli/src/shared/stats.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update utils/frame/benchmarking-cli/src/pallet/command.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Update utils/frame/benchmarking-cli/src/pallet/command.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Giles Cope <gilescope@gmail.com>
This commit is contained in:
committed by
GitHub
parent
a990473cf9
commit
b581604aa7
@@ -281,7 +281,7 @@ benchmarks_instance_pallet! {
|
||||
let target0 = T::Lookup::unlookup(account("target", 0, SEED));
|
||||
let target1 = T::Lookup::unlookup(account("target", 1, SEED));
|
||||
let target2 = T::Lookup::unlookup(account("target", 2, SEED));
|
||||
}: _(SystemOrigin::Signed(caller), Default::default(), target0.clone(), target1.clone(), target2.clone())
|
||||
}: _(SystemOrigin::Signed(caller), Default::default(), target0, target1, target2)
|
||||
verify {
|
||||
assert_last_event::<T, I>(Event::TeamChanged {
|
||||
asset_id: Default::default(),
|
||||
@@ -346,7 +346,7 @@ benchmarks_instance_pallet! {
|
||||
let (caller, _) = create_default_asset::<T, I>(true);
|
||||
T::Currency::make_free_balance_be(&caller, DepositBalanceOf::<T, I>::max_value());
|
||||
let dummy = vec![0u8; T::StringLimit::get() as usize];
|
||||
let origin = SystemOrigin::Signed(caller.clone()).into();
|
||||
let origin = SystemOrigin::Signed(caller).into();
|
||||
Assets::<T, I>::set_metadata(origin, Default::default(), dummy.clone(), dummy, 12)?;
|
||||
|
||||
let origin = T::ForceOrigin::successful_origin();
|
||||
@@ -365,7 +365,7 @@ benchmarks_instance_pallet! {
|
||||
owner: caller_lookup.clone(),
|
||||
issuer: caller_lookup.clone(),
|
||||
admin: caller_lookup.clone(),
|
||||
freezer: caller_lookup.clone(),
|
||||
freezer: caller_lookup,
|
||||
min_balance: 100u32.into(),
|
||||
is_sufficient: true,
|
||||
is_frozen: false,
|
||||
@@ -398,7 +398,7 @@ benchmarks_instance_pallet! {
|
||||
let delegate_lookup = T::Lookup::unlookup(delegate.clone());
|
||||
let amount = 100u32.into();
|
||||
let origin = SystemOrigin::Signed(owner.clone()).into();
|
||||
Assets::<T, I>::approve_transfer(origin, id, delegate_lookup.clone(), amount)?;
|
||||
Assets::<T, I>::approve_transfer(origin, id, delegate_lookup, amount)?;
|
||||
|
||||
let dest: T::AccountId = account("dest", 0, SEED);
|
||||
let dest_lookup = T::Lookup::unlookup(dest.clone());
|
||||
|
||||
@@ -204,7 +204,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
who: &T::AccountId,
|
||||
keep_alive: bool,
|
||||
) -> Result<T::Balance, DispatchError> {
|
||||
let details = Asset::<T, I>::get(id).ok_or_else(|| Error::<T, I>::Unknown)?;
|
||||
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(!details.is_frozen, Error::<T, I>::Frozen);
|
||||
|
||||
let account = Account::<T, I>::get(id, who).ok_or(Error::<T, I>::NoAccount)?;
|
||||
@@ -258,7 +258,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
Ok(dust) => actual.saturating_add(dust), //< guaranteed by reducible_balance
|
||||
Err(e) => {
|
||||
debug_assert!(false, "passed from reducible_balance; qed");
|
||||
return Err(e.into())
|
||||
return Err(e)
|
||||
},
|
||||
};
|
||||
|
||||
@@ -291,7 +291,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
(true, Some(dust)) => (amount, Some(dust)),
|
||||
_ => (debit, None),
|
||||
};
|
||||
Self::can_increase(id, &dest, credit, false).into_result()?;
|
||||
Self::can_increase(id, dest, credit, false).into_result()?;
|
||||
Ok((credit, maybe_burn))
|
||||
}
|
||||
|
||||
@@ -352,7 +352,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
) -> DispatchResult {
|
||||
Self::increase_balance(id, beneficiary, amount, |details| -> DispatchResult {
|
||||
if let Some(check_issuer) = maybe_check_issuer {
|
||||
ensure!(&check_issuer == &details.issuer, Error::<T, I>::NoPermission);
|
||||
ensure!(check_issuer == details.issuer, Error::<T, I>::NoPermission);
|
||||
}
|
||||
debug_assert!(
|
||||
T::Balance::max_value() - details.supply >= amount,
|
||||
@@ -433,7 +433,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
let actual = Self::decrease_balance(id, target, amount, f, |actual, details| {
|
||||
// Check admin rights.
|
||||
if let Some(check_admin) = maybe_check_admin {
|
||||
ensure!(&check_admin == &details.admin, Error::<T, I>::NoPermission);
|
||||
ensure!(check_admin == details.admin, Error::<T, I>::NoPermission);
|
||||
}
|
||||
|
||||
debug_assert!(details.supply >= actual, "checked in prep; qed");
|
||||
@@ -471,7 +471,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
let mut target_died: Option<DeadConsequence> = None;
|
||||
|
||||
Asset::<T, I>::try_mutate(id, |maybe_details| -> DispatchResult {
|
||||
let mut details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
|
||||
check(actual, details)?;
|
||||
|
||||
@@ -483,8 +483,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
account.balance = account.balance.saturating_sub(actual);
|
||||
if account.balance < details.min_balance {
|
||||
debug_assert!(account.balance.is_zero(), "checked in prep; qed");
|
||||
target_died =
|
||||
Some(Self::dead_account(target, &mut details, &account.reason, false));
|
||||
target_died = Some(Self::dead_account(target, details, &account.reason, false));
|
||||
if let Some(Remove) = target_died {
|
||||
return Ok(())
|
||||
}
|
||||
@@ -543,8 +542,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
}
|
||||
|
||||
// Figure out the debit and credit, together with side-effects.
|
||||
let debit = Self::prep_debit(id, &source, amount, f.into())?;
|
||||
let (credit, maybe_burn) = Self::prep_credit(id, &dest, amount, debit, f.burn_dust)?;
|
||||
let debit = Self::prep_debit(id, source, amount, f.into())?;
|
||||
let (credit, maybe_burn) = Self::prep_credit(id, dest, amount, debit, f.burn_dust)?;
|
||||
|
||||
let mut source_account =
|
||||
Account::<T, I>::get(id, &source).ok_or(Error::<T, I>::NoAccount)?;
|
||||
@@ -555,7 +554,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
|
||||
// Check admin rights.
|
||||
if let Some(need_admin) = maybe_need_admin {
|
||||
ensure!(&need_admin == &details.admin, Error::<T, I>::NoPermission);
|
||||
ensure!(need_admin == details.admin, Error::<T, I>::NoPermission);
|
||||
}
|
||||
|
||||
// Skip if source == dest
|
||||
@@ -590,7 +589,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
*maybe_account = Some(AssetAccountOf::<T, I> {
|
||||
balance: credit,
|
||||
is_frozen: false,
|
||||
reason: Self::new_account(&dest, details, None)?,
|
||||
reason: Self::new_account(dest, details, None)?,
|
||||
extra: T::Extra::default(),
|
||||
});
|
||||
},
|
||||
@@ -602,7 +601,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
if source_account.balance < details.min_balance {
|
||||
debug_assert!(source_account.balance.is_zero(), "checked in prep; qed");
|
||||
source_died =
|
||||
Some(Self::dead_account(&source, details, &source_account.reason, false));
|
||||
Some(Self::dead_account(source, details, &source_account.reason, false));
|
||||
if let Some(Remove) = source_died {
|
||||
Account::<T, I>::remove(id, &source);
|
||||
return Ok(())
|
||||
@@ -746,7 +745,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
};
|
||||
let deposit_required = T::ApprovalDeposit::get();
|
||||
if approved.deposit < deposit_required {
|
||||
T::Currency::reserve(&owner, deposit_required - approved.deposit)?;
|
||||
T::Currency::reserve(owner, deposit_required - approved.deposit)?;
|
||||
approved.deposit = deposit_required;
|
||||
}
|
||||
approved.amount = approved.amount.saturating_add(amount);
|
||||
@@ -789,10 +788,10 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
approved.amount.checked_sub(&amount).ok_or(Error::<T, I>::Unapproved)?;
|
||||
|
||||
let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false };
|
||||
owner_died = Self::transfer_and_die(id, &owner, &destination, amount, None, f)?.1;
|
||||
owner_died = Self::transfer_and_die(id, owner, destination, amount, None, f)?.1;
|
||||
|
||||
if remaining.is_zero() {
|
||||
T::Currency::unreserve(&owner, approved.deposit);
|
||||
T::Currency::unreserve(owner, approved.deposit);
|
||||
Asset::<T, I>::mutate(id, |maybe_details| {
|
||||
if let Some(details) = maybe_details {
|
||||
details.approvals.saturating_dec();
|
||||
|
||||
@@ -42,7 +42,7 @@ impl<T: Config<I>, I: 'static> StoredMap<(T::AssetId, T::AccountId), T::Extra> f
|
||||
if let Some(ref mut account) = maybe_account {
|
||||
account.extra = extra;
|
||||
} else {
|
||||
Err(DispatchError::NoProviders)?;
|
||||
return Err(DispatchError::NoProviders.into())
|
||||
}
|
||||
} else {
|
||||
// They want to delete it. Let this pass if the item never existed anyway.
|
||||
|
||||
@@ -788,7 +788,7 @@ pub mod pallet {
|
||||
let origin = ensure_signed(origin)?;
|
||||
|
||||
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &d.freezer, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
|
||||
let who = T::Lookup::lookup(who)?;
|
||||
|
||||
Account::<T, I>::try_mutate(id, &who, |maybe_account| -> DispatchResult {
|
||||
@@ -819,7 +819,7 @@ pub mod pallet {
|
||||
let origin = ensure_signed(origin)?;
|
||||
|
||||
let details = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &details.admin, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == details.admin, Error::<T, I>::NoPermission);
|
||||
let who = T::Lookup::lookup(who)?;
|
||||
|
||||
Account::<T, I>::try_mutate(id, &who, |maybe_account| -> DispatchResult {
|
||||
@@ -849,7 +849,7 @@ pub mod pallet {
|
||||
|
||||
Asset::<T, I>::try_mutate(id, |maybe_details| {
|
||||
let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &d.freezer, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == d.freezer, Error::<T, I>::NoPermission);
|
||||
|
||||
d.is_frozen = true;
|
||||
|
||||
@@ -876,7 +876,7 @@ pub mod pallet {
|
||||
|
||||
Asset::<T, I>::try_mutate(id, |maybe_details| {
|
||||
let d = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &d.admin, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == d.admin, Error::<T, I>::NoPermission);
|
||||
|
||||
d.is_frozen = false;
|
||||
|
||||
@@ -906,7 +906,7 @@ pub mod pallet {
|
||||
|
||||
Asset::<T, I>::try_mutate(id, |maybe_details| {
|
||||
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &details.owner, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == details.owner, Error::<T, I>::NoPermission);
|
||||
if details.owner == owner {
|
||||
return Ok(())
|
||||
}
|
||||
@@ -951,7 +951,7 @@ pub mod pallet {
|
||||
|
||||
Asset::<T, I>::try_mutate(id, |maybe_details| {
|
||||
let details = maybe_details.as_mut().ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &details.owner, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == details.owner, Error::<T, I>::NoPermission);
|
||||
|
||||
details.issuer = issuer.clone();
|
||||
details.admin = admin.clone();
|
||||
@@ -1009,7 +1009,7 @@ pub mod pallet {
|
||||
let origin = ensure_signed(origin)?;
|
||||
|
||||
let d = Asset::<T, I>::get(id).ok_or(Error::<T, I>::Unknown)?;
|
||||
ensure!(&origin == &d.owner, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == d.owner, Error::<T, I>::NoPermission);
|
||||
|
||||
Metadata::<T, I>::try_mutate_exists(id, |metadata| {
|
||||
let deposit = metadata.take().ok_or(Error::<T, I>::Unknown)?.deposit;
|
||||
@@ -1241,7 +1241,7 @@ pub mod pallet {
|
||||
.map(|_| ())
|
||||
.or_else(|origin| -> DispatchResult {
|
||||
let origin = ensure_signed(origin)?;
|
||||
ensure!(&origin == &d.admin, Error::<T, I>::NoPermission);
|
||||
ensure!(origin == d.admin, Error::<T, I>::NoPermission);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
|
||||
@@ -104,9 +104,9 @@ impl<Balance> ExistenceReason<Balance> {
|
||||
if let ExistenceReason::DepositHeld(deposit) =
|
||||
sp_std::mem::replace(self, ExistenceReason::DepositRefunded)
|
||||
{
|
||||
return Some(deposit)
|
||||
Some(deposit)
|
||||
} else {
|
||||
return None
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ where
|
||||
C: ReservableCurrency<AccountId>,
|
||||
{
|
||||
fn reserve(&self, source: &AccountId) -> DispatchResult {
|
||||
C::reserve(&source, self.value)
|
||||
C::reserve(source, self.value)
|
||||
}
|
||||
|
||||
fn claim(&self, source: &AccountId, target: &AccountId) -> bool {
|
||||
@@ -267,7 +267,7 @@ pub mod pallet {
|
||||
action,
|
||||
end_block: frame_system::Pallet::<T>::block_number() + duration,
|
||||
};
|
||||
PendingSwaps::<T>::insert(target.clone(), hashed_proof.clone(), swap.clone());
|
||||
PendingSwaps::<T>::insert(target.clone(), hashed_proof, swap.clone());
|
||||
|
||||
Self::deposit_event(Event::NewSwap { account: target, proof: hashed_proof, swap });
|
||||
|
||||
@@ -303,7 +303,7 @@ pub mod pallet {
|
||||
|
||||
let succeeded = swap.action.claim(&swap.source, &target);
|
||||
|
||||
PendingSwaps::<T>::remove(target.clone(), hashed_proof.clone());
|
||||
PendingSwaps::<T>::remove(target.clone(), hashed_proof);
|
||||
|
||||
Self::deposit_event(Event::SwapClaimed {
|
||||
account: target,
|
||||
|
||||
@@ -261,7 +261,7 @@ impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::AuthorityId>
|
||||
let i = Inner::find_author(digests)?;
|
||||
|
||||
let validators = <Pallet<T>>::authorities();
|
||||
validators.get(i as usize).map(|k| k.clone())
|
||||
validators.get(i as usize).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ where
|
||||
let number = header.number();
|
||||
|
||||
if let Some(ref author) = author {
|
||||
if !acc.insert((number.clone(), author.clone())) {
|
||||
if !acc.insert((*number, author.clone())) {
|
||||
return Err("more than one uncle per number per author included")
|
||||
}
|
||||
}
|
||||
@@ -225,7 +225,7 @@ pub mod pallet {
|
||||
ensure!(new_uncles.len() <= MAX_UNCLES, Error::<T>::TooManyUncles);
|
||||
|
||||
if <DidSetUncles<T>>::get() {
|
||||
Err(Error::<T>::UnclesAlreadySet)?
|
||||
return Err(Error::<T>::UnclesAlreadySet.into())
|
||||
}
|
||||
<DidSetUncles<T>>::put(true);
|
||||
|
||||
@@ -334,7 +334,7 @@ impl<T: Config> Pallet<T> {
|
||||
let hash = uncle.hash();
|
||||
|
||||
if let Some(author) = maybe_author.clone() {
|
||||
T::EventHandler::note_uncle(author, now - uncle.number().clone());
|
||||
T::EventHandler::note_uncle(author, now - *uncle.number());
|
||||
}
|
||||
uncles.push(UncleEntryItem::Uncle(hash, maybe_author));
|
||||
}
|
||||
@@ -368,7 +368,7 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
|
||||
{
|
||||
let parent_number = uncle.number().clone() - One::one();
|
||||
let parent_number = *uncle.number() - One::one();
|
||||
let parent_hash = <frame_system::Pallet<T>>::block_hash(&parent_number);
|
||||
if &parent_hash != uncle.parent_hash() {
|
||||
return Err(Error::<T>::InvalidUncleParent.into())
|
||||
@@ -387,7 +387,7 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
|
||||
// check uncle validity.
|
||||
T::FilterUncle::filter_uncle(&uncle, accumulator).map_err(|e| Into::into(e))
|
||||
T::FilterUncle::filter_uncle(uncle, accumulator).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn prune_old_uncles(minimum_height: T::BlockNumber) {
|
||||
|
||||
@@ -438,7 +438,7 @@ impl<T: Config> FindAuthor<u32> for Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
return None
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,7 +641,7 @@ impl<T: Config> Pallet<T> {
|
||||
let segment_idx = segment_idx + 1;
|
||||
let bounded_randomness =
|
||||
BoundedVec::<_, ConstU32<UNDER_CONSTRUCTION_SEGMENT_LENGTH>>::try_from(vec![
|
||||
randomness.clone(),
|
||||
*randomness,
|
||||
])
|
||||
.expect("UNDER_CONSTRUCTION_SEGMENT_LENGTH >= 1");
|
||||
UnderConstruction::<T>::insert(&segment_idx, bounded_randomness);
|
||||
@@ -726,7 +726,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
vrf_output.0.attach_input_hash(&pubkey, transcript).ok()
|
||||
})
|
||||
.map(|inout| inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT))
|
||||
.map(|inout| inout.make_bytes(sp_consensus_babe::BABE_VRF_INOUT_CONTEXT))
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ fn main() {
|
||||
|
||||
match action {
|
||||
Action::Insert => {
|
||||
if BagsList::on_insert(id.clone(), vote_weight).is_err() {
|
||||
if BagsList::on_insert(id, vote_weight).is_err() {
|
||||
// this was a duplicate id, which is ok. We can just update it.
|
||||
BagsList::on_update(&id, vote_weight);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use frame_election_provider_support::ScoreProvider;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// A common log target to use.
|
||||
pub const LOG_TARGET: &'static str = "runtime::bags-list::remote-tests";
|
||||
pub const LOG_TARGET: &str = "runtime::bags-list::remote-tests";
|
||||
|
||||
pub mod migration;
|
||||
pub mod sanity_check;
|
||||
|
||||
@@ -133,7 +133,7 @@ frame_benchmarking::benchmarks! {
|
||||
List::<T, _>::get_bags(),
|
||||
vec![
|
||||
(origin_bag_thresh, vec![origin_head.clone()]),
|
||||
(dest_bag_thresh, vec![dest_head.clone(), origin_tail.clone()])
|
||||
(dest_bag_thresh, vec![dest_head.clone(), origin_tail])
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ pub use list::{notional_bag_for, Bag, List, ListError, Node};
|
||||
pub use pallet::*;
|
||||
pub use weights::WeightInfo;
|
||||
|
||||
pub(crate) const LOG_TARGET: &'static str = "runtime::bags_list";
|
||||
pub(crate) const LOG_TARGET: &str = "runtime::bags_list";
|
||||
|
||||
// syntactic sugar for logging.
|
||||
#[macro_export]
|
||||
@@ -254,7 +254,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
pub fn do_rebag(account: &T::AccountId, new_weight: T::Score) -> Option<(T::Score, T::Score)> {
|
||||
// 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, I>::get(&account)
|
||||
let maybe_movement = list::Node::<T, I>::get(account)
|
||||
.and_then(|node| List::update_position_for(node, new_weight));
|
||||
if let Some((from, to)) = maybe_movement {
|
||||
Self::deposit_event(Event::<T, I>::Rebagged { who: account.clone(), from, to });
|
||||
|
||||
@@ -59,7 +59,7 @@ mod tests;
|
||||
pub fn notional_bag_for<T: Config<I>, I: 'static>(score: T::Score) -> T::Score {
|
||||
let thresholds = T::BagThresholds::get();
|
||||
let idx = thresholds.partition_point(|&threshold| score > threshold);
|
||||
thresholds.get(idx).copied().unwrap_or(T::Score::max_value())
|
||||
thresholds.get(idx).copied().unwrap_or_else(T::Score::max_value)
|
||||
}
|
||||
|
||||
/// The **ONLY** entry point of this module. All operations to the bags-list should happen through
|
||||
@@ -163,7 +163,7 @@ impl<T: Config<I>, I: 'static> List<T, I> {
|
||||
let affected_bag = {
|
||||
// this recreates `notional_bag_for` logic, but with the old thresholds.
|
||||
let idx = old_thresholds.partition_point(|&threshold| inserted_bag > threshold);
|
||||
old_thresholds.get(idx).copied().unwrap_or(T::Score::max_value())
|
||||
old_thresholds.get(idx).copied().unwrap_or_else(T::Score::max_value)
|
||||
};
|
||||
if !affected_old_bags.insert(affected_bag) {
|
||||
// If the previous threshold list was [10, 20], and we insert [3, 5], then there's
|
||||
@@ -420,24 +420,24 @@ impl<T: Config<I>, I: 'static> List<T, I> {
|
||||
use crate::pallet;
|
||||
use frame_support::ensure;
|
||||
|
||||
let lighter_node = Node::<T, I>::get(&lighter_id).ok_or(pallet::Error::IdNotFound)?;
|
||||
let heavier_node = Node::<T, I>::get(&heavier_id).ok_or(pallet::Error::IdNotFound)?;
|
||||
let lighter_node = Node::<T, I>::get(lighter_id).ok_or(pallet::Error::IdNotFound)?;
|
||||
let heavier_node = Node::<T, I>::get(heavier_id).ok_or(pallet::Error::IdNotFound)?;
|
||||
|
||||
ensure!(lighter_node.bag_upper == heavier_node.bag_upper, pallet::Error::NotInSameBag);
|
||||
|
||||
// this is the most expensive check, so we do it last.
|
||||
ensure!(
|
||||
T::ScoreProvider::score(&heavier_id) > T::ScoreProvider::score(&lighter_id),
|
||||
T::ScoreProvider::score(heavier_id) > T::ScoreProvider::score(lighter_id),
|
||||
pallet::Error::NotHeavier
|
||||
);
|
||||
|
||||
// remove the heavier node from this list. Note that this removes the node from storage and
|
||||
// decrements the node counter.
|
||||
Self::remove(&heavier_id);
|
||||
Self::remove(heavier_id);
|
||||
|
||||
// re-fetch `lighter_node` from storage since it may have been updated when `heavier_node`
|
||||
// was removed.
|
||||
let lighter_node = Node::<T, I>::get(&lighter_id).ok_or_else(|| {
|
||||
let lighter_node = Node::<T, I>::get(lighter_id).ok_or_else(|| {
|
||||
debug_assert!(false, "id that should exist cannot be found");
|
||||
crate::log!(warn, "id that should exist cannot be found");
|
||||
pallet::Error::IdNotFound
|
||||
@@ -527,7 +527,7 @@ impl<T: Config<I>, I: 'static> List<T, I> {
|
||||
thresholds.into_iter().filter_map(|t| Bag::<T, I>::get(t))
|
||||
};
|
||||
|
||||
let _ = active_bags.clone().map(|b| b.sanity_check()).collect::<Result<_, _>>()?;
|
||||
let _ = active_bags.clone().try_for_each(|b| b.sanity_check())?;
|
||||
|
||||
let nodes_in_bags_count =
|
||||
active_bags.clone().fold(0u32, |acc, cur| acc + cur.iter().count() as u32);
|
||||
@@ -708,7 +708,7 @@ impl<T: Config<I>, I: 'static> Bag<T, I> {
|
||||
// the first insertion into the bag. In this case, both head and tail should point to the
|
||||
// same node.
|
||||
if self.head.is_none() {
|
||||
self.head = Some(id.clone());
|
||||
self.head = Some(id);
|
||||
debug_assert!(self.iter().count() == 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ impl frame_election_provider_support::ScoreProvider<AccountId> for StakingMock {
|
||||
|
||||
#[cfg(any(feature = "runtime-benchmarks", test))]
|
||||
fn set_score_of(id: &AccountId, weight: Self::Score) {
|
||||
NEXT_VOTE_WEIGHT_MAP.with(|m| m.borrow_mut().insert(id.clone(), weight));
|
||||
NEXT_VOTE_WEIGHT_MAP.with(|m| m.borrow_mut().insert(*id, weight));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -775,7 +775,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
|
||||
/// Get both the free and reserved balances of an account.
|
||||
fn account(who: &T::AccountId) -> AccountData<T::Balance> {
|
||||
T::AccountStore::get(&who)
|
||||
T::AccountStore::get(who)
|
||||
}
|
||||
|
||||
/// Handles any steps needed after mutating an account.
|
||||
@@ -988,17 +988,15 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
}
|
||||
} else {
|
||||
Locks::<T, I>::insert(who, bounded_locks);
|
||||
if !existed {
|
||||
if system::Pallet::<T>::inc_consumers_without_limit(who).is_err() {
|
||||
// No providers for the locks. This is impossible under normal circumstances
|
||||
// since the funds that are under the lock will themselves be stored in the
|
||||
// account and therefore will need a reference.
|
||||
log::warn!(
|
||||
target: "runtime::balances",
|
||||
"Warning: Attempt to introduce lock consumer reference, yet no providers. \
|
||||
This is unexpected but should be safe."
|
||||
);
|
||||
}
|
||||
if !existed && system::Pallet::<T>::inc_consumers_without_limit(who).is_err() {
|
||||
// No providers for the locks. This is impossible under normal circumstances
|
||||
// since the funds that are under the lock will themselves be stored in the
|
||||
// account and therefore will need a reference.
|
||||
log::warn!(
|
||||
target: "runtime::balances",
|
||||
"Warning: Attempt to introduce lock consumer reference, yet no providers. \
|
||||
This is unexpected but should be safe."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1107,7 +1105,7 @@ impl<T: Config<I>, I: 'static> fungible::Mutate<T::AccountId> for Pallet<T, I> {
|
||||
return Ok(())
|
||||
}
|
||||
Self::try_mutate_account(who, |account, _is_new| -> DispatchResult {
|
||||
Self::deposit_consequence(who, amount, &account, true).into_result()?;
|
||||
Self::deposit_consequence(who, amount, account, true).into_result()?;
|
||||
account.free += amount;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -1126,7 +1124,7 @@ impl<T: Config<I>, I: 'static> fungible::Mutate<T::AccountId> for Pallet<T, I> {
|
||||
let actual = Self::try_mutate_account(
|
||||
who,
|
||||
|account, _is_new| -> Result<T::Balance, DispatchError> {
|
||||
let extra = Self::withdraw_consequence(who, amount, &account).into_result()?;
|
||||
let extra = Self::withdraw_consequence(who, amount, account).into_result()?;
|
||||
let actual = amount + extra;
|
||||
account.free -= actual;
|
||||
Ok(actual)
|
||||
@@ -1214,7 +1212,7 @@ impl<T: Config<I>, I: 'static> fungible::MutateHold<T::AccountId> for Pallet<T,
|
||||
ensure!(best_effort || actual == amount, Error::<T, I>::InsufficientBalance);
|
||||
// ^^^ Guaranteed to be <= amount and <= a.reserved
|
||||
a.free = new_free;
|
||||
a.reserved = a.reserved.saturating_sub(actual.clone());
|
||||
a.reserved = a.reserved.saturating_sub(actual);
|
||||
Ok(actual)
|
||||
})
|
||||
}
|
||||
@@ -1318,7 +1316,7 @@ mod imbalances {
|
||||
}
|
||||
}
|
||||
fn peek(&self) -> T::Balance {
|
||||
self.0.clone()
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1377,7 +1375,7 @@ mod imbalances {
|
||||
}
|
||||
}
|
||||
fn peek(&self) -> T::Balance {
|
||||
self.0.clone()
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1560,7 +1558,7 @@ where
|
||||
if value.is_zero() {
|
||||
return (NegativeImbalance::zero(), Zero::zero())
|
||||
}
|
||||
if Self::total_balance(&who).is_zero() {
|
||||
if Self::total_balance(who).is_zero() {
|
||||
return (NegativeImbalance::zero(), value)
|
||||
}
|
||||
|
||||
@@ -1656,7 +1654,7 @@ where
|
||||
return Self::PositiveImbalance::zero()
|
||||
}
|
||||
|
||||
let r = Self::try_mutate_account(
|
||||
Self::try_mutate_account(
|
||||
who,
|
||||
|account, is_new| -> Result<Self::PositiveImbalance, DispatchError> {
|
||||
let ed = T::ExistentialDeposit::get();
|
||||
@@ -1673,9 +1671,7 @@ where
|
||||
Ok(PositiveImbalance::new(value))
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|_| Self::PositiveImbalance::zero());
|
||||
|
||||
r
|
||||
.unwrap_or_else(|_| Self::PositiveImbalance::zero())
|
||||
}
|
||||
|
||||
/// Withdraw some free balance from an account, respecting existence requirements.
|
||||
@@ -1785,7 +1781,7 @@ where
|
||||
account.free.checked_sub(&value).ok_or(Error::<T, I>::InsufficientBalance)?;
|
||||
account.reserved =
|
||||
account.reserved.checked_add(&value).ok_or(ArithmeticError::Overflow)?;
|
||||
Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free)
|
||||
Self::ensure_can_withdraw(&who, value, WithdrawReasons::RESERVE, account.free)
|
||||
})?;
|
||||
|
||||
Self::deposit_event(Event::Reserved { who: who.clone(), amount: value });
|
||||
@@ -1799,7 +1795,7 @@ where
|
||||
if value.is_zero() {
|
||||
return Zero::zero()
|
||||
}
|
||||
if Self::total_balance(&who).is_zero() {
|
||||
if Self::total_balance(who).is_zero() {
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -1820,7 +1816,7 @@ where
|
||||
},
|
||||
};
|
||||
|
||||
Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual.clone() });
|
||||
Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual });
|
||||
value - actual
|
||||
}
|
||||
|
||||
@@ -1835,7 +1831,7 @@ where
|
||||
if value.is_zero() {
|
||||
return (NegativeImbalance::zero(), Zero::zero())
|
||||
}
|
||||
if Self::total_balance(&who).is_zero() {
|
||||
if Self::total_balance(who).is_zero() {
|
||||
return (NegativeImbalance::zero(), value)
|
||||
}
|
||||
|
||||
@@ -1925,7 +1921,7 @@ where
|
||||
},
|
||||
Err(index) => {
|
||||
reserves
|
||||
.try_insert(index, ReserveData { id: id.clone(), amount: value })
|
||||
.try_insert(index, ReserveData { id: *id, amount: value })
|
||||
.map_err(|_| Error::<T, I>::TooManyReserves)?;
|
||||
},
|
||||
};
|
||||
@@ -2086,7 +2082,7 @@ where
|
||||
reserves
|
||||
.try_insert(
|
||||
index,
|
||||
ReserveData { id: id.clone(), amount: actual },
|
||||
ReserveData { id: *id, amount: actual },
|
||||
)
|
||||
.map_err(|_| Error::<T, I>::TooManyReserves)?;
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ impl Analysis {
|
||||
})
|
||||
.collect();
|
||||
|
||||
values.sort();
|
||||
values.sort_unstable();
|
||||
let mid = values.len() / 2;
|
||||
|
||||
Some(Self {
|
||||
@@ -216,7 +216,7 @@ impl Analysis {
|
||||
}
|
||||
|
||||
for (_, rs) in results.iter_mut() {
|
||||
rs.sort();
|
||||
rs.sort_unstable();
|
||||
let ql = rs.len() / 4;
|
||||
*rs = rs[ql..rs.len() - ql].to_vec();
|
||||
}
|
||||
@@ -255,7 +255,7 @@ impl Analysis {
|
||||
.iter()
|
||||
.map(|(p, vs)| {
|
||||
// Avoid divide by zero
|
||||
if vs.len() == 0 {
|
||||
if vs.is_empty() {
|
||||
return (p.clone(), 0, 0)
|
||||
}
|
||||
let total = vs.iter().fold(0u128, |acc, v| acc + *v);
|
||||
|
||||
@@ -99,7 +99,7 @@ benchmarks! {
|
||||
propose_curator {
|
||||
setup_pot_account::<T>();
|
||||
let (caller, curator, fee, value, reason) = setup_bounty::<T>(0, T::MaximumReasonLength::get());
|
||||
let curator_lookup = T::Lookup::unlookup(curator.clone());
|
||||
let curator_lookup = T::Lookup::unlookup(curator);
|
||||
Bounties::<T>::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?;
|
||||
let bounty_id = BountyCount::<T>::get() - 1;
|
||||
Bounties::<T>::approve_bounty(RawOrigin::Root.into(), bounty_id)?;
|
||||
|
||||
@@ -474,7 +474,7 @@ pub mod pallet {
|
||||
// Else this is the curator, willingly giving up their role.
|
||||
// Give back their deposit.
|
||||
let err_amount =
|
||||
T::Currency::unreserve(&curator, bounty.curator_deposit);
|
||||
T::Currency::unreserve(curator, bounty.curator_deposit);
|
||||
debug_assert!(err_amount.is_zero());
|
||||
bounty.curator_deposit = Zero::zero();
|
||||
// Continue to change bounty status below...
|
||||
@@ -706,7 +706,7 @@ pub mod pallet {
|
||||
BountyStatus::Active { curator, .. } => {
|
||||
// Cancelled by council, refund deposit of the working curator.
|
||||
let err_amount =
|
||||
T::Currency::unreserve(&curator, bounty.curator_deposit);
|
||||
T::Currency::unreserve(curator, bounty.curator_deposit);
|
||||
debug_assert!(err_amount.is_zero());
|
||||
// Then execute removal of the bounty below.
|
||||
},
|
||||
|
||||
@@ -110,7 +110,7 @@ fn activate_bounty<T: Config>(
|
||||
Bounties::<T>::propose_curator(
|
||||
RawOrigin::Root.into(),
|
||||
child_bounty_setup.bounty_id,
|
||||
curator_lookup.clone(),
|
||||
curator_lookup,
|
||||
child_bounty_setup.fee,
|
||||
)?;
|
||||
Bounties::<T>::accept_curator(
|
||||
@@ -141,7 +141,7 @@ fn activate_child_bounty<T: Config>(
|
||||
RawOrigin::Signed(bounty_setup.curator.clone()).into(),
|
||||
bounty_setup.bounty_id,
|
||||
bounty_setup.child_bounty_id,
|
||||
child_curator_lookup.clone(),
|
||||
child_curator_lookup,
|
||||
bounty_setup.child_bounty_fee,
|
||||
)?;
|
||||
|
||||
@@ -211,7 +211,7 @@ benchmarks! {
|
||||
RawOrigin::Signed(bounty_setup.curator.clone()).into(),
|
||||
bounty_setup.bounty_id,
|
||||
bounty_setup.child_bounty_id,
|
||||
child_curator_lookup.clone(),
|
||||
child_curator_lookup,
|
||||
bounty_setup.child_bounty_fee,
|
||||
)?;
|
||||
}: _(RawOrigin::Signed(bounty_setup.child_curator), bounty_setup.bounty_id,
|
||||
@@ -246,7 +246,7 @@ benchmarks! {
|
||||
setup_pot_account::<T>();
|
||||
let bounty_setup = activate_child_bounty::<T>(0, T::MaximumReasonLength::get())?;
|
||||
let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED);
|
||||
let beneficiary = T::Lookup::unlookup(beneficiary_account.clone());
|
||||
let beneficiary = T::Lookup::unlookup(beneficiary_account);
|
||||
|
||||
ChildBounties::<T>::award_child_bounty(
|
||||
RawOrigin::Signed(bounty_setup.child_curator.clone()).into(),
|
||||
|
||||
@@ -512,7 +512,7 @@ pub mod pallet {
|
||||
Some(sender) if sender == *curator => {
|
||||
// This is the child-bounty curator, willingly giving up their
|
||||
// role. Give back their deposit.
|
||||
T::Currency::unreserve(&curator, child_bounty.curator_deposit);
|
||||
T::Currency::unreserve(curator, child_bounty.curator_deposit);
|
||||
// Reset curator deposit.
|
||||
child_bounty.curator_deposit = Zero::zero();
|
||||
// Continue to change bounty status below.
|
||||
@@ -673,13 +673,13 @@ pub mod pallet {
|
||||
// Unreserve the curator deposit. Should not fail
|
||||
// because the deposit is always reserved when curator is
|
||||
// assigned.
|
||||
let _ = T::Currency::unreserve(&curator, child_bounty.curator_deposit);
|
||||
let _ = T::Currency::unreserve(curator, child_bounty.curator_deposit);
|
||||
|
||||
// Make payout to child-bounty curator.
|
||||
// Should not fail because curator fee is always less than bounty value.
|
||||
let fee_transfer_result = T::Currency::transfer(
|
||||
&child_bounty_account,
|
||||
&curator,
|
||||
curator,
|
||||
curator_fee,
|
||||
AllowDeath,
|
||||
);
|
||||
|
||||
@@ -250,7 +250,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -259,7 +259,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -272,7 +272,7 @@ benchmarks_instance_pallet! {
|
||||
// Whitelist voter account from further DB operations.
|
||||
let voter_key = frame_system::Account::<T>::hashed_key_for(&voter);
|
||||
frame_benchmarking::benchmarking::add_to_whitelist(voter_key.into());
|
||||
}: _(SystemOrigin::Signed(voter), last_hash.clone(), index, approve)
|
||||
}: _(SystemOrigin::Signed(voter), last_hash, index, approve)
|
||||
verify {
|
||||
// All proposals exist and the last proposal has just been updated.
|
||||
assert_eq!(Collective::<T, I>::proposals().len(), p as usize);
|
||||
@@ -327,7 +327,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -336,7 +336,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -347,7 +347,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = false;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -355,7 +355,7 @@ benchmarks_instance_pallet! {
|
||||
// Whitelist voter account from further DB operations.
|
||||
let voter_key = frame_system::Account::<T>::hashed_key_for(&voter);
|
||||
frame_benchmarking::benchmarking::add_to_whitelist(voter_key.into());
|
||||
}: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::max_value(), bytes_in_storage)
|
||||
}: close(SystemOrigin::Signed(voter), last_hash, index, Weight::max_value(), bytes_in_storage)
|
||||
verify {
|
||||
// The last proposal is removed.
|
||||
assert_eq!(Collective::<T, I>::proposals().len(), (p - 1) as usize);
|
||||
@@ -400,7 +400,7 @@ benchmarks_instance_pallet! {
|
||||
// Caller switches vote to nay on their own proposal, allowing them to be the deciding approval vote
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(caller.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
p - 1,
|
||||
false,
|
||||
)?;
|
||||
@@ -411,7 +411,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = false;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
p - 1,
|
||||
approve,
|
||||
)?;
|
||||
@@ -420,7 +420,7 @@ benchmarks_instance_pallet! {
|
||||
// Member zero is the first aye
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(members[0].clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
p - 1,
|
||||
true,
|
||||
)?;
|
||||
@@ -432,11 +432,11 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(caller.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index, approve,
|
||||
)?;
|
||||
|
||||
}: close(SystemOrigin::Signed(caller), last_hash.clone(), index, Weight::max_value(), bytes_in_storage)
|
||||
}: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage)
|
||||
verify {
|
||||
// The last proposal is removed.
|
||||
assert_eq!(Collective::<T, I>::proposals().len(), (p - 1) as usize);
|
||||
@@ -493,7 +493,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = true;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
approve,
|
||||
)?;
|
||||
@@ -502,7 +502,7 @@ benchmarks_instance_pallet! {
|
||||
// caller is prime, prime votes nay
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(caller.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
index,
|
||||
false,
|
||||
)?;
|
||||
@@ -560,7 +560,7 @@ benchmarks_instance_pallet! {
|
||||
// The prime member votes aye, so abstentions default to aye.
|
||||
Collective::<T, _>::vote(
|
||||
SystemOrigin::Signed(caller.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
p - 1,
|
||||
true // Vote aye.
|
||||
)?;
|
||||
@@ -572,7 +572,7 @@ benchmarks_instance_pallet! {
|
||||
let approve = false;
|
||||
Collective::<T, I>::vote(
|
||||
SystemOrigin::Signed(voter.clone()).into(),
|
||||
last_hash.clone(),
|
||||
last_hash,
|
||||
p - 1,
|
||||
approve
|
||||
)?;
|
||||
|
||||
@@ -277,15 +277,14 @@ where
|
||||
}
|
||||
module
|
||||
};
|
||||
let limits = module
|
||||
let limits = *module
|
||||
.import_section()
|
||||
.unwrap()
|
||||
.entries()
|
||||
.iter()
|
||||
.find_map(|e| if let External::Memory(mem) = e.external() { Some(mem) } else { None })
|
||||
.unwrap()
|
||||
.limits()
|
||||
.clone();
|
||||
.limits();
|
||||
let code = module.to_bytes().unwrap();
|
||||
let hash = T::Hashing::hash(&code);
|
||||
let memory =
|
||||
@@ -512,16 +511,10 @@ pub mod body {
|
||||
DynInstr::RandomI32(low, high) => {
|
||||
vec![Instruction::I32Const(rng.gen_range(*low..*high))]
|
||||
},
|
||||
DynInstr::RandomI32Repeated(num) => (&mut rng)
|
||||
.sample_iter(Standard)
|
||||
.take(*num)
|
||||
.map(|val| Instruction::I32Const(val))
|
||||
.collect(),
|
||||
DynInstr::RandomI64Repeated(num) => (&mut rng)
|
||||
.sample_iter(Standard)
|
||||
.take(*num)
|
||||
.map(|val| Instruction::I64Const(val))
|
||||
.collect(),
|
||||
DynInstr::RandomI32Repeated(num) =>
|
||||
(&mut rng).sample_iter(Standard).take(*num).map(Instruction::I32Const).collect(),
|
||||
DynInstr::RandomI64Repeated(num) =>
|
||||
(&mut rng).sample_iter(Standard).take(*num).map(Instruction::I64Const).collect(),
|
||||
DynInstr::RandomGetLocal(low, high) => {
|
||||
vec![Instruction::GetLocal(rng.gen_range(*low..*high))]
|
||||
},
|
||||
|
||||
@@ -138,7 +138,7 @@ where
|
||||
Storage::<T>::write(&info.trie_id, &item.0, Some(item.1.clone()), None, false)
|
||||
.map_err(|_| "Failed to write storage to restoration dest")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&self.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&self.account_id, info);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -253,7 +253,7 @@ benchmarks! {
|
||||
)?;
|
||||
let value = T::Currency::minimum_balance();
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
let callee = instance.addr.clone();
|
||||
let callee = instance.addr;
|
||||
}: call(origin, callee, value, Weight::MAX, None, vec![])
|
||||
|
||||
// This constructs a contract that is maximal expensive to instrument.
|
||||
@@ -1067,7 +1067,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1164,7 +1164,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1216,7 +1216,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1263,7 +1263,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1308,7 +1308,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1360,7 +1360,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1412,7 +1412,7 @@ benchmarks! {
|
||||
)
|
||||
.map_err(|_| "Failed to write to storage during setup.")?;
|
||||
}
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info.clone());
|
||||
<ContractInfoOf<T>>::insert(&instance.account_id, info);
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
}: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
@@ -1577,7 +1577,7 @@ benchmarks! {
|
||||
});
|
||||
let instance = Contract::<T>::new(code, vec![])?;
|
||||
let callee = instance.addr.clone();
|
||||
let origin = RawOrigin::Signed(instance.caller.clone());
|
||||
let origin = RawOrigin::Signed(instance.caller);
|
||||
}: call(origin, callee, 0u32.into(), Weight::MAX, None, vec![])
|
||||
|
||||
seal_call_per_transfer_clone_kb {
|
||||
@@ -1739,7 +1739,7 @@ benchmarks! {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for addr in &addresses {
|
||||
if let Some(_) = ContractInfoOf::<T>::get(&addr) {
|
||||
if ContractInfoOf::<T>::get(&addr).is_some() {
|
||||
return Err("Expected that contract does not exist at this point.".into());
|
||||
}
|
||||
}
|
||||
@@ -1747,7 +1747,7 @@ benchmarks! {
|
||||
verify {
|
||||
for addr in &addresses {
|
||||
ContractInfoOf::<T>::get(&addr)
|
||||
.ok_or_else(|| "Contract should have been instantiated")?;
|
||||
.ok_or("Contract should have been instantiated")?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1755,7 +1755,7 @@ benchmarks! {
|
||||
let t in 0 .. 1;
|
||||
let s in 0 .. (code::max_pages::<T>() - 1) * 64;
|
||||
let callee_code = WasmModule::<T>::dummy();
|
||||
let hash = callee_code.hash.clone();
|
||||
let hash = callee_code.hash;
|
||||
let hash_bytes = callee_code.hash.encode();
|
||||
let hash_len = hash_bytes.len();
|
||||
Contracts::<T>::store_code_raw(callee_code.code, whitelisted_caller())?;
|
||||
|
||||
@@ -610,7 +610,7 @@ where
|
||||
debug_message: Option<&'a mut Vec<u8>>,
|
||||
) -> Result<(Self, E), ExecError> {
|
||||
let (first_frame, executable, nonce) =
|
||||
Self::new_frame(args, value, gas_meter, storage_meter, 0, &schedule)?;
|
||||
Self::new_frame(args, value, gas_meter, storage_meter, 0, schedule)?;
|
||||
let stack = Self {
|
||||
origin,
|
||||
schedule,
|
||||
@@ -660,13 +660,10 @@ where
|
||||
},
|
||||
FrameArgs::Instantiate { sender, nonce, executable, salt } => {
|
||||
let account_id =
|
||||
<Contracts<T>>::contract_address(&sender, executable.code_hash(), &salt);
|
||||
<Contracts<T>>::contract_address(&sender, executable.code_hash(), salt);
|
||||
let trie_id = Storage::<T>::generate_trie_id(&account_id, nonce);
|
||||
let contract = Storage::<T>::new_contract(
|
||||
&account_id,
|
||||
trie_id,
|
||||
executable.code_hash().clone(),
|
||||
)?;
|
||||
let contract =
|
||||
Storage::<T>::new_contract(&account_id, trie_id, *executable.code_hash())?;
|
||||
(
|
||||
account_id,
|
||||
contract,
|
||||
@@ -742,7 +739,7 @@ where
|
||||
top_frame.nested_storage.charge_instantiate(
|
||||
&self.origin,
|
||||
&top_frame.account_id,
|
||||
&mut top_frame.contract_info.get(&top_frame.account_id),
|
||||
top_frame.contract_info.get(&top_frame.account_id),
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -1020,11 +1017,11 @@ where
|
||||
code_hash: CodeHash<Self::T>,
|
||||
input_data: Vec<u8>,
|
||||
) -> Result<ExecReturnValue, ExecError> {
|
||||
let executable = E::from_storage(code_hash, &self.schedule, self.gas_meter())?;
|
||||
let executable = E::from_storage(code_hash, self.schedule, self.gas_meter())?;
|
||||
let top_frame = self.top_frame_mut();
|
||||
let contract_info = top_frame.contract_info().clone();
|
||||
let account_id = top_frame.account_id.clone();
|
||||
let value = top_frame.value_transferred.clone();
|
||||
let value = top_frame.value_transferred;
|
||||
let executable = self.push_frame(
|
||||
FrameArgs::Call {
|
||||
dest: account_id,
|
||||
@@ -1045,7 +1042,7 @@ where
|
||||
input_data: Vec<u8>,
|
||||
salt: &[u8],
|
||||
) -> Result<(AccountIdOf<T>, ExecReturnValue), ExecError> {
|
||||
let executable = E::from_storage(code_hash, &self.schedule, self.gas_meter())?;
|
||||
let executable = E::from_storage(code_hash, self.schedule, self.gas_meter())?;
|
||||
let nonce = self.next_nonce();
|
||||
let executable = self.push_frame(
|
||||
FrameArgs::Instantiate {
|
||||
@@ -1118,7 +1115,7 @@ where
|
||||
|
||||
fn caller(&self) -> &T::AccountId {
|
||||
if let Some(caller) = &self.top_frame().delegate_caller {
|
||||
&caller
|
||||
caller
|
||||
} else {
|
||||
self.frames().nth(1).map(|f| &f.account_id).unwrap_or(&self.origin)
|
||||
}
|
||||
@@ -1180,7 +1177,7 @@ where
|
||||
}
|
||||
|
||||
fn schedule(&self) -> &Schedule<Self::T> {
|
||||
&self.schedule
|
||||
self.schedule
|
||||
}
|
||||
|
||||
fn gas_meter(&mut self) -> &mut GasMeter<Self::T> {
|
||||
@@ -1205,7 +1202,7 @@ where
|
||||
}
|
||||
|
||||
fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> {
|
||||
secp256k1_ecdsa_recover_compressed(&signature, &message_hash).map_err(|_| ())
|
||||
secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ())
|
||||
}
|
||||
|
||||
fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()> {
|
||||
@@ -1220,8 +1217,8 @@ where
|
||||
fn set_code_hash(&mut self, hash: CodeHash<Self::T>) -> Result<(), DispatchError> {
|
||||
E::add_user(hash)?;
|
||||
let top_frame = self.top_frame_mut();
|
||||
let prev_hash = top_frame.contract_info().code_hash.clone();
|
||||
E::remove_user(prev_hash.clone());
|
||||
let prev_hash = top_frame.contract_info().code_hash;
|
||||
E::remove_user(prev_hash);
|
||||
top_frame.contract_info().code_hash = hash;
|
||||
Contracts::<Self::T>::deposit_event(Event::ContractCodeUpdated {
|
||||
contract: top_frame.account_id.clone(),
|
||||
|
||||
@@ -114,7 +114,7 @@ where
|
||||
if self.gas_left < amount {
|
||||
Err(<Error<T>>::OutOfGas.into())
|
||||
} else {
|
||||
self.gas_left = self.gas_left - amount;
|
||||
self.gas_left -= amount;
|
||||
Ok(GasMeter::new(amount))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,7 +670,7 @@ struct ScheduleRules<'a, T: Config> {
|
||||
impl<T: Config> Schedule<T> {
|
||||
pub(crate) fn rules(&self, module: &elements::Module) -> impl gas_metering::Rules + '_ {
|
||||
ScheduleRules {
|
||||
schedule: &self,
|
||||
schedule: self,
|
||||
params: module
|
||||
.type_section()
|
||||
.iter()
|
||||
|
||||
@@ -154,10 +154,10 @@ where
|
||||
let hashed_key = blake2_256(key);
|
||||
let child_trie_info = &child_trie_info(trie_id);
|
||||
let (old_len, old_value) = if take {
|
||||
let val = child::get_raw(&child_trie_info, &hashed_key);
|
||||
let val = child::get_raw(child_trie_info, &hashed_key);
|
||||
(val.as_ref().map(|v| v.len() as u32), val)
|
||||
} else {
|
||||
(child::len(&child_trie_info, &hashed_key), None)
|
||||
(child::len(child_trie_info, &hashed_key), None)
|
||||
};
|
||||
|
||||
if let Some(storage_meter) = storage_meter {
|
||||
@@ -183,8 +183,8 @@ where
|
||||
}
|
||||
|
||||
match &new_value {
|
||||
Some(new_value) => child::put_raw(&child_trie_info, &hashed_key, new_value),
|
||||
None => child::kill(&child_trie_info, &hashed_key),
|
||||
Some(new_value) => child::put_raw(child_trie_info, &hashed_key, new_value),
|
||||
None => child::kill(child_trie_info, &hashed_key),
|
||||
}
|
||||
|
||||
Ok(match (old_len, old_value) {
|
||||
|
||||
@@ -230,7 +230,7 @@ where
|
||||
|
||||
self.total_deposit = self.total_deposit.saturating_add(&absorbed.total_deposit);
|
||||
if !absorbed.own_deposit.is_zero() {
|
||||
E::charge(origin, &contract, &absorbed.own_deposit, absorbed.terminated);
|
||||
E::charge(origin, contract, &absorbed.own_deposit, absorbed.terminated);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ where
|
||||
limit: Option<BalanceOf<T>>,
|
||||
min_leftover: BalanceOf<T>,
|
||||
) -> Result<Self, DispatchError> {
|
||||
let limit = E::check_limit(&origin, limit, min_leftover)?;
|
||||
let limit = E::check_limit(origin, limit, min_leftover)?;
|
||||
Ok(Self { limit, ..Default::default() })
|
||||
}
|
||||
|
||||
|
||||
@@ -165,8 +165,7 @@ where
|
||||
{
|
||||
let charged = gas_meter.charge(CodeToken::Load(schedule.limits.code_len))?;
|
||||
|
||||
let mut prefab_module =
|
||||
<CodeStorage<T>>::get(code_hash).ok_or_else(|| Error::<T>::CodeNotFound)?;
|
||||
let mut prefab_module = <CodeStorage<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
|
||||
gas_meter.adjust_gas(charged, CodeToken::Load(prefab_module.code.len() as u32));
|
||||
prefab_module.code_hash = code_hash;
|
||||
|
||||
@@ -189,7 +188,7 @@ pub fn reinstrument<T: Config>(
|
||||
schedule: &Schedule<T>,
|
||||
) -> Result<u32, DispatchError> {
|
||||
let original_code =
|
||||
<PristineCode<T>>::get(&prefab_module.code_hash).ok_or_else(|| Error::<T>::CodeNotFound)?;
|
||||
<PristineCode<T>>::get(&prefab_module.code_hash).ok_or(Error::<T>::CodeNotFound)?;
|
||||
let original_code_len = original_code.len();
|
||||
prefab_module.code = prepare::reinstrument_contract::<T>(original_code, schedule)?;
|
||||
prefab_module.instruction_weights_version = schedule.instruction_weights.version;
|
||||
|
||||
@@ -225,10 +225,7 @@ impl<'a, T: Config> ContractModule<'a, T> {
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|entry| match *entry.external() {
|
||||
External::Function(_) => true,
|
||||
_ => false,
|
||||
})
|
||||
.filter(|entry| matches!(*entry.external(), External::Function(_)))
|
||||
.count();
|
||||
|
||||
for export in export_entries {
|
||||
@@ -259,11 +256,10 @@ impl<'a, T: Config> ContractModule<'a, T> {
|
||||
// We still support () -> (i32) for backwards compatibility.
|
||||
let func_ty_idx = func_entries
|
||||
.get(fn_idx as usize)
|
||||
.ok_or_else(|| "export refers to non-existent function")?
|
||||
.ok_or("export refers to non-existent function")?
|
||||
.type_ref();
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(func_ty_idx as usize)
|
||||
.ok_or_else(|| "function has a non-existent type")?;
|
||||
let Type::Function(ref func_ty) =
|
||||
types.get(func_ty_idx as usize).ok_or("function has a non-existent type")?;
|
||||
if !(func_ty.params().is_empty() &&
|
||||
(func_ty.results().is_empty() || func_ty.results() == [ValueType::I32]))
|
||||
{
|
||||
@@ -300,11 +296,11 @@ impl<'a, T: Config> ContractModule<'a, T> {
|
||||
let mut imported_mem_type = None;
|
||||
|
||||
for import in import_entries {
|
||||
let type_idx = match import.external() {
|
||||
&External::Table(_) => return Err("Cannot import tables"),
|
||||
&External::Global(_) => return Err("Cannot import globals"),
|
||||
&External::Function(ref type_idx) => type_idx,
|
||||
&External::Memory(ref memory_type) => {
|
||||
let type_idx = match *import.external() {
|
||||
External::Table(_) => return Err("Cannot import tables"),
|
||||
External::Global(_) => return Err("Cannot import globals"),
|
||||
External::Function(ref type_idx) => type_idx,
|
||||
External::Memory(ref memory_type) => {
|
||||
if import.module() != IMPORT_MODULE_MEMORY {
|
||||
return Err("Invalid module for imported memory")
|
||||
}
|
||||
@@ -321,7 +317,7 @@ impl<'a, T: Config> ContractModule<'a, T> {
|
||||
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(*type_idx as usize)
|
||||
.ok_or_else(|| "validation: import entry points to a non-existent type")?;
|
||||
.ok_or("validation: import entry points to a non-existent type")?;
|
||||
|
||||
if !T::ChainExtension::enabled() &&
|
||||
import.field().as_bytes() == b"seal_call_chain_extension"
|
||||
@@ -352,17 +348,15 @@ fn get_memory_limits<T: Config>(
|
||||
let limits = memory_type.limits();
|
||||
match (limits.initial(), limits.maximum()) {
|
||||
(initial, Some(maximum)) if initial > maximum =>
|
||||
return Err(
|
||||
"Requested initial number of pages should not exceed the requested maximum",
|
||||
),
|
||||
Err("Requested initial number of pages should not exceed the requested maximum"),
|
||||
(_, Some(maximum)) if maximum > schedule.limits.memory_pages =>
|
||||
return Err("Maximum number of pages should not exceed the configured maximum."),
|
||||
Err("Maximum number of pages should not exceed the configured maximum."),
|
||||
(initial, Some(maximum)) => Ok((initial, maximum)),
|
||||
(_, None) => {
|
||||
// Maximum number of pages should be always declared.
|
||||
// This isn't a hard requirement and can be treated as a maximum set
|
||||
// to configured maximum.
|
||||
return Err("Maximum number of pages should be always declared.")
|
||||
Err("Maximum number of pages should be always declared.")
|
||||
},
|
||||
}
|
||||
} else {
|
||||
@@ -377,7 +371,7 @@ fn check_and_instrument<C: ImportSatisfyCheck, T: Config>(
|
||||
schedule: &Schedule<T>,
|
||||
) -> Result<(Vec<u8>, (u32, u32)), &'static str> {
|
||||
let result = (|| {
|
||||
let contract_module = ContractModule::new(&original_code, schedule)?;
|
||||
let contract_module = ContractModule::new(original_code, schedule)?;
|
||||
contract_module.scan_exports()?;
|
||||
contract_module.ensure_no_internal_memory()?;
|
||||
contract_module.ensure_table_size_limit(schedule.limits.table_size)?;
|
||||
|
||||
@@ -460,13 +460,13 @@ where
|
||||
return match trap_reason {
|
||||
// The trap was the result of the execution `return` host function.
|
||||
TrapReason::Return(ReturnData { flags, data }) => {
|
||||
let flags = ReturnFlags::from_bits(flags)
|
||||
.ok_or_else(|| Error::<E::T>::InvalidCallFlags)?;
|
||||
let flags =
|
||||
ReturnFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?;
|
||||
Ok(ExecReturnValue { flags, data: Bytes(data) })
|
||||
},
|
||||
TrapReason::Termination =>
|
||||
Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }),
|
||||
TrapReason::SupervisorError(error) => Err(error)?,
|
||||
TrapReason::SupervisorError(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,10 +480,10 @@ where
|
||||
//
|
||||
// Because panics are really undesirable in the runtime code, we treat this as
|
||||
// a trap for now. Eventually, we might want to revisit this.
|
||||
Err(sp_sandbox::Error::Module) => Err("validation error")?,
|
||||
Err(sp_sandbox::Error::Module) => return Err("validation error".into()),
|
||||
// Any other kind of a trap should result in a failure.
|
||||
Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) =>
|
||||
Err(Error::<E::T>::ContractTrapped)?,
|
||||
return Err(Error::<E::T>::ContractTrapped.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -620,7 +620,7 @@ where
|
||||
let len: u32 = self.read_sandbox_memory_as(out_len_ptr)?;
|
||||
|
||||
if len < buf_len {
|
||||
Err(Error::<E::T>::OutputBufferTooSmall)?
|
||||
return Err(Error::<E::T>::OutputBufferTooSmall.into())
|
||||
}
|
||||
|
||||
if let Some(costs) = create_token(buf_len) {
|
||||
@@ -717,7 +717,7 @@ where
|
||||
let charged = self
|
||||
.charge_gas(RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: max_size })?;
|
||||
if value_len > max_size {
|
||||
Err(Error::<E::T>::ValueTooLarge)?;
|
||||
return Err(Error::<E::T>::ValueTooLarge.into())
|
||||
}
|
||||
let mut key: StorageKey = [0; 32];
|
||||
self.read_sandbox_memory_into_buf(key_ptr, &mut key)?;
|
||||
@@ -750,11 +750,11 @@ where
|
||||
) -> Result<ReturnCode, TrapReason> {
|
||||
self.charge_gas(call_type.cost())?;
|
||||
let input_data = if flags.contains(CallFlags::CLONE_INPUT) {
|
||||
let input = self.input_data.as_ref().ok_or_else(|| Error::<E::T>::InputForwarded)?;
|
||||
let input = self.input_data.as_ref().ok_or(Error::<E::T>::InputForwarded)?;
|
||||
charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?;
|
||||
input.clone()
|
||||
} else if flags.contains(CallFlags::FORWARD_INPUT) {
|
||||
self.input_data.take().ok_or_else(|| Error::<E::T>::InputForwarded)?
|
||||
self.input_data.take().ok_or(Error::<E::T>::InputForwarded)?
|
||||
} else {
|
||||
self.charge_gas(RuntimeCosts::CopyFromContract(input_data_len))?;
|
||||
self.read_sandbox_memory(input_data_ptr, input_data_len)?
|
||||
@@ -1108,7 +1108,7 @@ define_env!(Env, <E: Ext>,
|
||||
output_len_ptr: u32
|
||||
) -> ReturnCode => {
|
||||
ctx.call(
|
||||
CallFlags::from_bits(flags).ok_or_else(|| Error::<E::T>::InvalidCallFlags)?,
|
||||
CallFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?,
|
||||
CallType::Call{callee_ptr, value_ptr, gas},
|
||||
input_data_ptr,
|
||||
input_data_len,
|
||||
@@ -1151,7 +1151,7 @@ define_env!(Env, <E: Ext>,
|
||||
output_len_ptr: u32
|
||||
) -> ReturnCode => {
|
||||
ctx.call(
|
||||
CallFlags::from_bits(flags).ok_or_else(|| Error::<E::T>::InvalidCallFlags)?,
|
||||
CallFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?,
|
||||
CallType::DelegateCall{code_hash_ptr},
|
||||
input_data_ptr,
|
||||
input_data_len,
|
||||
@@ -1486,7 +1486,7 @@ define_env!(Env, <E: Ext>,
|
||||
ctx.charge_gas(RuntimeCosts::GasLeft)?;
|
||||
let gas_left = &ctx.ext.gas_meter().gas_left().encode();
|
||||
Ok(ctx.write_sandbox_output(
|
||||
out_ptr, out_len_ptr, &gas_left, false, already_charged,
|
||||
out_ptr, out_len_ptr, gas_left, false, already_charged,
|
||||
)?)
|
||||
},
|
||||
|
||||
@@ -1535,7 +1535,7 @@ define_env!(Env, <E: Ext>,
|
||||
[seal0] seal_random(ctx, subject_ptr: u32, subject_len: u32, out_ptr: u32, out_len_ptr: u32) => {
|
||||
ctx.charge_gas(RuntimeCosts::Random)?;
|
||||
if subject_len > ctx.ext.schedule().limits.subject_len {
|
||||
Err(Error::<E::T>::RandomSubjectTooLong)?;
|
||||
return Err(Error::<E::T>::RandomSubjectTooLong.into());
|
||||
}
|
||||
let subject_buf = ctx.read_sandbox_memory(subject_ptr, subject_len)?;
|
||||
Ok(ctx.write_sandbox_output(
|
||||
@@ -1567,7 +1567,7 @@ define_env!(Env, <E: Ext>,
|
||||
[seal1] seal_random(ctx, subject_ptr: u32, subject_len: u32, out_ptr: u32, out_len_ptr: u32) => {
|
||||
ctx.charge_gas(RuntimeCosts::Random)?;
|
||||
if subject_len > ctx.ext.schedule().limits.subject_len {
|
||||
Err(Error::<E::T>::RandomSubjectTooLong)?;
|
||||
return Err(Error::<E::T>::RandomSubjectTooLong.into());
|
||||
}
|
||||
let subject_buf = ctx.read_sandbox_memory(subject_ptr, subject_len)?;
|
||||
Ok(ctx.write_sandbox_output(
|
||||
@@ -1685,13 +1685,13 @@ define_env!(Env, <E: Ext>,
|
||||
|
||||
let num_topic = topics_len
|
||||
.checked_div(sp_std::mem::size_of::<TopicOf<E::T>>() as u32)
|
||||
.ok_or_else(|| "Zero sized topics are not allowed")?;
|
||||
.ok_or("Zero sized topics are not allowed")?;
|
||||
ctx.charge_gas(RuntimeCosts::DepositEvent {
|
||||
num_topic,
|
||||
len: data_len,
|
||||
})?;
|
||||
if data_len > ctx.ext.max_value_size() {
|
||||
Err(Error::<E::T>::ValueTooLarge)?;
|
||||
return Err(Error::<E::T>::ValueTooLarge.into());
|
||||
}
|
||||
|
||||
let mut topics: Vec::<TopicOf<<E as Ext>::T>> = match topics_len {
|
||||
@@ -1701,14 +1701,14 @@ define_env!(Env, <E: Ext>,
|
||||
|
||||
// If there are more than `event_topics`, then trap.
|
||||
if topics.len() > ctx.ext.schedule().limits.event_topics as usize {
|
||||
Err(Error::<E::T>::TooManyTopics)?;
|
||||
return Err(Error::<E::T>::TooManyTopics.into());
|
||||
}
|
||||
|
||||
// Check for duplicate topics. If there are any, then trap.
|
||||
// Complexity O(n * log(n)) and no additional allocations.
|
||||
// This also sorts the topics.
|
||||
if has_duplicates(&mut topics) {
|
||||
Err(Error::<E::T>::DuplicateTopics)?;
|
||||
return Err(Error::<E::T>::DuplicateTopics.into());
|
||||
}
|
||||
|
||||
let event_data = ctx.read_sandbox_memory(data_ptr, data_len)?;
|
||||
@@ -1888,7 +1888,7 @@ define_env!(Env, <E: Ext>,
|
||||
) -> u32 => {
|
||||
use crate::chain_extension::{ChainExtension, Environment, RetVal};
|
||||
if !<E::T as Config>::ChainExtension::enabled() {
|
||||
Err(Error::<E::T>::NoChainExtension)?;
|
||||
return Err(Error::<E::T>::NoChainExtension.into());
|
||||
}
|
||||
let env = Environment::new(ctx, input_ptr, input_len, output_ptr, output_len_ptr);
|
||||
match <E::T as Config>::ChainExtension::call(func_id, env)? {
|
||||
|
||||
@@ -44,7 +44,7 @@ fn fill_voting<T: Config>() -> (ClassOf<T>, BTreeMap<ClassOf<T>, Vec<IndexOf<T>>
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = r.iter().max_by_key(|(_, ref v)| v.len()).unwrap().0.clone();
|
||||
let c = r.iter().max_by_key(|(_, v)| v.len()).unwrap().0.clone();
|
||||
(c, r)
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ benchmarks! {
|
||||
let r = polls.len() - 1;
|
||||
// We need to create existing votes
|
||||
for i in polls.iter().skip(1) {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, account_vote)?;
|
||||
}
|
||||
let votes = match VotingFor::<T>::get(&caller, &class) {
|
||||
Voting::Casting(Casting { votes, .. }) => votes,
|
||||
@@ -100,7 +100,7 @@ benchmarks! {
|
||||
let r = polls.len();
|
||||
// We need to create existing votes
|
||||
for i in polls.iter() {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote)?;
|
||||
}
|
||||
let votes = match VotingFor::<T>::get(&caller, &class) {
|
||||
Voting::Casting(Casting { votes, .. }) => votes,
|
||||
@@ -128,7 +128,7 @@ benchmarks! {
|
||||
let r = polls.len();
|
||||
// We need to create existing votes
|
||||
for i in polls.iter() {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote)?;
|
||||
}
|
||||
let votes = match VotingFor::<T>::get(&caller, &class) {
|
||||
Voting::Casting(Casting { votes, .. }) => votes,
|
||||
@@ -156,7 +156,7 @@ benchmarks! {
|
||||
let r = polls.len();
|
||||
// We need to create existing votes
|
||||
for i in polls.iter() {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, old_account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, old_account_vote)?;
|
||||
}
|
||||
let votes = match VotingFor::<T>::get(&caller, &class) {
|
||||
Voting::Casting(Casting { votes, .. }) => votes,
|
||||
@@ -189,14 +189,14 @@ benchmarks! {
|
||||
|
||||
// We need to create existing delegations
|
||||
for i in polls.iter().take(r as usize) {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote)?;
|
||||
}
|
||||
assert_matches!(
|
||||
VotingFor::<T>::get(&voter, &class),
|
||||
Voting::Casting(Casting { votes, .. }) if votes.len() == r as usize
|
||||
);
|
||||
|
||||
}: _(RawOrigin::Signed(caller.clone()), class.clone(), voter.clone(), Conviction::Locked1x, delegated_balance)
|
||||
}: _(RawOrigin::Signed(caller.clone()), class.clone(), voter, Conviction::Locked1x, delegated_balance)
|
||||
verify {
|
||||
assert_matches!(VotingFor::<T>::get(&caller, &class), Voting::Delegating(_));
|
||||
}
|
||||
@@ -224,7 +224,7 @@ benchmarks! {
|
||||
|
||||
// We need to create delegations
|
||||
for i in polls.iter().take(r as usize) {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote)?;
|
||||
}
|
||||
assert_matches!(
|
||||
VotingFor::<T>::get(&voter, &class),
|
||||
@@ -248,7 +248,7 @@ benchmarks! {
|
||||
for (class, polls) in all_polls.iter() {
|
||||
assert!(polls.len() > 0);
|
||||
for i in polls.iter() {
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, normal_account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), *i, normal_account_vote)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ benchmarks! {
|
||||
|
||||
// Vote big on the class with the most ongoing votes of them to bump the lock and make it
|
||||
// hard to recompute when removed.
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), polls[0], big_account_vote.clone())?;
|
||||
ConvictionVoting::<T>::vote(RawOrigin::Signed(caller.clone()).into(), polls[0], big_account_vote)?;
|
||||
let now_usable = <T::Currency as fungible::Inspect<T::AccountId>>::reducible_balance(&caller, false);
|
||||
assert_eq!(orig_usable - now_usable, 100u32.into());
|
||||
|
||||
|
||||
@@ -553,7 +553,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
}),
|
||||
);
|
||||
match old {
|
||||
Voting::Delegating(Delegating { .. }) => Err(Error::<T, I>::AlreadyDelegating)?,
|
||||
Voting::Delegating(Delegating { .. }) =>
|
||||
return Err(Error::<T, I>::AlreadyDelegating.into()),
|
||||
Voting::Casting(Casting { votes, delegations, prior }) => {
|
||||
// here we just ensure that we're currently idling with no votes recorded.
|
||||
ensure!(votes.is_empty(), Error::<T, I>::AlreadyVoting);
|
||||
|
||||
@@ -52,7 +52,7 @@ fn add_proposal<T: Config>(n: u32) -> Result<T::Hash, &'static str> {
|
||||
let value = T::MinimumDeposit::get();
|
||||
let proposal_hash: T::Hash = T::Hashing::hash_of(&n);
|
||||
|
||||
Democracy::<T>::propose(RawOrigin::Signed(other).into(), proposal_hash, value.into())?;
|
||||
Democracy::<T>::propose(RawOrigin::Signed(other).into(), proposal_hash, value)?;
|
||||
|
||||
Ok(proposal_hash)
|
||||
}
|
||||
@@ -98,7 +98,7 @@ benchmarks! {
|
||||
let proposal_hash: T::Hash = T::Hashing::hash_of(&0);
|
||||
let value = T::MinimumDeposit::get();
|
||||
whitelist_account!(caller);
|
||||
}: _(RawOrigin::Signed(caller), proposal_hash, value.into())
|
||||
}: _(RawOrigin::Signed(caller), proposal_hash, value)
|
||||
verify {
|
||||
assert_eq!(Democracy::<T>::public_props().len(), p as usize, "Proposals not created.");
|
||||
}
|
||||
@@ -133,7 +133,7 @@ benchmarks! {
|
||||
// We need to create existing direct votes
|
||||
for i in 0 .. r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?;
|
||||
}
|
||||
let votes = match VotingOf::<T>::get(&caller) {
|
||||
Voting::Direct { votes, .. } => votes,
|
||||
@@ -161,7 +161,7 @@ benchmarks! {
|
||||
// We need to create existing direct votes
|
||||
for i in 0 ..=r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?;
|
||||
}
|
||||
let votes = match VotingOf::<T>::get(&caller) {
|
||||
Voting::Direct { votes, .. } => votes,
|
||||
@@ -217,7 +217,7 @@ benchmarks! {
|
||||
// Place our proposal in the external queue, too.
|
||||
let hash = T::Hashing::hash_of(&0);
|
||||
assert_ok!(
|
||||
Democracy::<T>::external_propose(T::ExternalOrigin::successful_origin(), hash.clone())
|
||||
Democracy::<T>::external_propose(T::ExternalOrigin::successful_origin(), hash)
|
||||
);
|
||||
let origin = T::BlacklistOrigin::successful_origin();
|
||||
// Add a referendum of our proposal.
|
||||
@@ -275,13 +275,13 @@ benchmarks! {
|
||||
fast_track {
|
||||
let origin_propose = T::ExternalDefaultOrigin::successful_origin();
|
||||
let proposal_hash: T::Hash = T::Hashing::hash_of(&0);
|
||||
Democracy::<T>::external_propose_default(origin_propose, proposal_hash.clone())?;
|
||||
Democracy::<T>::external_propose_default(origin_propose, proposal_hash)?;
|
||||
|
||||
// NOTE: Instant origin may invoke a little bit more logic, but may not always succeed.
|
||||
let origin_fast_track = T::FastTrackOrigin::successful_origin();
|
||||
let voting_period = T::FastTrackVotingPeriod::get();
|
||||
let delay = 0u32;
|
||||
}: _<T::Origin>(origin_fast_track, proposal_hash, voting_period.into(), delay.into())
|
||||
}: _<T::Origin>(origin_fast_track, proposal_hash, voting_period, delay.into())
|
||||
verify {
|
||||
assert_eq!(Democracy::<T>::referendum_count(), 1, "referendum not created")
|
||||
}
|
||||
@@ -293,7 +293,7 @@ benchmarks! {
|
||||
let proposal_hash: T::Hash = T::Hashing::hash_of(&v);
|
||||
|
||||
let origin_propose = T::ExternalDefaultOrigin::successful_origin();
|
||||
Democracy::<T>::external_propose_default(origin_propose, proposal_hash.clone())?;
|
||||
Democracy::<T>::external_propose_default(origin_propose, proposal_hash)?;
|
||||
|
||||
let mut vetoers: Vec<T::AccountId> = Vec::new();
|
||||
for i in 0 .. v {
|
||||
@@ -499,7 +499,7 @@ benchmarks! {
|
||||
// We need to create existing direct votes for the `new_delegate`
|
||||
for i in 0..r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_idx, account_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_idx, account_vote)?;
|
||||
}
|
||||
let votes = match VotingOf::<T>::get(&new_delegate) {
|
||||
Voting::Direct { votes, .. } => votes,
|
||||
@@ -550,7 +550,7 @@ benchmarks! {
|
||||
Democracy::<T>::vote(
|
||||
RawOrigin::Signed(the_delegate.clone()).into(),
|
||||
ref_idx,
|
||||
account_vote.clone()
|
||||
account_vote
|
||||
)?;
|
||||
}
|
||||
let votes = match VotingOf::<T>::get(&the_delegate) {
|
||||
@@ -619,17 +619,17 @@ benchmarks! {
|
||||
let proposal_hash = T::Hashing::hash(&encoded_proposal[..]);
|
||||
|
||||
let submitter = funded_account::<T>("submitter", b);
|
||||
Democracy::<T>::note_preimage(RawOrigin::Signed(submitter.clone()).into(), encoded_proposal.clone())?;
|
||||
Democracy::<T>::note_preimage(RawOrigin::Signed(submitter).into(), encoded_proposal.clone())?;
|
||||
|
||||
// We need to set this otherwise we get `Early` error.
|
||||
let block_number = T::VotingPeriod::get() + T::EnactmentPeriod::get() + T::BlockNumber::one();
|
||||
System::<T>::set_block_number(block_number.into());
|
||||
System::<T>::set_block_number(block_number);
|
||||
|
||||
assert!(Preimages::<T>::contains_key(proposal_hash));
|
||||
|
||||
let caller = funded_account::<T>("caller", 0);
|
||||
whitelist_account!(caller);
|
||||
}: _(RawOrigin::Signed(caller), proposal_hash.clone(), u32::MAX)
|
||||
}: _(RawOrigin::Signed(caller), proposal_hash, u32::MAX)
|
||||
verify {
|
||||
let proposal_hash = T::Hashing::hash(&encoded_proposal[..]);
|
||||
assert!(!Preimages::<T>::contains_key(proposal_hash));
|
||||
@@ -646,7 +646,7 @@ benchmarks! {
|
||||
// Vote and immediately unvote
|
||||
for i in 0 .. r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote)?;
|
||||
Democracy::<T>::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_idx)?;
|
||||
}
|
||||
|
||||
@@ -669,7 +669,7 @@ benchmarks! {
|
||||
let small_vote = account_vote::<T>(base_balance);
|
||||
for i in 0 .. r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote)?;
|
||||
}
|
||||
|
||||
// Create a big vote so lock increases
|
||||
@@ -711,7 +711,7 @@ benchmarks! {
|
||||
|
||||
for i in 0 .. r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?;
|
||||
}
|
||||
|
||||
let votes = match VotingOf::<T>::get(&caller) {
|
||||
@@ -740,7 +740,7 @@ benchmarks! {
|
||||
|
||||
for i in 0 .. r {
|
||||
let ref_idx = add_referendum::<T>(i)?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?;
|
||||
Democracy::<T>::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?;
|
||||
}
|
||||
|
||||
let votes = match VotingOf::<T>::get(&caller) {
|
||||
|
||||
@@ -670,8 +670,7 @@ pub mod pallet {
|
||||
) -> DispatchResult {
|
||||
let who = ensure_signed(origin)?;
|
||||
|
||||
let seconds =
|
||||
Self::len_of_deposit_of(proposal).ok_or_else(|| Error::<T>::ProposalMissing)?;
|
||||
let seconds = Self::len_of_deposit_of(proposal).ok_or(Error::<T>::ProposalMissing)?;
|
||||
ensure!(seconds <= seconds_upper_bound, Error::<T>::WrongUpperBound);
|
||||
let mut deposit = Self::deposit_of(proposal).ok_or(Error::<T>::ProposalMissing)?;
|
||||
T::Currency::reserve(&who, deposit.1)?;
|
||||
@@ -820,12 +819,10 @@ pub mod pallet {
|
||||
// - `InstantAllowed` is `true` and `origin` is `InstantOrigin`.
|
||||
let maybe_ensure_instant = if voting_period < T::FastTrackVotingPeriod::get() {
|
||||
Some(origin)
|
||||
} else if let Err(origin) = T::FastTrackOrigin::try_origin(origin) {
|
||||
Some(origin)
|
||||
} else {
|
||||
if let Err(origin) = T::FastTrackOrigin::try_origin(origin) {
|
||||
Some(origin)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
None
|
||||
};
|
||||
if let Some(ensure_instant) = maybe_ensure_instant {
|
||||
T::InstantOrigin::ensure_origin(ensure_instant)?;
|
||||
@@ -867,7 +864,7 @@ pub mod pallet {
|
||||
if let Some((e_proposal_hash, _)) = <NextExternal<T>>::get() {
|
||||
ensure!(proposal_hash == e_proposal_hash, Error::<T>::ProposalMissing);
|
||||
} else {
|
||||
Err(Error::<T>::NoProposal)?;
|
||||
return Err(Error::<T>::NoProposal.into())
|
||||
}
|
||||
|
||||
let mut existing_vetoers =
|
||||
@@ -966,7 +963,7 @@ pub mod pallet {
|
||||
/// voted on. Weight is charged as if maximum votes.
|
||||
// NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure
|
||||
// because a valid delegation cover decoding a direct voting with max votes.
|
||||
#[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get()))]
|
||||
pub fn undelegate(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
|
||||
let who = ensure_signed(origin)?;
|
||||
let votes = Self::try_undelegate(who)?;
|
||||
@@ -1634,7 +1631,7 @@ impl<T: Config> Pallet<T> {
|
||||
);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::NoneWaiting)?
|
||||
return Err(Error::<T>::NoneWaiting.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1667,7 +1664,7 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::NoneWaiting)?
|
||||
return Err(Error::<T>::NoneWaiting.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1822,8 +1819,7 @@ impl<T: Config> Pallet<T> {
|
||||
// To decode the enum variant we only need the first byte.
|
||||
let mut buf = [0u8; 1];
|
||||
let key = <Preimages<T>>::hashed_key_for(proposal_hash);
|
||||
let bytes =
|
||||
sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::<T>::NotImminent)?;
|
||||
let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or(Error::<T>::NotImminent)?;
|
||||
// The value may be smaller that 1 byte.
|
||||
let mut input = &buf[0..buf.len().min(bytes as usize)];
|
||||
|
||||
@@ -1851,8 +1847,7 @@ impl<T: Config> Pallet<T> {
|
||||
// * at most 5 bytes to decode a `Compact<u32>`
|
||||
let mut buf = [0u8; 6];
|
||||
let key = <Preimages<T>>::hashed_key_for(proposal_hash);
|
||||
let bytes =
|
||||
sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::<T>::PreimageMissing)?;
|
||||
let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or(Error::<T>::PreimageMissing)?;
|
||||
// The value may be smaller that 6 bytes.
|
||||
let mut input = &buf[0..buf.len().min(bytes as usize)];
|
||||
|
||||
@@ -1931,7 +1926,7 @@ impl<T: Config> Pallet<T> {
|
||||
fn decode_compact_u32_at(key: &[u8]) -> Option<u32> {
|
||||
// `Compact<u32>` takes at most 5 bytes.
|
||||
let mut buf = [0u8; 5];
|
||||
let bytes = sp_io::storage::read(&key, &mut buf, 0)?;
|
||||
let bytes = sp_io::storage::read(key, &mut buf, 0)?;
|
||||
// The value may be smaller than 5 bytes.
|
||||
let mut input = &buf[0..buf.len().min(bytes as usize)];
|
||||
match codec::Compact::<u32>::decode(&mut input) {
|
||||
|
||||
@@ -491,7 +491,7 @@ frame_benchmarking::benchmarks! {
|
||||
|
||||
// sort assignments by decreasing voter stake
|
||||
assignments.sort_by_key(|crate::unsigned::Assignment::<T> { who, .. }| {
|
||||
let stake = cache.get(&who).map(|idx| {
|
||||
let stake = cache.get(who).map(|idx| {
|
||||
let (_, stake, _) = voters[*idx];
|
||||
stake
|
||||
}).unwrap_or_default();
|
||||
|
||||
@@ -264,7 +264,7 @@ mod mock;
|
||||
#[macro_use]
|
||||
pub mod helpers;
|
||||
|
||||
const LOG_TARGET: &'static str = "runtime::election-provider";
|
||||
const LOG_TARGET: &str = "runtime::election-provider";
|
||||
|
||||
pub mod signed;
|
||||
pub mod unsigned;
|
||||
@@ -1446,7 +1446,7 @@ impl<T: Config> Pallet<T> {
|
||||
ensure!(winners.len() as u32 == desired_targets, FeasibilityError::WrongWinnerCount);
|
||||
|
||||
// Ensure that the solution's score can pass absolute min-score.
|
||||
let submitted_score = raw_solution.score.clone();
|
||||
let submitted_score = raw_solution.score;
|
||||
ensure!(
|
||||
Self::minimum_untrusted_score().map_or(true, |min_score| {
|
||||
submitted_score.strict_threshold_better(min_score, Perbill::zero())
|
||||
@@ -1471,29 +1471,26 @@ impl<T: Config> Pallet<T> {
|
||||
.map_err::<FeasibilityError, _>(Into::into)?;
|
||||
|
||||
// Ensure that assignments is correct.
|
||||
let _ = assignments
|
||||
.iter()
|
||||
.map(|ref assignment| {
|
||||
// Check that assignment.who is actually a voter (defensive-only).
|
||||
// NOTE: while using the index map from `voter_index` is better than a blind linear
|
||||
// search, this *still* has room for optimization. Note that we had the index when
|
||||
// we did `solution -> assignment` and we lost it. Ideal is to keep the index
|
||||
// around.
|
||||
let _ = assignments.iter().try_for_each(|assignment| {
|
||||
// Check that assignment.who is actually a voter (defensive-only).
|
||||
// NOTE: while using the index map from `voter_index` is better than a blind linear
|
||||
// search, this *still* has room for optimization. Note that we had the index when
|
||||
// we did `solution -> assignment` and we lost it. Ideal is to keep the index
|
||||
// around.
|
||||
|
||||
// Defensive-only: must exist in the snapshot.
|
||||
let snapshot_index =
|
||||
voter_index(&assignment.who).ok_or(FeasibilityError::InvalidVoter)?;
|
||||
// Defensive-only: index comes from the snapshot, must exist.
|
||||
let (_voter, _stake, targets) =
|
||||
snapshot_voters.get(snapshot_index).ok_or(FeasibilityError::InvalidVoter)?;
|
||||
// Defensive-only: must exist in the snapshot.
|
||||
let snapshot_index =
|
||||
voter_index(&assignment.who).ok_or(FeasibilityError::InvalidVoter)?;
|
||||
// Defensive-only: index comes from the snapshot, must exist.
|
||||
let (_voter, _stake, targets) =
|
||||
snapshot_voters.get(snapshot_index).ok_or(FeasibilityError::InvalidVoter)?;
|
||||
|
||||
// Check that all of the targets are valid based on the snapshot.
|
||||
if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) {
|
||||
return Err(FeasibilityError::InvalidVote)
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.collect::<Result<(), FeasibilityError>>()?;
|
||||
// Check that all of the targets are valid based on the snapshot.
|
||||
if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) {
|
||||
return Err(FeasibilityError::InvalidVote)
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// ----- Start building support. First, we need one more closure.
|
||||
let stake_of = helpers::stake_of_fn::<T>(&snapshot_voters, &cache);
|
||||
|
||||
@@ -99,7 +99,7 @@ impl<T: Config> From<FeasibilityError> for MinerError<T> {
|
||||
/// Save a given call into OCW storage.
|
||||
fn save_solution<T: Config>(call: &Call<T>) -> Result<(), MinerError<T>> {
|
||||
log!(debug, "saving a call to the offchain storage.");
|
||||
let storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL);
|
||||
let storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL);
|
||||
match storage.mutate::<_, (), _>(|_| Ok(call.clone())) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) =>
|
||||
@@ -116,7 +116,7 @@ fn save_solution<T: Config>(call: &Call<T>) -> Result<(), MinerError<T>> {
|
||||
|
||||
/// Get a saved solution from OCW storage if it exists.
|
||||
fn restore_solution<T: Config>() -> Result<Call<T>, MinerError<T>> {
|
||||
StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL)
|
||||
StorageValueRef::persistent(OFFCHAIN_CACHED_CALL)
|
||||
.get()
|
||||
.ok()
|
||||
.flatten()
|
||||
@@ -126,7 +126,7 @@ fn restore_solution<T: Config>() -> Result<Call<T>, MinerError<T>> {
|
||||
/// Clear a saved solution from OCW storage.
|
||||
pub(super) fn kill_ocw_solution<T: Config>() {
|
||||
log!(debug, "clearing offchain call cache storage.");
|
||||
let mut storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL);
|
||||
let mut storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL);
|
||||
storage.clear();
|
||||
}
|
||||
|
||||
@@ -135,14 +135,14 @@ pub(super) fn kill_ocw_solution<T: Config>() {
|
||||
/// After calling this, the next offchain worker is guaranteed to work, with respect to the
|
||||
/// frequency repeat.
|
||||
fn clear_offchain_repeat_frequency() {
|
||||
let mut last_block = StorageValueRef::persistent(&OFFCHAIN_LAST_BLOCK);
|
||||
let mut last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK);
|
||||
last_block.clear();
|
||||
}
|
||||
|
||||
/// `true` when OCW storage contains a solution
|
||||
#[cfg(test)]
|
||||
fn ocw_solution_exists<T: Config>() -> bool {
|
||||
matches!(StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL).get::<Call<T>>(), Ok(Some(_)))
|
||||
matches!(StorageValueRef::persistent(OFFCHAIN_CACHED_CALL).get::<Call<T>>(), Ok(Some(_)))
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
@@ -206,9 +206,8 @@ impl<T: Config> Pallet<T> {
|
||||
// get the solution, with a load of checks to ensure if submitted, IT IS ABSOLUTELY VALID.
|
||||
let (raw_solution, witness) = Self::mine_and_check()?;
|
||||
|
||||
let score = raw_solution.score.clone();
|
||||
let call: Call<T> =
|
||||
Call::submit_unsigned { raw_solution: Box::new(raw_solution), witness }.into();
|
||||
let score = raw_solution.score;
|
||||
let call: Call<T> = Call::submit_unsigned { raw_solution: Box::new(raw_solution), witness };
|
||||
|
||||
log!(
|
||||
debug,
|
||||
@@ -532,7 +531,7 @@ impl<T: Config> Pallet<T> {
|
||||
// we found the right value - early exit the function.
|
||||
Ok(next) => return next,
|
||||
}
|
||||
step = step / 2;
|
||||
step /= 2;
|
||||
current_weight = weight_with(voters);
|
||||
}
|
||||
|
||||
@@ -566,7 +565,7 @@ impl<T: Config> Pallet<T> {
|
||||
/// is returned, `now` is written in storage and will be used in further calls as the baseline.
|
||||
pub fn ensure_offchain_repeat_frequency(now: T::BlockNumber) -> Result<(), MinerError<T>> {
|
||||
let threshold = T::OffchainRepeat::get();
|
||||
let last_block = StorageValueRef::persistent(&OFFCHAIN_LAST_BLOCK);
|
||||
let last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK);
|
||||
|
||||
let mutate_stat = last_block.mutate::<_, &'static str, _>(
|
||||
|maybe_head: Result<Option<T::BlockNumber>, _>| {
|
||||
|
||||
@@ -153,7 +153,7 @@ fn check_attributes(input: ParseStream) -> syn::Result<bool> {
|
||||
if attrs.len() > 1 {
|
||||
let extra_attr = attrs.pop().expect("attributes vec with len > 1 can be popped");
|
||||
return Err(syn::Error::new_spanned(
|
||||
extra_attr.clone(),
|
||||
extra_attr,
|
||||
"compact solution can accept only #[compact]",
|
||||
))
|
||||
}
|
||||
@@ -164,7 +164,7 @@ fn check_attributes(input: ParseStream) -> syn::Result<bool> {
|
||||
if attr.path.is_ident("compact") {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(syn::Error::new_spanned(attr.clone(), "compact solution can accept only #[compact]"))
|
||||
Err(syn::Error::new_spanned(attr, "compact solution can accept only #[compact]"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result<TokenStream2> {
|
||||
} = def;
|
||||
|
||||
if count <= 2 {
|
||||
Err(syn_err("cannot build solution struct with capacity less than 3."))?
|
||||
return Err(syn_err("cannot build solution struct with capacity less than 3."))
|
||||
}
|
||||
|
||||
let single = {
|
||||
|
||||
@@ -244,7 +244,7 @@ impl<VoterIndex, TargetIndex, P: PerThing> IndexAssignment<VoterIndex, TargetInd
|
||||
distribution: assignment
|
||||
.distribution
|
||||
.iter()
|
||||
.map(|(target, proportion)| Some((target_index(target)?, proportion.clone())))
|
||||
.map(|(target, proportion)| Some((target_index(target)?, *proportion)))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.or_invalid_index()?,
|
||||
})
|
||||
|
||||
@@ -93,8 +93,7 @@ fn submit_candidates_with_self_vote<T: Config>(
|
||||
let stake = default_stake::<T>(c);
|
||||
let _ = candidates
|
||||
.iter()
|
||||
.map(|c| submit_voter::<T>(c.clone(), vec![c.clone()], stake).map(|_| ()))
|
||||
.collect::<Result<_, _>>()?;
|
||||
.try_for_each(|c| submit_voter::<T>(c.clone(), vec![c.clone()], stake).map(|_| ()))?;
|
||||
Ok(candidates)
|
||||
}
|
||||
|
||||
|
||||
@@ -503,7 +503,7 @@ pub mod pallet {
|
||||
|
||||
let had_replacement = Self::remove_and_replace_member(&who, true)?;
|
||||
debug_assert_eq!(has_replacement, had_replacement);
|
||||
Self::deposit_event(Event::MemberKicked { member: who.clone() });
|
||||
Self::deposit_event(Event::MemberKicked { member: who });
|
||||
|
||||
if !had_replacement {
|
||||
Self::do_phragmen();
|
||||
@@ -782,7 +782,7 @@ impl<T: Config> Pallet<T> {
|
||||
})?;
|
||||
|
||||
let remaining_member_ids_sorted =
|
||||
Self::members().into_iter().map(|x| x.who.clone()).collect::<Vec<_>>();
|
||||
Self::members().into_iter().map(|x| x.who).collect::<Vec<_>>();
|
||||
let outgoing = &[who.clone()];
|
||||
let maybe_current_prime = T::ChangeMembers::get_prime();
|
||||
let return_value = match maybe_replacement {
|
||||
@@ -861,7 +861,7 @@ impl<T: Config> Pallet<T> {
|
||||
/// Reads Members, RunnersUp, Candidates and Voting(who) from database.
|
||||
fn is_defunct_voter(votes: &[T::AccountId]) -> bool {
|
||||
votes.iter().all(|v| {
|
||||
!Self::is_member(v) && !Self::is_runner_up(v) && !Self::is_candidate(v).is_ok()
|
||||
!Self::is_member(v) && !Self::is_runner_up(v) && Self::is_candidate(v).is_err()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -923,148 +923,156 @@ impl<T: Config> Pallet<T> {
|
||||
let weight_candidates = candidates_and_deposit.len() as u32;
|
||||
let weight_voters = voters_and_votes.len() as u32;
|
||||
let weight_edges = num_edges;
|
||||
let _ = sp_npos_elections::seq_phragmen(
|
||||
num_to_elect,
|
||||
candidate_ids,
|
||||
voters_and_votes.clone(),
|
||||
None,
|
||||
)
|
||||
.map(|ElectionResult::<T::AccountId, Perbill> { winners, assignments: _ }| {
|
||||
// this is already sorted by id.
|
||||
let old_members_ids_sorted =
|
||||
<Members<T>>::take().into_iter().map(|m| m.who).collect::<Vec<T::AccountId>>();
|
||||
// this one needs a sort by id.
|
||||
let mut old_runners_up_ids_sorted =
|
||||
<RunnersUp<T>>::take().into_iter().map(|r| r.who).collect::<Vec<T::AccountId>>();
|
||||
old_runners_up_ids_sorted.sort();
|
||||
let _ =
|
||||
sp_npos_elections::seq_phragmen(num_to_elect, candidate_ids, voters_and_votes, None)
|
||||
.map(|ElectionResult::<T::AccountId, Perbill> { winners, assignments: _ }| {
|
||||
// this is already sorted by id.
|
||||
let old_members_ids_sorted = <Members<T>>::take()
|
||||
.into_iter()
|
||||
.map(|m| m.who)
|
||||
.collect::<Vec<T::AccountId>>();
|
||||
// this one needs a sort by id.
|
||||
let mut old_runners_up_ids_sorted = <RunnersUp<T>>::take()
|
||||
.into_iter()
|
||||
.map(|r| r.who)
|
||||
.collect::<Vec<T::AccountId>>();
|
||||
old_runners_up_ids_sorted.sort();
|
||||
|
||||
// filter out those who end up with no backing stake.
|
||||
let mut new_set_with_stake = winners
|
||||
.into_iter()
|
||||
.filter_map(|(m, b)| if b.is_zero() { None } else { Some((m, to_balance(b))) })
|
||||
.collect::<Vec<(T::AccountId, BalanceOf<T>)>>();
|
||||
// filter out those who end up with no backing stake.
|
||||
let mut new_set_with_stake = winners
|
||||
.into_iter()
|
||||
.filter_map(
|
||||
|(m, b)| if b.is_zero() { None } else { Some((m, to_balance(b))) },
|
||||
)
|
||||
.collect::<Vec<(T::AccountId, BalanceOf<T>)>>();
|
||||
|
||||
// OPTIMIZATION NOTE: we could bail out here if `new_set.len() == 0`. There isn't
|
||||
// much left to do. Yet, re-arranging the code would require duplicating the
|
||||
// slashing of exposed candidates, cleaning any previous members, and so on. For
|
||||
// now, in favor of readability and veracity, we keep it simple.
|
||||
// OPTIMIZATION NOTE: we could bail out here if `new_set.len() == 0`. There
|
||||
// isn't much left to do. Yet, re-arranging the code would require duplicating
|
||||
// the slashing of exposed candidates, cleaning any previous members, and so on.
|
||||
// For now, in favor of readability and veracity, we keep it simple.
|
||||
|
||||
// split new set into winners and runners up.
|
||||
let split_point = desired_seats.min(new_set_with_stake.len());
|
||||
let mut new_members_sorted_by_id =
|
||||
new_set_with_stake.drain(..split_point).collect::<Vec<_>>();
|
||||
new_members_sorted_by_id.sort_by(|i, j| i.0.cmp(&j.0));
|
||||
// split new set into winners and runners up.
|
||||
let split_point = desired_seats.min(new_set_with_stake.len());
|
||||
let mut new_members_sorted_by_id =
|
||||
new_set_with_stake.drain(..split_point).collect::<Vec<_>>();
|
||||
new_members_sorted_by_id.sort_by(|i, j| i.0.cmp(&j.0));
|
||||
|
||||
// all the rest will be runners-up
|
||||
new_set_with_stake.reverse();
|
||||
let new_runners_up_sorted_by_rank = new_set_with_stake;
|
||||
let mut new_runners_up_ids_sorted =
|
||||
new_runners_up_sorted_by_rank.iter().map(|(r, _)| r.clone()).collect::<Vec<_>>();
|
||||
new_runners_up_ids_sorted.sort();
|
||||
// all the rest will be runners-up
|
||||
new_set_with_stake.reverse();
|
||||
let new_runners_up_sorted_by_rank = new_set_with_stake;
|
||||
let mut new_runners_up_ids_sorted = new_runners_up_sorted_by_rank
|
||||
.iter()
|
||||
.map(|(r, _)| r.clone())
|
||||
.collect::<Vec<_>>();
|
||||
new_runners_up_ids_sorted.sort();
|
||||
|
||||
// Now we select a prime member using a [Borda
|
||||
// count](https://en.wikipedia.org/wiki/Borda_count). We weigh everyone's vote for
|
||||
// that new member by a multiplier based on the order of the votes. i.e. the first
|
||||
// person a voter votes for gets a 16x multiplier, the next person gets a 15x
|
||||
// multiplier, an so on... (assuming `MAXIMUM_VOTE` = 16)
|
||||
let mut prime_votes = new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|c| (&c.0, BalanceOf::<T>::zero()))
|
||||
.collect::<Vec<_>>();
|
||||
for (_, stake, votes) in voters_and_stakes.into_iter() {
|
||||
for (vote_multiplier, who) in votes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(vote_position, who)| ((MAXIMUM_VOTE - vote_position) as u32, who))
|
||||
{
|
||||
if let Ok(i) = prime_votes.binary_search_by_key(&who, |k| k.0) {
|
||||
prime_votes[i].1 = prime_votes[i]
|
||||
.1
|
||||
.saturating_add(stake.saturating_mul(vote_multiplier.into()));
|
||||
// Now we select a prime member using a [Borda
|
||||
// count](https://en.wikipedia.org/wiki/Borda_count). We weigh everyone's vote for
|
||||
// that new member by a multiplier based on the order of the votes. i.e. the
|
||||
// first person a voter votes for gets a 16x multiplier, the next person gets a
|
||||
// 15x multiplier, an so on... (assuming `MAXIMUM_VOTE` = 16)
|
||||
let mut prime_votes = new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|c| (&c.0, BalanceOf::<T>::zero()))
|
||||
.collect::<Vec<_>>();
|
||||
for (_, stake, votes) in voters_and_stakes.into_iter() {
|
||||
for (vote_multiplier, who) in
|
||||
votes.iter().enumerate().map(|(vote_position, who)| {
|
||||
((MAXIMUM_VOTE - vote_position) as u32, who)
|
||||
}) {
|
||||
if let Ok(i) = prime_votes.binary_search_by_key(&who, |k| k.0) {
|
||||
prime_votes[i].1 = prime_votes[i]
|
||||
.1
|
||||
.saturating_add(stake.saturating_mul(vote_multiplier.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// We then select the new member with the highest weighted stake. In the case of a tie,
|
||||
// the last person in the list with the tied score is selected. This is the person with
|
||||
// the "highest" account id based on the sort above.
|
||||
let prime = prime_votes.into_iter().max_by_key(|x| x.1).map(|x| x.0.clone());
|
||||
// We then select the new member with the highest weighted stake. In the case of
|
||||
// a tie, the last person in the list with the tied score is selected. This is
|
||||
// the person with the "highest" account id based on the sort above.
|
||||
let prime = prime_votes.into_iter().max_by_key(|x| x.1).map(|x| x.0.clone());
|
||||
|
||||
// new_members_sorted_by_id is sorted by account id.
|
||||
let new_members_ids_sorted = new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|(m, _)| m.clone())
|
||||
.collect::<Vec<T::AccountId>>();
|
||||
// new_members_sorted_by_id is sorted by account id.
|
||||
let new_members_ids_sorted = new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|(m, _)| m.clone())
|
||||
.collect::<Vec<T::AccountId>>();
|
||||
|
||||
// report member changes. We compute diff because we need the outgoing list.
|
||||
let (incoming, outgoing) = T::ChangeMembers::compute_members_diff_sorted(
|
||||
&new_members_ids_sorted,
|
||||
&old_members_ids_sorted,
|
||||
);
|
||||
T::ChangeMembers::change_members_sorted(&incoming, &outgoing, &new_members_ids_sorted);
|
||||
T::ChangeMembers::set_prime(prime);
|
||||
// report member changes. We compute diff because we need the outgoing list.
|
||||
let (incoming, outgoing) = T::ChangeMembers::compute_members_diff_sorted(
|
||||
&new_members_ids_sorted,
|
||||
&old_members_ids_sorted,
|
||||
);
|
||||
T::ChangeMembers::change_members_sorted(
|
||||
&incoming,
|
||||
&outgoing,
|
||||
&new_members_ids_sorted,
|
||||
);
|
||||
T::ChangeMembers::set_prime(prime);
|
||||
|
||||
// All candidates/members/runners-up who are no longer retaining a position as a
|
||||
// seat holder will lose their bond.
|
||||
candidates_and_deposit.iter().for_each(|(c, d)| {
|
||||
if new_members_ids_sorted.binary_search(c).is_err() &&
|
||||
new_runners_up_ids_sorted.binary_search(c).is_err()
|
||||
{
|
||||
let (imbalance, _) = T::Currency::slash_reserved(c, *d);
|
||||
T::LoserCandidate::on_unbalanced(imbalance);
|
||||
Self::deposit_event(Event::CandidateSlashed {
|
||||
candidate: c.clone(),
|
||||
amount: *d,
|
||||
// All candidates/members/runners-up who are no longer retaining a position as a
|
||||
// seat holder will lose their bond.
|
||||
candidates_and_deposit.iter().for_each(|(c, d)| {
|
||||
if new_members_ids_sorted.binary_search(c).is_err() &&
|
||||
new_runners_up_ids_sorted.binary_search(c).is_err()
|
||||
{
|
||||
let (imbalance, _) = T::Currency::slash_reserved(c, *d);
|
||||
T::LoserCandidate::on_unbalanced(imbalance);
|
||||
Self::deposit_event(Event::CandidateSlashed {
|
||||
candidate: c.clone(),
|
||||
amount: *d,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// write final values to storage.
|
||||
let deposit_of_candidate = |x: &T::AccountId| -> BalanceOf<T> {
|
||||
// defensive-only. This closure is used against the new members and new runners-up,
|
||||
// both of which are phragmen winners and thus must have deposit.
|
||||
candidates_and_deposit
|
||||
.iter()
|
||||
.find_map(|(c, d)| if c == x { Some(*d) } else { None })
|
||||
.defensive_unwrap_or_default()
|
||||
};
|
||||
// fetch deposits from the one recorded one. This will make sure that a candidate who
|
||||
// submitted candidacy before a change to candidacy deposit will have the correct amount
|
||||
// recorded.
|
||||
<Members<T>>::put(
|
||||
new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|(who, stake)| SeatHolder {
|
||||
deposit: deposit_of_candidate(&who),
|
||||
who: who.clone(),
|
||||
stake: stake.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
<RunnersUp<T>>::put(
|
||||
new_runners_up_sorted_by_rank
|
||||
.into_iter()
|
||||
.map(|(who, stake)| SeatHolder {
|
||||
deposit: deposit_of_candidate(&who),
|
||||
who,
|
||||
stake,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
// write final values to storage.
|
||||
let deposit_of_candidate = |x: &T::AccountId| -> BalanceOf<T> {
|
||||
// defensive-only. This closure is used against the new members and new
|
||||
// runners-up, both of which are phragmen winners and thus must have
|
||||
// deposit.
|
||||
candidates_and_deposit
|
||||
.iter()
|
||||
.find_map(|(c, d)| if c == x { Some(*d) } else { None })
|
||||
.defensive_unwrap_or_default()
|
||||
};
|
||||
// fetch deposits from the one recorded one. This will make sure that a
|
||||
// candidate who submitted candidacy before a change to candidacy deposit will
|
||||
// have the correct amount recorded.
|
||||
<Members<T>>::put(
|
||||
new_members_sorted_by_id
|
||||
.iter()
|
||||
.map(|(who, stake)| SeatHolder {
|
||||
deposit: deposit_of_candidate(who),
|
||||
who: who.clone(),
|
||||
stake: *stake,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
<RunnersUp<T>>::put(
|
||||
new_runners_up_sorted_by_rank
|
||||
.into_iter()
|
||||
.map(|(who, stake)| SeatHolder {
|
||||
deposit: deposit_of_candidate(&who),
|
||||
who,
|
||||
stake,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
// clean candidates.
|
||||
<Candidates<T>>::kill();
|
||||
// clean candidates.
|
||||
<Candidates<T>>::kill();
|
||||
|
||||
Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id });
|
||||
<ElectionRounds<T>>::mutate(|v| *v += 1);
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::error!(
|
||||
target: "runtime::elections-phragmen",
|
||||
"Failed to run election [{:?}].",
|
||||
e,
|
||||
);
|
||||
Self::deposit_event(Event::ElectionError);
|
||||
});
|
||||
Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id });
|
||||
<ElectionRounds<T>>::mutate(|v| *v += 1);
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::error!(
|
||||
target: "runtime::elections-phragmen",
|
||||
"Failed to run election [{:?}].",
|
||||
e,
|
||||
);
|
||||
Self::deposit_event(Event::ElectionError);
|
||||
});
|
||||
|
||||
T::WeightInfo::election_phragmen(weight_candidates, weight_voters, weight_edges)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn migrate<T: Config>(to_migrate: Vec<T::AccountId>) -> Weight {
|
||||
|
||||
for who in to_migrate.iter() {
|
||||
if let Ok(mut voter) = Voting::<T>::try_get(who) {
|
||||
let free_balance = T::Currency::free_balance(&who);
|
||||
let free_balance = T::Currency::free_balance(who);
|
||||
|
||||
weight = weight.saturating_add(T::DbWeight::get().reads(2));
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn migrate<T: Config>(to_migrate: Vec<T::AccountId>) -> Weight {
|
||||
Voting::<T>::insert(&who, voter);
|
||||
|
||||
let pallet_id = T::PalletId::get();
|
||||
T::Currency::set_lock(pallet_id, &who, free_balance, WithdrawReasons::all());
|
||||
T::Currency::set_lock(pallet_id, who, free_balance, WithdrawReasons::all());
|
||||
|
||||
weight = weight.saturating_add(T::DbWeight::get().writes(2));
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub fn pre_migrate_fn<T: Config>(to_migrate: Vec<T::AccountId>) -> Box<dyn Fn()
|
||||
Box::new(move || {
|
||||
for who in to_migrate.iter() {
|
||||
if let Ok(voter) = Voting::<T>::try_get(who) {
|
||||
let free_balance = T::Currency::free_balance(&who);
|
||||
let free_balance = T::Currency::free_balance(who);
|
||||
|
||||
if voter.stake > free_balance {
|
||||
// all good
|
||||
|
||||
@@ -63,7 +63,7 @@ benchmarks! {
|
||||
}
|
||||
}: {
|
||||
// The benchmark execution phase could also be a closure with custom code
|
||||
m.sort();
|
||||
m.sort_unstable();
|
||||
}
|
||||
|
||||
// This line generates test cases for benchmarking, and could be run by:
|
||||
|
||||
@@ -758,8 +758,8 @@ where
|
||||
Some(Call::set_dummy { .. }) => {
|
||||
sp_runtime::print("set_dummy was received.");
|
||||
|
||||
let mut valid_tx = ValidTransaction::default();
|
||||
valid_tx.priority = Bounded::max_value();
|
||||
let valid_tx =
|
||||
ValidTransaction { priority: Bounded::max_value(), ..Default::default() };
|
||||
Ok(valid_tx)
|
||||
},
|
||||
_ => Ok(Default::default()),
|
||||
|
||||
@@ -446,7 +446,7 @@ impl<T: Config> Pallet<T> {
|
||||
if !signer.can_sign() {
|
||||
return Err(
|
||||
"No local accounts available. Consider adding one via `author_insertKey` RPC.",
|
||||
)?
|
||||
)
|
||||
}
|
||||
// Make an external HTTP request to fetch the current price.
|
||||
// Note this call will block until response is received.
|
||||
@@ -640,7 +640,7 @@ impl<T: Config> Pallet<T> {
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let exp = price.fraction_length.checked_sub(2).unwrap_or(0);
|
||||
let exp = price.fraction_length.saturating_sub(2);
|
||||
Some(price.integer as u32 * 100 + (price.fraction / 10_u64.pow(exp)) as u32)
|
||||
}
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ where
|
||||
let new_header = <frame_system::Pallet<System>>::finalize();
|
||||
let items_zip = header.digest().logs().iter().zip(new_header.digest().logs().iter());
|
||||
for (header_item, computed_item) in items_zip {
|
||||
header_item.check_equal(&computed_item);
|
||||
header_item.check_equal(computed_item);
|
||||
assert!(header_item == computed_item, "Digest item must match that calculated.");
|
||||
}
|
||||
|
||||
@@ -275,7 +275,7 @@ where
|
||||
pub fn initialize_block(header: &System::Header) {
|
||||
sp_io::init_tracing();
|
||||
sp_tracing::enter_span!(sp_tracing::Level::TRACE, "init_block");
|
||||
let digests = Self::extract_pre_digest(&header);
|
||||
let digests = Self::extract_pre_digest(header);
|
||||
Self::initialize_block_impl(header.number(), header.parent_hash(), &digests);
|
||||
}
|
||||
|
||||
@@ -338,7 +338,7 @@ where
|
||||
let header = block.header();
|
||||
|
||||
// Check that `parent_hash` is correct.
|
||||
let n = header.number().clone();
|
||||
let n = *header.number();
|
||||
assert!(
|
||||
n > System::BlockNumber::zero() &&
|
||||
<frame_system::Pallet<System>>::block_hash(n - System::BlockNumber::one()) ==
|
||||
@@ -478,13 +478,13 @@ where
|
||||
);
|
||||
let items_zip = header.digest().logs().iter().zip(new_header.digest().logs().iter());
|
||||
for (header_item, computed_item) in items_zip {
|
||||
header_item.check_equal(&computed_item);
|
||||
header_item.check_equal(computed_item);
|
||||
assert!(header_item == computed_item, "Digest item must match that calculated.");
|
||||
}
|
||||
|
||||
// check storage root.
|
||||
let storage_root = new_header.state_root();
|
||||
header.state_root().check_equal(&storage_root);
|
||||
header.state_root().check_equal(storage_root);
|
||||
assert!(header.state_root() == storage_root, "Storage root must match that calculated.");
|
||||
|
||||
assert!(
|
||||
|
||||
@@ -399,7 +399,7 @@ pub mod pallet {
|
||||
qs[queue_index].0 += net.0;
|
||||
qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1);
|
||||
});
|
||||
Self::deposit_event(Event::BidPlaced { who: who.clone(), amount, duration });
|
||||
Self::deposit_event(Event::BidPlaced { who, amount, duration });
|
||||
|
||||
Ok(().into())
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
use frame_support::pallet_prelude::*;
|
||||
use frame_support::{dispatch::DispatchResult, pallet_prelude::*};
|
||||
use frame_system::pallet_prelude::*;
|
||||
|
||||
#[pallet::pallet]
|
||||
@@ -244,10 +244,11 @@ pub mod pallet {
|
||||
origin: OriginFor<T>,
|
||||
delay: T::BlockNumber,
|
||||
best_finalized_block_number: T::BlockNumber,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
) -> DispatchResult {
|
||||
ensure_root(origin)?;
|
||||
|
||||
Ok(Self::on_stalled(delay, best_finalized_block_number).into())
|
||||
Self::on_stalled(delay, best_finalized_block_number);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,7 +424,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::PauseFailed)?
|
||||
Err(Error::<T>::PauseFailed.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +436,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::ResumeFailed)?
|
||||
Err(Error::<T>::ResumeFailed.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -461,9 +462,9 @@ impl<T: Config> Pallet<T> {
|
||||
if !<PendingChange<T>>::exists() {
|
||||
let scheduled_at = <frame_system::Pallet<T>>::block_number();
|
||||
|
||||
if let Some(_) = forced {
|
||||
if forced.is_some() {
|
||||
if Self::next_forced().map_or(false, |next| next > scheduled_at) {
|
||||
Err(Error::<T>::TooSoon)?
|
||||
return Err(Error::<T>::TooSoon.into())
|
||||
}
|
||||
|
||||
// only allow the next forced change when twice the window has passed since
|
||||
@@ -488,7 +489,7 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::ChangePending)?
|
||||
Err(Error::<T>::ChangePending.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,14 +545,14 @@ impl<T: Config> Pallet<T> {
|
||||
let previous_set_id_session_index = if set_id == 0 {
|
||||
None
|
||||
} else {
|
||||
let session_index = Self::session_for_set(set_id - 1)
|
||||
.ok_or_else(|| Error::<T>::InvalidEquivocationProof)?;
|
||||
let session_index =
|
||||
Self::session_for_set(set_id - 1).ok_or(Error::<T>::InvalidEquivocationProof)?;
|
||||
|
||||
Some(session_index)
|
||||
};
|
||||
|
||||
let set_id_session_index =
|
||||
Self::session_for_set(set_id).ok_or_else(|| Error::<T>::InvalidEquivocationProof)?;
|
||||
Self::session_for_set(set_id).ok_or(Error::<T>::InvalidEquivocationProof)?;
|
||||
|
||||
// check that the session id for the membership proof is within the
|
||||
// bounds of the set id reported in the equivocation.
|
||||
|
||||
@@ -39,11 +39,7 @@ fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {
|
||||
let registrar: T::AccountId = account("registrar", i, SEED);
|
||||
let _ = T::Currency::make_free_balance_be(®istrar, BalanceOf::<T>::max_value());
|
||||
Identity::<T>::add_registrar(RawOrigin::Root.into(), registrar.clone())?;
|
||||
Identity::<T>::set_fee(
|
||||
RawOrigin::Signed(registrar.clone()).into(),
|
||||
i.into(),
|
||||
10u32.into(),
|
||||
)?;
|
||||
Identity::<T>::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?;
|
||||
let fields =
|
||||
IdentityFields(
|
||||
IdentityField::Display |
|
||||
@@ -52,7 +48,7 @@ fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {
|
||||
IdentityField::PgpFingerprint |
|
||||
IdentityField::Image | IdentityField::Twitter,
|
||||
);
|
||||
Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i.into(), fields)?;
|
||||
Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?;
|
||||
}
|
||||
|
||||
assert_eq!(Registrars::<T>::get().len(), r as usize);
|
||||
@@ -75,9 +71,9 @@ fn create_sub_accounts<T: Config>(
|
||||
}
|
||||
|
||||
// Set identity so `set_subs` does not fail.
|
||||
let _ = T::Currency::make_free_balance_be(&who, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
let _ = T::Currency::make_free_balance_be(who, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
let info = create_identity_info::<T>(1);
|
||||
Identity::<T>::set_identity(who_origin.clone().into(), Box::new(info))?;
|
||||
Identity::<T>::set_identity(who_origin.into(), Box::new(info))?;
|
||||
|
||||
Ok(subs)
|
||||
}
|
||||
@@ -101,7 +97,7 @@ fn add_sub_accounts<T: Config>(
|
||||
fn create_identity_info<T: Config>(num_fields: u32) -> IdentityInfo<T::MaxAdditionalFields> {
|
||||
let data = Data::Raw(vec![0; 32].try_into().unwrap());
|
||||
|
||||
let info = IdentityInfo {
|
||||
IdentityInfo {
|
||||
additional: vec![(data.clone(), data.clone()); num_fields as usize].try_into().unwrap(),
|
||||
display: data.clone(),
|
||||
legal: data.clone(),
|
||||
@@ -110,10 +106,8 @@ fn create_identity_info<T: Config>(num_fields: u32) -> IdentityInfo<T::MaxAdditi
|
||||
email: data.clone(),
|
||||
pgp_fingerprint: Some([0; 20]),
|
||||
image: data.clone(),
|
||||
twitter: data.clone(),
|
||||
};
|
||||
|
||||
return info
|
||||
twitter: data,
|
||||
}
|
||||
}
|
||||
|
||||
benchmarks! {
|
||||
@@ -282,7 +276,7 @@ benchmarks! {
|
||||
|
||||
Identity::<T>::add_registrar(RawOrigin::Root.into(), caller.clone())?;
|
||||
let registrars = Registrars::<T>::get();
|
||||
ensure!(registrars[r as usize].as_ref().unwrap().account == caller.clone(), "id not set.");
|
||||
ensure!(registrars[r as usize].as_ref().unwrap().account == caller, "id not set.");
|
||||
}: _(RawOrigin::Signed(caller), r, account("new", 0, SEED))
|
||||
verify {
|
||||
let registrars = Registrars::<T>::get();
|
||||
@@ -325,7 +319,7 @@ benchmarks! {
|
||||
};
|
||||
|
||||
Identity::<T>::add_registrar(RawOrigin::Root.into(), caller.clone())?;
|
||||
Identity::<T>::request_judgement(user_origin.clone(), r, 10u32.into())?;
|
||||
Identity::<T>::request_judgement(user_origin, r, 10u32.into())?;
|
||||
}: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable)
|
||||
verify {
|
||||
assert_last_event::<T>(Event::<T>::JudgementGiven { target: user, registrar_index: r }.into())
|
||||
|
||||
@@ -324,8 +324,8 @@ pub mod pallet {
|
||||
/// - One event.
|
||||
/// # </weight>
|
||||
#[pallet::weight( T::WeightInfo::set_identity(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn set_identity(
|
||||
origin: OriginFor<T>,
|
||||
@@ -416,7 +416,7 @@ pub mod pallet {
|
||||
let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);
|
||||
|
||||
let not_other_sub =
|
||||
subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| &i.0 == &sender);
|
||||
subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| i.0 == sender);
|
||||
ensure!(not_other_sub, Error::<T>::AlreadyClaimed);
|
||||
|
||||
if old_deposit < new_deposit {
|
||||
@@ -470,9 +470,9 @@ pub mod pallet {
|
||||
/// - One event.
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::clear_identity(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxSubAccounts::get().into(), // S
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxSubAccounts::get(), // S
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
|
||||
let sender = ensure_signed(origin)?;
|
||||
@@ -484,7 +484,7 @@ pub mod pallet {
|
||||
<SuperOf<T>>::remove(sub);
|
||||
}
|
||||
|
||||
let err_amount = T::Currency::unreserve(&sender, deposit.clone());
|
||||
let err_amount = T::Currency::unreserve(&sender, deposit);
|
||||
debug_assert!(err_amount.is_zero());
|
||||
|
||||
Self::deposit_event(Event::IdentityCleared { who: sender, deposit });
|
||||
@@ -521,8 +521,8 @@ pub mod pallet {
|
||||
/// - One event.
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::request_judgement(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn request_judgement(
|
||||
origin: OriginFor<T>,
|
||||
@@ -542,7 +542,7 @@ pub mod pallet {
|
||||
match id.judgements.binary_search_by_key(®_index, |x| x.0) {
|
||||
Ok(i) =>
|
||||
if id.judgements[i].1.is_sticky() {
|
||||
Err(Error::<T>::StickyJudgement)?
|
||||
return Err(Error::<T>::StickyJudgement.into())
|
||||
} else {
|
||||
id.judgements[i] = item
|
||||
},
|
||||
@@ -583,8 +583,8 @@ pub mod pallet {
|
||||
/// - One event
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::cancel_request(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn cancel_request(
|
||||
origin: OriginFor<T>,
|
||||
@@ -600,7 +600,7 @@ pub mod pallet {
|
||||
let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {
|
||||
fee
|
||||
} else {
|
||||
Err(Error::<T>::JudgementGiven)?
|
||||
return Err(Error::<T>::JudgementGiven.into())
|
||||
};
|
||||
|
||||
let err_amount = T::Currency::unreserve(&sender, fee);
|
||||
@@ -754,8 +754,8 @@ pub mod pallet {
|
||||
/// - One event.
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::provide_judgement(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn provide_judgement(
|
||||
origin: OriginFor<T>,
|
||||
@@ -821,9 +821,9 @@ pub mod pallet {
|
||||
/// - One event.
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::kill_identity(
|
||||
T::MaxRegistrars::get().into(), // R
|
||||
T::MaxSubAccounts::get().into(), // S
|
||||
T::MaxAdditionalFields::get().into(), // X
|
||||
T::MaxRegistrars::get(), // R
|
||||
T::MaxSubAccounts::get(), // S
|
||||
T::MaxAdditionalFields::get(), // X
|
||||
))]
|
||||
pub fn kill_identity(
|
||||
origin: OriginFor<T>,
|
||||
|
||||
@@ -217,20 +217,14 @@ impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + Part
|
||||
/// Returns `true` if this judgement is indicative of a deposit being currently held. This means
|
||||
/// it should not be cleared or replaced except by an operation which utilizes the deposit.
|
||||
pub(crate) fn has_deposit(&self) -> bool {
|
||||
match self {
|
||||
Judgement::FeePaid(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
matches!(self, Judgement::FeePaid(_))
|
||||
}
|
||||
|
||||
/// Returns `true` if this judgement is one that should not be generally be replaced outside
|
||||
/// of specialized handlers. Examples include "malicious" judgements and deposit-holding
|
||||
/// judgements.
|
||||
pub(crate) fn is_sticky(&self) -> bool {
|
||||
match self {
|
||||
Judgement::FeePaid(_) | Judgement::Erroneous => true,
|
||||
_ => false,
|
||||
}
|
||||
matches!(self, Judgement::FeePaid(_) | Judgement::Erroneous)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -508,9 +508,9 @@ pub mod pallet {
|
||||
|
||||
Ok(())
|
||||
} else if exists {
|
||||
Err(Error::<T>::DuplicatedHeartbeat)?
|
||||
Err(Error::<T>::DuplicatedHeartbeat.into())
|
||||
} else {
|
||||
Err(Error::<T>::InvalidKey)?
|
||||
Err(Error::<T>::InvalidKey.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -573,7 +573,7 @@ pub mod pallet {
|
||||
|
||||
// check signature (this is expensive so we do it last).
|
||||
let signature_valid = heartbeat.using_encoded(|encoded_heartbeat| {
|
||||
authority_id.verify(&encoded_heartbeat, &signature)
|
||||
authority_id.verify(&encoded_heartbeat, signature)
|
||||
});
|
||||
|
||||
if !signature_valid {
|
||||
|
||||
@@ -142,7 +142,7 @@ pub mod pallet {
|
||||
Accounts::<T>::try_mutate(index, |maybe_value| -> DispatchResult {
|
||||
let (account, amount, perm) = maybe_value.take().ok_or(Error::<T>::NotAssigned)?;
|
||||
ensure!(!perm, Error::<T>::Permanent);
|
||||
ensure!(&account == &who, Error::<T>::NotOwner);
|
||||
ensure!(account == who, Error::<T>::NotOwner);
|
||||
let lost = T::Currency::repatriate_reserved(&who, &new, amount, Reserved)?;
|
||||
*maybe_value = Some((new.clone(), amount.saturating_sub(lost), false));
|
||||
Ok(())
|
||||
@@ -176,7 +176,7 @@ pub mod pallet {
|
||||
Accounts::<T>::try_mutate(index, |maybe_value| -> DispatchResult {
|
||||
let (account, amount, perm) = maybe_value.take().ok_or(Error::<T>::NotAssigned)?;
|
||||
ensure!(!perm, Error::<T>::Permanent);
|
||||
ensure!(&account == &who, Error::<T>::NotOwner);
|
||||
ensure!(account == who, Error::<T>::NotOwner);
|
||||
T::Currency::unreserve(&who, amount);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -249,7 +249,7 @@ pub mod pallet {
|
||||
Accounts::<T>::try_mutate(index, |maybe_value| -> DispatchResult {
|
||||
let (account, amount, perm) = maybe_value.take().ok_or(Error::<T>::NotAssigned)?;
|
||||
ensure!(!perm, Error::<T>::Permanent);
|
||||
ensure!(&account == &who, Error::<T>::NotOwner);
|
||||
ensure!(account == who, Error::<T>::NotOwner);
|
||||
T::Currency::slash_reserved(&who, amount);
|
||||
*maybe_value = Some((account, Zero::zero(), true));
|
||||
Ok(())
|
||||
|
||||
@@ -108,7 +108,7 @@ impl<T: Config> ValidateCall<T> for () {
|
||||
impl<T: Config> ValidateCall<T> for Pallet<T> {
|
||||
fn validate_call(call: &<T as Config>::Call) -> bool {
|
||||
let valid_calls = CallIndices::<T>::get();
|
||||
let call_index = match Self::call_to_index(&call) {
|
||||
let call_index = match Self::call_to_index(call) {
|
||||
Ok(call_index) => call_index,
|
||||
Err(_) => return false,
|
||||
};
|
||||
@@ -278,7 +278,7 @@ pub mod pallet {
|
||||
// but is not used if it is not relevant.
|
||||
}
|
||||
}
|
||||
return T::DbWeight::get().reads(1)
|
||||
T::DbWeight::get().reads(1)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -418,9 +418,9 @@ impl<T: Config> Pallet<T> {
|
||||
fn call_to_index(call: &<T as Config>::Call) -> Result<CallIndex, DispatchError> {
|
||||
let encoded_call = call.encode();
|
||||
if encoded_call.len() < 2 {
|
||||
Err(Error::<T>::EncodingFailed)?
|
||||
return Err(Error::<T>::EncodingFailed.into())
|
||||
}
|
||||
return Ok((encoded_call[0], encoded_call[1]))
|
||||
Ok((encoded_call[0], encoded_call[1]))
|
||||
}
|
||||
|
||||
/// Logic for buying a ticket.
|
||||
|
||||
@@ -377,7 +377,7 @@ mod benchmark {
|
||||
let m in 1 .. T::MaxMembers::get();
|
||||
|
||||
let members = (0..m).map(|i| account("member", i, SEED)).collect::<Vec<T::AccountId>>();
|
||||
set_members::<T, I>(members.clone(), None);
|
||||
set_members::<T, I>(members, None);
|
||||
let new_member = account::<T::AccountId>("add", m, SEED);
|
||||
}: {
|
||||
assert_ok!(<Membership<T, I>>::add_member(T::AddOrigin::successful_origin(), new_member.clone()));
|
||||
|
||||
@@ -45,7 +45,7 @@ fn setup_multi<T: Config>(
|
||||
let call: <T as Config>::Call =
|
||||
frame_system::Call::<T>::remark { remark: vec![0; z as usize] }.into();
|
||||
let call_data = OpaqueCall::<T>::from_encoded(call.encode());
|
||||
return Ok((signatories, call_data))
|
||||
Ok((signatories, call_data))
|
||||
}
|
||||
|
||||
benchmarks! {
|
||||
@@ -74,7 +74,7 @@ benchmarks! {
|
||||
// Transaction Length
|
||||
let z in 0 .. 10_000;
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
// Whitelist caller account from further DB operations.
|
||||
@@ -92,7 +92,7 @@ benchmarks! {
|
||||
// Transaction Length
|
||||
let z in 0 .. 10_000;
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
|
||||
@@ -111,7 +111,7 @@ benchmarks! {
|
||||
// Transaction Length
|
||||
let z in 0 .. 10_000;
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let mut signatories2 = signatories.clone();
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
@@ -136,7 +136,7 @@ benchmarks! {
|
||||
// Transaction Length
|
||||
let z in 0 .. 10_000;
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let mut signatories2 = signatories.clone();
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
@@ -162,7 +162,7 @@ benchmarks! {
|
||||
// Transaction Length
|
||||
let z in 0 .. 10_000;
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let mut signatories2 = signatories.clone();
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
@@ -195,7 +195,7 @@ benchmarks! {
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
// Whitelist caller account from further DB operations.
|
||||
let caller_key = frame_system::Account::<T>::hashed_key_for(&caller);
|
||||
frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into());
|
||||
@@ -214,16 +214,16 @@ benchmarks! {
|
||||
let mut signatories2 = signatories.clone();
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
// before the call, get the timepoint
|
||||
let timepoint = Multisig::<T>::timepoint();
|
||||
// Create the multi
|
||||
Multisig::<T>::as_multi(
|
||||
RawOrigin::Signed(caller.clone()).into(),
|
||||
RawOrigin::Signed(caller).into(),
|
||||
s as u16,
|
||||
signatories,
|
||||
None,
|
||||
call.clone(),
|
||||
call,
|
||||
false,
|
||||
0
|
||||
)?;
|
||||
@@ -247,7 +247,7 @@ benchmarks! {
|
||||
let mut signatories2 = signatories.clone();
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
// before the call, get the timepoint
|
||||
let timepoint = Multisig::<T>::timepoint();
|
||||
// Create the multi
|
||||
@@ -284,11 +284,11 @@ benchmarks! {
|
||||
let (mut signatories, call) = setup_multi::<T>(s, z)?;
|
||||
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, s.try_into().unwrap());
|
||||
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
|
||||
let call_hash = blake2_256(&call.encoded());
|
||||
let call_hash = blake2_256(call.encoded());
|
||||
let timepoint = Multisig::<T>::timepoint();
|
||||
// Create the multi
|
||||
let o = RawOrigin::Signed(caller.clone()).into();
|
||||
Multisig::<T>::as_multi(o, s as u16, signatories.clone(), None, call.clone(), true, 0)?;
|
||||
Multisig::<T>::as_multi(o, s as u16, signatories.clone(), None, call, true, 0)?;
|
||||
assert!(Multisigs::<T>::contains_key(&multi_account_id, call_hash));
|
||||
assert!(Calls::<T>::contains_key(call_hash));
|
||||
// Whitelist caller account from further DB operations.
|
||||
|
||||
@@ -295,8 +295,7 @@ pub mod pallet {
|
||||
let weight_used = T::WeightInfo::as_multi_threshold_1(call_len as u32)
|
||||
.saturating_add(actual_weight);
|
||||
let post_info = Some(weight_used).into();
|
||||
let error = err.error.into();
|
||||
DispatchErrorWithPostInfo { post_info, error }
|
||||
DispatchErrorWithPostInfo { post_info, error: err.error }
|
||||
},
|
||||
None => err,
|
||||
})
|
||||
|
||||
@@ -147,7 +147,7 @@ pub mod pallet {
|
||||
deposit
|
||||
} else {
|
||||
let deposit = T::ReservationFee::get();
|
||||
T::Currency::reserve(&sender, deposit.clone())?;
|
||||
T::Currency::reserve(&sender, deposit)?;
|
||||
Self::deposit_event(Event::<T>::NameSet { who: sender.clone() });
|
||||
deposit
|
||||
};
|
||||
@@ -172,7 +172,7 @@ pub mod pallet {
|
||||
|
||||
let deposit = <NameOf<T>>::take(&sender).ok_or(Error::<T>::Unnamed)?.1;
|
||||
|
||||
let err_amount = T::Currency::unreserve(&sender, deposit.clone());
|
||||
let err_amount = T::Currency::unreserve(&sender, deposit);
|
||||
debug_assert!(err_amount.is_zero());
|
||||
|
||||
Self::deposit_event(Event::<T>::NameCleared { who: sender, deposit });
|
||||
@@ -204,7 +204,7 @@ pub mod pallet {
|
||||
// Grab their deposit (and check that they have one).
|
||||
let deposit = <NameOf<T>>::take(&target).ok_or(Error::<T>::Unnamed)?.1;
|
||||
// Slash their deposit from them.
|
||||
T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit.clone()).0);
|
||||
T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);
|
||||
|
||||
Self::deposit_event(Event::<T>::NameKilled { target, deposit });
|
||||
Ok(())
|
||||
|
||||
@@ -101,15 +101,14 @@ fn create_offender<T: Config>(n: u32, nominators: u32) -> Result<Offender<T>, &'
|
||||
let controller: T::AccountId = account("controller", n, SEED);
|
||||
let controller_lookup: LookupSourceOf<T> = T::Lookup::unlookup(controller.clone());
|
||||
let reward_destination = RewardDestination::Staked;
|
||||
let raw_amount = bond_amount::<T>();
|
||||
let amount = bond_amount::<T>();
|
||||
// add twice as much balance to prevent the account from being killed.
|
||||
let free_amount = raw_amount.saturating_mul(2u32.into());
|
||||
let free_amount = amount.saturating_mul(2u32.into());
|
||||
T::Currency::make_free_balance_be(&stash, free_amount);
|
||||
let amount: BalanceOf<T> = raw_amount.into();
|
||||
Staking::<T>::bond(
|
||||
RawOrigin::Signed(stash.clone()).into(),
|
||||
controller_lookup.clone(),
|
||||
amount.clone(),
|
||||
amount,
|
||||
reward_destination.clone(),
|
||||
)?;
|
||||
|
||||
@@ -127,12 +126,12 @@ fn create_offender<T: Config>(n: u32, nominators: u32) -> Result<Offender<T>, &'
|
||||
account("nominator controller", n * MAX_NOMINATORS + i, SEED);
|
||||
let nominator_controller_lookup: LookupSourceOf<T> =
|
||||
T::Lookup::unlookup(nominator_controller.clone());
|
||||
T::Currency::make_free_balance_be(&nominator_stash, free_amount.into());
|
||||
T::Currency::make_free_balance_be(&nominator_stash, free_amount);
|
||||
|
||||
Staking::<T>::bond(
|
||||
RawOrigin::Signed(nominator_stash.clone()).into(),
|
||||
nominator_controller_lookup.clone(),
|
||||
amount.clone(),
|
||||
amount,
|
||||
reward_destination.clone(),
|
||||
)?;
|
||||
|
||||
@@ -143,14 +142,13 @@ fn create_offender<T: Config>(n: u32, nominators: u32) -> Result<Offender<T>, &'
|
||||
)?;
|
||||
|
||||
individual_exposures
|
||||
.push(IndividualExposure { who: nominator_stash.clone(), value: amount.clone() });
|
||||
.push(IndividualExposure { who: nominator_stash.clone(), value: amount });
|
||||
nominator_stashes.push(nominator_stash.clone());
|
||||
}
|
||||
|
||||
let exposure =
|
||||
Exposure { total: amount.clone() * n.into(), own: amount, others: individual_exposures };
|
||||
let exposure = Exposure { total: amount * n.into(), own: amount, others: individual_exposures };
|
||||
let current_era = 0u32;
|
||||
Staking::<T>::add_era_stakers(current_era.into(), stash.clone().into(), exposure);
|
||||
Staking::<T>::add_era_stakers(current_era, stash.clone(), exposure);
|
||||
|
||||
Ok(Offender { controller, stash, nominator_stashes })
|
||||
}
|
||||
@@ -327,13 +325,13 @@ benchmarks! {
|
||||
.flat_map(|offender| {
|
||||
let nom_slashes = offender.nominator_stashes.into_iter().flat_map(|nom| {
|
||||
balance_slash(nom.clone()).map(Into::into)
|
||||
.chain(slash(nom.clone()).map(Into::into))
|
||||
}).collect::<Vec<_>>();
|
||||
.chain(slash(nom).map(Into::into))
|
||||
});
|
||||
|
||||
let mut events = chill(offender.stash.clone()).map(Into::into)
|
||||
.chain(balance_slash(offender.stash.clone()).map(Into::into))
|
||||
.chain(slash(offender.stash.clone()).map(Into::into))
|
||||
.chain(nom_slashes.into_iter())
|
||||
.chain(slash(offender.stash).map(Into::into))
|
||||
.chain(nom_slashes)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// the first deposit creates endowed events, see `endowed_reward_events`
|
||||
@@ -341,10 +339,10 @@ benchmarks! {
|
||||
first = false;
|
||||
let mut reward_events = reporters.clone().into_iter()
|
||||
.flat_map(|reporter| vec![
|
||||
balance_deposit(reporter.clone(), reward.into()).into(),
|
||||
balance_deposit(reporter.clone(), reward).into(),
|
||||
frame_system::Event::<T>::NewAccount { account: reporter.clone() }.into(),
|
||||
<T as BalancesConfig>::Event::from(
|
||||
pallet_balances::Event::<T>::Endowed{account: reporter.clone(), free_balance: reward.into()}
|
||||
pallet_balances::Event::<T>::Endowed{account: reporter, free_balance: reward.into()}
|
||||
).into(),
|
||||
])
|
||||
.collect::<Vec<_>>();
|
||||
@@ -352,7 +350,7 @@ benchmarks! {
|
||||
events.into_iter()
|
||||
} else {
|
||||
let mut reward_events = reporters.clone().into_iter()
|
||||
.map(|reporter| balance_deposit(reporter, reward.into()).into())
|
||||
.map(|reporter| balance_deposit(reporter, reward).into())
|
||||
.collect::<Vec<_>>();
|
||||
events.append(&mut reward_events);
|
||||
events.into_iter()
|
||||
|
||||
@@ -136,8 +136,7 @@ where
|
||||
// The amount new offenders are slashed
|
||||
let new_fraction = O::slash_fraction(offenders_count, validator_set_count);
|
||||
|
||||
let slash_perbill: Vec<_> =
|
||||
(0..concurrent_offenders.len()).map(|_| new_fraction.clone()).collect();
|
||||
let slash_perbill: Vec<_> = (0..concurrent_offenders.len()).map(|_| new_fraction).collect();
|
||||
|
||||
T::OnOffenceHandler::on_offence(
|
||||
&concurrent_offenders,
|
||||
@@ -202,7 +201,7 @@ impl<T: Config> Pallet<T> {
|
||||
let concurrent_offenders = storage
|
||||
.concurrent_reports
|
||||
.iter()
|
||||
.filter_map(|report_id| <Reports<T>>::get(report_id))
|
||||
.filter_map(<Reports<T>>::get)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
storage.save();
|
||||
|
||||
@@ -42,8 +42,8 @@ pub fn remove_deferred_storage<T: Config>() -> Weight {
|
||||
log::info!(target: "runtime::offences", "have {} deferred offences, applying.", deferred.len());
|
||||
for (offences, perbill, session) in deferred.iter() {
|
||||
let consumed = T::OnOffenceHandler::on_offence(
|
||||
&offences,
|
||||
&perbill,
|
||||
offences,
|
||||
perbill,
|
||||
*session,
|
||||
DisableStrategy::WhenSlashed,
|
||||
);
|
||||
|
||||
@@ -62,7 +62,7 @@ benchmarks! {
|
||||
let caller = funded_account::<T>("caller", 0);
|
||||
whitelist_account!(caller);
|
||||
let (preimage, hash) = sized_preimage_and_hash::<T>(s);
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
}: note_preimage(RawOrigin::Signed(caller), preimage)
|
||||
verify {
|
||||
assert!(Preimage::<T>::have_preimage(&hash));
|
||||
@@ -71,7 +71,7 @@ benchmarks! {
|
||||
note_no_deposit_preimage {
|
||||
let s in 0 .. T::MaxSize::get();
|
||||
let (preimage, hash) = sized_preimage_and_hash::<T>(s);
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
}: note_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), preimage)
|
||||
verify {
|
||||
assert!(Preimage::<T>::have_preimage(&hash));
|
||||
@@ -83,7 +83,7 @@ benchmarks! {
|
||||
whitelist_account!(caller);
|
||||
let (preimage, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::note_preimage(RawOrigin::Signed(caller.clone()).into(), preimage));
|
||||
}: _(RawOrigin::Signed(caller), hash.clone())
|
||||
}: _(RawOrigin::Signed(caller), hash)
|
||||
verify {
|
||||
assert!(!Preimage::<T>::have_preimage(&hash));
|
||||
}
|
||||
@@ -91,7 +91,7 @@ benchmarks! {
|
||||
unnote_no_deposit_preimage {
|
||||
let (preimage, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::note_preimage(T::ManagerOrigin::successful_origin(), preimage));
|
||||
}: unnote_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash.clone())
|
||||
}: unnote_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash)
|
||||
verify {
|
||||
assert!(!Preimage::<T>::have_preimage(&hash));
|
||||
}
|
||||
@@ -124,7 +124,7 @@ benchmarks! {
|
||||
// Cheap request - the preimage is already requested, so just a counter bump.
|
||||
request_requested_preimage {
|
||||
let (_, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
}: request_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash)
|
||||
verify {
|
||||
assert_eq!(StatusFor::<T>::get(&hash), Some(RequestStatus::Requested(2)));
|
||||
@@ -133,26 +133,26 @@ benchmarks! {
|
||||
// Expensive unrequest - last reference and it's noted, so will destroy the preimage.
|
||||
unrequest_preimage {
|
||||
let (preimage, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
assert_ok!(Preimage::<T>::note_preimage(T::ManagerOrigin::successful_origin(), preimage));
|
||||
}: _<T::Origin>(T::ManagerOrigin::successful_origin(), hash.clone())
|
||||
}: _<T::Origin>(T::ManagerOrigin::successful_origin(), hash)
|
||||
verify {
|
||||
assert_eq!(StatusFor::<T>::get(&hash), None);
|
||||
}
|
||||
// Cheap unrequest - last reference, but it's not noted.
|
||||
unrequest_unnoted_preimage {
|
||||
let (_, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
}: unrequest_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash.clone())
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
}: unrequest_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash)
|
||||
verify {
|
||||
assert_eq!(StatusFor::<T>::get(&hash), None);
|
||||
}
|
||||
// Cheap unrequest - not the last reference.
|
||||
unrequest_multi_referenced_preimage {
|
||||
let (_, hash) = preimage_and_hash::<T>();
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone()));
|
||||
}: unrequest_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash.clone())
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
assert_ok!(Preimage::<T>::request_preimage(T::ManagerOrigin::successful_origin(), hash));
|
||||
}: unrequest_preimage<T::Origin>(T::ManagerOrigin::successful_origin(), hash)
|
||||
verify {
|
||||
assert_eq!(StatusFor::<T>::get(&hash), Some(RequestStatus::Requested(1)));
|
||||
}
|
||||
|
||||
@@ -215,7 +215,8 @@ impl<T: Config> Pallet<T> {
|
||||
// previously requested. This also allows the tx to pay no fee.
|
||||
let was_requested = match (StatusFor::<T>::get(hash), maybe_depositor) {
|
||||
(Some(RequestStatus::Requested(..)), _) => true,
|
||||
(Some(RequestStatus::Unrequested(..)), _) => Err(Error::<T>::AlreadyNoted)?,
|
||||
(Some(RequestStatus::Unrequested(..)), _) =>
|
||||
return Err(Error::<T>::AlreadyNoted.into()),
|
||||
(None, None) => {
|
||||
StatusFor::<T>::insert(hash, RequestStatus::Unrequested(None));
|
||||
false
|
||||
@@ -256,7 +257,7 @@ impl<T: Config> Pallet<T> {
|
||||
});
|
||||
StatusFor::<T>::insert(hash, RequestStatus::Requested(count));
|
||||
if count == 1 {
|
||||
Self::deposit_event(Event::Requested { hash: hash.clone() });
|
||||
Self::deposit_event(Event::Requested { hash: *hash });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,20 +271,17 @@ impl<T: Config> Pallet<T> {
|
||||
) -> DispatchResult {
|
||||
match StatusFor::<T>::get(hash).ok_or(Error::<T>::NotNoted)? {
|
||||
RequestStatus::Unrequested(Some((owner, deposit))) => {
|
||||
ensure!(
|
||||
maybe_check_owner.map_or(true, |c| &c == &owner),
|
||||
Error::<T>::NotAuthorized
|
||||
);
|
||||
ensure!(maybe_check_owner.map_or(true, |c| c == owner), Error::<T>::NotAuthorized);
|
||||
T::Currency::unreserve(&owner, deposit);
|
||||
},
|
||||
RequestStatus::Unrequested(None) => {
|
||||
ensure!(maybe_check_owner.is_none(), Error::<T>::NotAuthorized);
|
||||
},
|
||||
RequestStatus::Requested(_) => Err(Error::<T>::Requested)?,
|
||||
RequestStatus::Requested(_) => return Err(Error::<T>::Requested.into()),
|
||||
}
|
||||
StatusFor::<T>::remove(hash);
|
||||
PreimageFor::<T>::remove(hash);
|
||||
Self::deposit_event(Event::Cleared { hash: hash.clone() });
|
||||
Self::deposit_event(Event::Cleared { hash: *hash });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -298,9 +296,9 @@ impl<T: Config> Pallet<T> {
|
||||
debug_assert!(count == 1, "preimage request counter at zero?");
|
||||
PreimageFor::<T>::remove(hash);
|
||||
StatusFor::<T>::remove(hash);
|
||||
Self::deposit_event(Event::Cleared { hash: hash.clone() });
|
||||
Self::deposit_event(Event::Cleared { hash: *hash });
|
||||
},
|
||||
RequestStatus::Unrequested(_) => Err(Error::<T>::NotRequested)?,
|
||||
RequestStatus::Unrequested(_) => return Err(Error::<T>::NotRequested.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ fn assert_last_event<T: Config>(generic_event: <T as Config>::Event) {
|
||||
}
|
||||
|
||||
fn add_proxies<T: Config>(n: u32, maybe_who: Option<T::AccountId>) -> Result<(), &'static str> {
|
||||
let caller = maybe_who.unwrap_or_else(|| whitelisted_caller());
|
||||
let caller = maybe_who.unwrap_or_else(whitelisted_caller);
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
for i in 0..n {
|
||||
Proxy::<T>::add_proxy(
|
||||
@@ -77,7 +77,7 @@ fn add_announcements<T: Config>(
|
||||
|
||||
benchmarks! {
|
||||
proxy {
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
// In this case the caller is the "target" proxy
|
||||
let caller: T::AccountId = account("target", p - 1, SEED);
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
@@ -91,7 +91,7 @@ benchmarks! {
|
||||
|
||||
proxy_announced {
|
||||
let a in 0 .. T::MaxPending::get() - 1;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
// In this case the caller is the "target" proxy
|
||||
let caller: T::AccountId = account("anonymous", 0, SEED);
|
||||
let delegate: T::AccountId = account("target", p - 1, SEED);
|
||||
@@ -112,7 +112,7 @@ benchmarks! {
|
||||
|
||||
remove_announcement {
|
||||
let a in 0 .. T::MaxPending::get() - 1;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
// In this case the caller is the "target" proxy
|
||||
let caller: T::AccountId = account("target", p - 1, SEED);
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
@@ -133,7 +133,7 @@ benchmarks! {
|
||||
|
||||
reject_announcement {
|
||||
let a in 0 .. T::MaxPending::get() - 1;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
// In this case the caller is the "target" proxy
|
||||
let caller: T::AccountId = account("target", p - 1, SEED);
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
@@ -154,7 +154,7 @@ benchmarks! {
|
||||
|
||||
announce {
|
||||
let a in 0 .. T::MaxPending::get() - 1;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
// In this case the caller is the "target" proxy
|
||||
let caller: T::AccountId = account("target", p - 1, SEED);
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
|
||||
@@ -169,11 +169,11 @@ benchmarks! {
|
||||
}
|
||||
|
||||
add_proxy {
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
}: _(
|
||||
RawOrigin::Signed(caller.clone()),
|
||||
account("target", T::MaxProxies::get().into(), SEED),
|
||||
account("target", T::MaxProxies::get(), SEED),
|
||||
T::ProxyType::default(),
|
||||
T::BlockNumber::zero()
|
||||
)
|
||||
@@ -183,7 +183,7 @@ benchmarks! {
|
||||
}
|
||||
|
||||
remove_proxy {
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
}: _(
|
||||
RawOrigin::Signed(caller.clone()),
|
||||
@@ -197,7 +197,7 @@ benchmarks! {
|
||||
}
|
||||
|
||||
remove_proxies {
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
}: _(RawOrigin::Signed(caller.clone()))
|
||||
verify {
|
||||
@@ -206,7 +206,7 @@ benchmarks! {
|
||||
}
|
||||
|
||||
anonymous {
|
||||
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
|
||||
let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::<T>(p, None)?;
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
}: _(
|
||||
RawOrigin::Signed(caller.clone()),
|
||||
@@ -225,7 +225,7 @@ benchmarks! {
|
||||
}
|
||||
|
||||
kill_anonymous {
|
||||
let p in 0 .. (T::MaxProxies::get() - 2).into();
|
||||
let p in 0 .. (T::MaxProxies::get() - 2);
|
||||
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
|
||||
|
||||
@@ -196,7 +196,7 @@ pub mod pallet {
|
||||
/// # </weight>
|
||||
#[pallet::weight({
|
||||
let di = call.get_dispatch_info();
|
||||
(T::WeightInfo::proxy(T::MaxProxies::get().into())
|
||||
(T::WeightInfo::proxy(T::MaxProxies::get())
|
||||
.saturating_add(di.weight)
|
||||
// AccountData for inner call origin accountdata.
|
||||
.saturating_add(T::DbWeight::get().reads_writes(1, 1)),
|
||||
@@ -230,7 +230,7 @@ pub mod pallet {
|
||||
/// # <weight>
|
||||
/// Weight is a function of the number of proxies the user has (P).
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::add_proxy(T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::add_proxy(T::MaxProxies::get()))]
|
||||
pub fn add_proxy(
|
||||
origin: OriginFor<T>,
|
||||
delegate: T::AccountId,
|
||||
@@ -252,7 +252,7 @@ pub mod pallet {
|
||||
/// # <weight>
|
||||
/// Weight is a function of the number of proxies the user has (P).
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::remove_proxy(T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::remove_proxy(T::MaxProxies::get()))]
|
||||
pub fn remove_proxy(
|
||||
origin: OriginFor<T>,
|
||||
delegate: T::AccountId,
|
||||
@@ -273,7 +273,7 @@ pub mod pallet {
|
||||
/// # <weight>
|
||||
/// Weight is a function of the number of proxies the user has (P).
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::remove_proxies(T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::remove_proxies(T::MaxProxies::get()))]
|
||||
pub fn remove_proxies(origin: OriginFor<T>) -> DispatchResult {
|
||||
let who = ensure_signed(origin)?;
|
||||
let (_, old_deposit) = Proxies::<T>::take(&who);
|
||||
@@ -305,7 +305,7 @@ pub mod pallet {
|
||||
/// Weight is a function of the number of proxies the user has (P).
|
||||
/// # </weight>
|
||||
/// TODO: Might be over counting 1 read
|
||||
#[pallet::weight(T::WeightInfo::anonymous(T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::anonymous(T::MaxProxies::get()))]
|
||||
pub fn anonymous(
|
||||
origin: OriginFor<T>,
|
||||
proxy_type: T::ProxyType,
|
||||
@@ -356,7 +356,7 @@ pub mod pallet {
|
||||
/// # <weight>
|
||||
/// Weight is a function of the number of proxies the user has (P).
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::kill_anonymous(T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::kill_anonymous(T::MaxProxies::get()))]
|
||||
pub fn kill_anonymous(
|
||||
origin: OriginFor<T>,
|
||||
spawner: T::AccountId,
|
||||
@@ -398,7 +398,7 @@ pub mod pallet {
|
||||
/// - A: the number of announcements made.
|
||||
/// - P: the number of proxies the user has.
|
||||
/// # </weight>
|
||||
#[pallet::weight(T::WeightInfo::announce(T::MaxPending::get(), T::MaxProxies::get().into()))]
|
||||
#[pallet::weight(T::WeightInfo::announce(T::MaxPending::get(), T::MaxProxies::get()))]
|
||||
pub fn announce(
|
||||
origin: OriginFor<T>,
|
||||
real: T::AccountId,
|
||||
@@ -408,12 +408,12 @@ pub mod pallet {
|
||||
Proxies::<T>::get(&real)
|
||||
.0
|
||||
.into_iter()
|
||||
.find(|x| &x.delegate == &who)
|
||||
.find(|x| x.delegate == who)
|
||||
.ok_or(Error::<T>::NotProxy)?;
|
||||
|
||||
let announcement = Announcement {
|
||||
real: real.clone(),
|
||||
call_hash: call_hash.clone(),
|
||||
call_hash,
|
||||
height: system::Pallet::<T>::block_number(),
|
||||
};
|
||||
|
||||
@@ -452,9 +452,10 @@ pub mod pallet {
|
||||
/// - A: the number of announcements made.
|
||||
/// - P: the number of proxies the user has.
|
||||
/// # </weight>
|
||||
#[pallet::weight(
|
||||
T::WeightInfo::remove_announcement(T::MaxPending::get(), T::MaxProxies::get().into())
|
||||
)]
|
||||
#[pallet::weight(T::WeightInfo::remove_announcement(
|
||||
T::MaxPending::get(),
|
||||
T::MaxProxies::get()
|
||||
))]
|
||||
pub fn remove_announcement(
|
||||
origin: OriginFor<T>,
|
||||
real: T::AccountId,
|
||||
@@ -482,9 +483,10 @@ pub mod pallet {
|
||||
/// - A: the number of announcements made.
|
||||
/// - P: the number of proxies the user has.
|
||||
/// # </weight>
|
||||
#[pallet::weight(
|
||||
T::WeightInfo::reject_announcement(T::MaxPending::get(), T::MaxProxies::get().into())
|
||||
)]
|
||||
#[pallet::weight(T::WeightInfo::reject_announcement(
|
||||
T::MaxPending::get(),
|
||||
T::MaxProxies::get()
|
||||
))]
|
||||
pub fn reject_announcement(
|
||||
origin: OriginFor<T>,
|
||||
delegate: T::AccountId,
|
||||
@@ -517,7 +519,7 @@ pub mod pallet {
|
||||
/// # </weight>
|
||||
#[pallet::weight({
|
||||
let di = call.get_dispatch_info();
|
||||
(T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get().into())
|
||||
(T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get())
|
||||
.saturating_add(di.weight)
|
||||
// AccountData for inner call origin accountdata.
|
||||
.saturating_add(T::DbWeight::get().reads_writes(1, 1)),
|
||||
@@ -759,9 +761,9 @@ impl<T: Config> Pallet<T> {
|
||||
let new_deposit =
|
||||
if len == 0 { BalanceOf::<T>::zero() } else { base + factor * (len as u32).into() };
|
||||
if new_deposit > old_deposit {
|
||||
T::Currency::reserve(&who, new_deposit - old_deposit)?;
|
||||
T::Currency::reserve(who, new_deposit - old_deposit)?;
|
||||
} else if new_deposit < old_deposit {
|
||||
T::Currency::unreserve(&who, old_deposit - new_deposit);
|
||||
T::Currency::unreserve(who, old_deposit - new_deposit);
|
||||
}
|
||||
Ok(if len == 0 { None } else { Some(new_deposit) })
|
||||
}
|
||||
@@ -816,7 +818,7 @@ impl<T: Config> Pallet<T> {
|
||||
// has.
|
||||
Some(Call::add_proxy { ref proxy_type, .. }) |
|
||||
Some(Call::remove_proxy { ref proxy_type, .. })
|
||||
if !def.proxy_type.is_superset(&proxy_type) =>
|
||||
if !def.proxy_type.is_superset(proxy_type) =>
|
||||
false,
|
||||
// Proxy call cannot remove all proxies or kill anonymous proxies unless it has full
|
||||
// permissions.
|
||||
|
||||
@@ -388,7 +388,7 @@ pub mod pallet {
|
||||
let who = ensure_signed(origin)?;
|
||||
// Check `who` is allowed to make a call on behalf of `account`
|
||||
let target = Self::proxy(&who).ok_or(Error::<T>::NotAllowed)?;
|
||||
ensure!(&target == &account, Error::<T>::NotAllowed);
|
||||
ensure!(target == account, Error::<T>::NotAllowed);
|
||||
call.dispatch(frame_system::RawOrigin::Signed(account).into())
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.error)
|
||||
@@ -541,7 +541,7 @@ pub mod pallet {
|
||||
ensure!(Self::is_friend(&recovery_config.friends, &who), Error::<T>::NotFriend);
|
||||
// Either insert the vouch, or return an error that the user already vouched.
|
||||
match active_recovery.friends.binary_search(&who) {
|
||||
Ok(_pos) => Err(Error::<T>::AlreadyVouched)?,
|
||||
Ok(_pos) => return Err(Error::<T>::AlreadyVouched.into()),
|
||||
Err(pos) => active_recovery
|
||||
.friends
|
||||
.try_insert(pos, who.clone())
|
||||
|
||||
@@ -57,10 +57,7 @@ fn create_referendum<T: Config>() -> (T::AccountId, ReferendumIndex) {
|
||||
fn place_deposit<T: Config>(index: ReferendumIndex) {
|
||||
let caller = funded_account::<T>("caller", 0);
|
||||
whitelist_account!(caller);
|
||||
assert_ok!(Referenda::<T>::place_decision_deposit(
|
||||
RawOrigin::Signed(caller.clone()).into(),
|
||||
index,
|
||||
));
|
||||
assert_ok!(Referenda::<T>::place_decision_deposit(RawOrigin::Signed(caller).into(), index));
|
||||
}
|
||||
|
||||
fn nudge<T: Config>(index: ReferendumIndex) {
|
||||
@@ -265,7 +262,7 @@ benchmarks! {
|
||||
let track = Referenda::<T>::ensure_ongoing(index).unwrap().track;
|
||||
assert_ok!(Referenda::<T>::cancel(T::CancelOrigin::successful_origin(), index));
|
||||
assert_eq!(DecidingCount::<T>::get(&track), 1);
|
||||
}: one_fewer_deciding(RawOrigin::Root, track.clone())
|
||||
}: one_fewer_deciding(RawOrigin::Root, track)
|
||||
verify {
|
||||
assert_eq!(DecidingCount::<T>::get(&track), 0);
|
||||
}
|
||||
@@ -278,7 +275,7 @@ benchmarks! {
|
||||
assert_ok!(Referenda::<T>::cancel(T::CancelOrigin::successful_origin(), queued[0]));
|
||||
assert_eq!(TrackQueue::<T>::get(&track).len() as u32, T::MaxQueued::get());
|
||||
let deciding_count = DecidingCount::<T>::get(&track);
|
||||
}: one_fewer_deciding(RawOrigin::Root, track.clone())
|
||||
}: one_fewer_deciding(RawOrigin::Root, track)
|
||||
verify {
|
||||
assert_eq!(DecidingCount::<T>::get(&track), deciding_count);
|
||||
assert_eq!(TrackQueue::<T>::get(&track).len() as u32, T::MaxQueued::get() - 1);
|
||||
@@ -297,7 +294,7 @@ benchmarks! {
|
||||
assert_ok!(Referenda::<T>::cancel(T::CancelOrigin::successful_origin(), queued[0]));
|
||||
assert_eq!(TrackQueue::<T>::get(&track).len() as u32, T::MaxQueued::get());
|
||||
let deciding_count = DecidingCount::<T>::get(&track);
|
||||
}: one_fewer_deciding(RawOrigin::Root, track.clone())
|
||||
}: one_fewer_deciding(RawOrigin::Root, track)
|
||||
verify {
|
||||
assert_eq!(DecidingCount::<T>::get(&track), deciding_count);
|
||||
assert_eq!(TrackQueue::<T>::get(&track).len() as u32, T::MaxQueued::get() - 1);
|
||||
|
||||
@@ -363,7 +363,7 @@ pub mod pallet {
|
||||
let status = ReferendumStatus {
|
||||
track,
|
||||
origin: proposal_origin,
|
||||
proposal_hash: proposal_hash.clone(),
|
||||
proposal_hash,
|
||||
enactment: enactment_moment,
|
||||
submitted: now,
|
||||
submission_deposit,
|
||||
@@ -643,7 +643,7 @@ impl<T: Config<I>, I: 'static> Polling<T::Tally> for Pallet<T, I> {
|
||||
.iter()
|
||||
.max_by_key(|(_, info)| info.max_deciding)
|
||||
.expect("Always one class");
|
||||
(r.0.clone(), r.1.max_deciding)
|
||||
(r.0, r.1.max_deciding)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -730,8 +730,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
Self::deposit_event(Event::<T, I>::DecisionStarted {
|
||||
index,
|
||||
tally: status.tally.clone(),
|
||||
proposal_hash: status.proposal_hash.clone(),
|
||||
track: status.track.clone(),
|
||||
proposal_hash: status.proposal_hash,
|
||||
track: status.track,
|
||||
});
|
||||
let confirming = if is_passing {
|
||||
Self::deposit_event(Event::<T, I>::ConfirmStarted { index });
|
||||
@@ -895,7 +895,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
let prepare_end = status.submitted.saturating_add(track.prepare_period);
|
||||
if now >= prepare_end {
|
||||
let (maybe_alarm, branch) =
|
||||
Self::ready_for_deciding(now, &track, index, &mut status);
|
||||
Self::ready_for_deciding(now, track, index, &mut status);
|
||||
if let Some(set_alarm) = maybe_alarm {
|
||||
alarm = alarm.min(set_alarm);
|
||||
}
|
||||
@@ -934,7 +934,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
&track.min_approval,
|
||||
);
|
||||
branch = if is_passing {
|
||||
match deciding.confirming.clone() {
|
||||
match deciding.confirming {
|
||||
Some(t) if now >= t => {
|
||||
// Passed!
|
||||
Self::ensure_no_alarm(&mut status);
|
||||
@@ -996,7 +996,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
ServiceBranch::ContinueNotConfirming
|
||||
}
|
||||
};
|
||||
alarm = Self::decision_time(&deciding, &status.tally, track);
|
||||
alarm = Self::decision_time(deciding, &status.tally, track);
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -182,7 +182,7 @@ pub trait TracksInfo<Balance, Moment> {
|
||||
|
||||
/// Return the track info for track `id`, by default this just looks it up in `Self::tracks()`.
|
||||
fn info(id: Self::Id) -> Option<&'static TrackInfo<Balance, Moment>> {
|
||||
Self::tracks().iter().find(|x| &x.0 == &id).map(|x| &x.1)
|
||||
Self::tracks().iter().find(|x| x.0 == id).map(|x| &x.1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,9 +309,9 @@ impl Curve {
|
||||
match self {
|
||||
Self::LinearDecreasing { begin, delta } =>
|
||||
if delta.is_zero() {
|
||||
return *delta
|
||||
*delta
|
||||
} else {
|
||||
return (*begin - y.min(*begin)).min(*delta) / *delta
|
||||
(*begin - y.min(*begin)).min(*delta) / *delta
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,7 +727,7 @@ impl<T: Config> Pallet<T> {
|
||||
Self::deposit_event(Event::Canceled { when, index });
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::NotFound)?
|
||||
return Err(Error::<T>::NotFound.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -765,7 +765,7 @@ impl<T: Config> Pallet<T> {
|
||||
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
|
||||
// ensure id it is unique
|
||||
if Lookup::<T>::contains_key(&id) {
|
||||
return Err(Error::<T>::FailedToSchedule)?
|
||||
return Err(Error::<T>::FailedToSchedule.into())
|
||||
}
|
||||
|
||||
let when = Self::resolve_time(when)?;
|
||||
@@ -817,7 +817,7 @@ impl<T: Config> Pallet<T> {
|
||||
Self::deposit_event(Event::Canceled { when, index });
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T>::NotFound)?
|
||||
return Err(Error::<T>::NotFound.into())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ pub mod pallet {
|
||||
// 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())
|
||||
T::Currency::reserve(who, T::CandidateDeposit::get())
|
||||
.expect("balance too low to create candidacy");
|
||||
<CandidateExists<T, I>>::insert(who, true);
|
||||
});
|
||||
@@ -387,7 +387,7 @@ pub mod pallet {
|
||||
// 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 item = (who, Some(score));
|
||||
let location = pool
|
||||
.binary_search_by_key(&Reverse(score), |(_, maybe_score)| {
|
||||
Reverse(maybe_score.unwrap_or_default())
|
||||
|
||||
@@ -27,13 +27,10 @@ pub(super) const LAST_PRUNE: &[u8] = b"session_historical_last_prune";
|
||||
|
||||
/// Derive the key used to store the list of validators
|
||||
pub(super) fn derive_key<P: AsRef<[u8]>>(prefix: P, session_index: SessionIndex) -> Vec<u8> {
|
||||
let prefix: &[u8] = prefix.as_ref();
|
||||
session_index.using_encoded(|encoded_session_index| {
|
||||
prefix
|
||||
.into_iter()
|
||||
.chain(b"/".into_iter())
|
||||
.chain(encoded_session_index.into_iter())
|
||||
.copied()
|
||||
.collect::<Vec<u8>>()
|
||||
let mut key = prefix.as_ref().to_owned();
|
||||
key.push(b'/');
|
||||
key.extend_from_slice(encoded_session_index);
|
||||
key
|
||||
})
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ impl<
|
||||
// (0% is never returned).
|
||||
let progress = if now >= offset {
|
||||
let current = (now - offset) % period.clone() + One::one();
|
||||
Some(Permill::from_rational(current.clone(), period.clone()))
|
||||
Some(Permill::from_rational(current, period))
|
||||
} else {
|
||||
Some(Permill::from_rational(now + One::one(), offset))
|
||||
};
|
||||
@@ -689,7 +689,6 @@ impl<T: Config> Pallet<T> {
|
||||
if let Some(&(_, ref old_keys)) = now_session_keys.next() {
|
||||
if old_keys != keys {
|
||||
changed = true;
|
||||
return
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -803,10 +802,10 @@ impl<T: Config> Pallet<T> {
|
||||
let who = T::ValidatorIdOf::convert(account.clone())
|
||||
.ok_or(Error::<T>::NoAssociatedValidatorId)?;
|
||||
|
||||
ensure!(frame_system::Pallet::<T>::can_inc_consumer(&account), Error::<T>::NoAccount);
|
||||
ensure!(frame_system::Pallet::<T>::can_inc_consumer(account), Error::<T>::NoAccount);
|
||||
let old_keys = Self::inner_set_keys(&who, keys)?;
|
||||
if old_keys.is_none() {
|
||||
let assertion = frame_system::Pallet::<T>::inc_consumers(&account).is_ok();
|
||||
let assertion = frame_system::Pallet::<T>::inc_consumers(account).is_ok();
|
||||
debug_assert!(assertion, "can_inc_consumer() returned true; no change since; qed");
|
||||
}
|
||||
|
||||
@@ -866,7 +865,7 @@ impl<T: Config> Pallet<T> {
|
||||
let key_data = old_keys.get_raw(*id);
|
||||
Self::clear_key_owner(*id, key_data);
|
||||
}
|
||||
frame_system::Pallet::<T>::dec_consumers(&account);
|
||||
frame_system::Pallet::<T>::dec_consumers(account);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -949,6 +948,6 @@ impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::ValidatorId>
|
||||
let i = Inner::find_author(digests)?;
|
||||
|
||||
let validators = <Pallet<T>>::validators();
|
||||
validators.get(i as usize).map(|k| k.clone())
|
||||
validators.get(i as usize).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,10 +357,10 @@ impl<AccountId: PartialEq, Balance> BidKind<AccountId, Balance> {
|
||||
if a == v {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("incorrect identity")?
|
||||
Err("incorrect identity".into())
|
||||
}
|
||||
} else {
|
||||
Err("not vouched")?
|
||||
Err("not vouched".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -724,7 +724,7 @@ pub mod pallet {
|
||||
let deposit = T::CandidateDeposit::get();
|
||||
T::Currency::reserve(&who, deposit)?;
|
||||
|
||||
Self::put_bid(bids, &who, value.clone(), BidKind::Deposit(deposit));
|
||||
Self::put_bid(bids, &who, value, BidKind::Deposit(deposit));
|
||||
Self::deposit_event(Event::<T, I>::Bid { candidate_id: who, offer: value });
|
||||
Ok(())
|
||||
}
|
||||
@@ -770,7 +770,7 @@ pub mod pallet {
|
||||
Self::deposit_event(Event::<T, I>::Unbid { candidate: who });
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T, I>::BadPosition)?
|
||||
Err(Error::<T, I>::BadPosition.into())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -844,7 +844,7 @@ pub mod pallet {
|
||||
ensure!(!<Vouching<T, I>>::contains_key(&voucher), Error::<T, I>::AlreadyVouching);
|
||||
|
||||
<Vouching<T, I>>::insert(&voucher, VouchingStatus::Vouching);
|
||||
Self::put_bid(bids, &who, value.clone(), BidKind::Vouch(voucher.clone(), tip));
|
||||
Self::put_bid(bids, &who, value, BidKind::Vouch(voucher.clone(), tip));
|
||||
Self::deposit_event(Event::<T, I>::Vouch {
|
||||
candidate_id: who,
|
||||
offer: value,
|
||||
@@ -887,7 +887,7 @@ pub mod pallet {
|
||||
Self::deposit_event(Event::<T, I>::Unvouch { candidate: who });
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::<T, I>::BadPosition)?
|
||||
Err(Error::<T, I>::BadPosition.into())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1001,7 +1001,7 @@ pub mod pallet {
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
Err(Error::<T, I>::NoPayout)?
|
||||
Err(Error::<T, I>::NoPayout.into())
|
||||
}
|
||||
|
||||
/// Found the society.
|
||||
@@ -1229,7 +1229,7 @@ pub mod pallet {
|
||||
// Remove suspended candidate
|
||||
<SuspendedCandidates<T, I>>::remove(who);
|
||||
} else {
|
||||
Err(Error::<T, I>::NotSuspended)?
|
||||
return Err(Error::<T, I>::NotSuspended.into())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1392,8 +1392,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
ensure!(Self::founder() != Some(m.clone()), Error::<T, I>::Founder);
|
||||
|
||||
let mut members = <Members<T, I>>::get();
|
||||
match members.binary_search(&m) {
|
||||
Err(_) => Err(Error::<T, I>::NotMember)?,
|
||||
match members.binary_search(m) {
|
||||
Err(_) => Err(Error::<T, I>::NotMember.into()),
|
||||
Ok(i) => {
|
||||
members.remove(i);
|
||||
T::MembershipChanged::change_members_sorted(&[], &[m.clone()], &members[..]);
|
||||
@@ -1572,7 +1572,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
<Members<T, I>>::put(&members[..]);
|
||||
<Head<T, I>>::put(&primary);
|
||||
|
||||
T::MembershipChanged::change_members_sorted(&accounts, &[], &members);
|
||||
T::MembershipChanged::change_members_sorted(&accounts, &[], members);
|
||||
Self::deposit_event(Event::<T, I>::Inducted { primary, candidates: accounts });
|
||||
}
|
||||
|
||||
@@ -1605,7 +1605,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
if !payouts.is_empty() {
|
||||
let mut dropped = 0;
|
||||
for (_, amount) in payouts.iter_mut() {
|
||||
if let Some(new_rest) = rest.checked_sub(&amount) {
|
||||
if let Some(new_rest) = rest.checked_sub(amount) {
|
||||
// not yet totally slashed after this one; drop it completely.
|
||||
rest = new_rest;
|
||||
dropped += 1;
|
||||
@@ -1635,7 +1635,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
|
||||
/// Suspend a user, removing them from the member list.
|
||||
fn suspend_member(who: &T::AccountId) {
|
||||
if Self::remove_member(&who).is_ok() {
|
||||
if Self::remove_member(who).is_ok() {
|
||||
<SuspendedMembers<T, I>>::insert(who, true);
|
||||
<Strikes<T, I>>::remove(who);
|
||||
Self::deposit_event(Event::<T, I>::MemberSuspended { member: who.clone() });
|
||||
@@ -1683,12 +1683,10 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
let mut approval_count = 0;
|
||||
let mut rejection_count = 0;
|
||||
// Tallies total number of approve and reject votes for the defender.
|
||||
members.iter().filter_map(|m| <DefenderVotes<T, I>>::take(m)).for_each(
|
||||
|v| match v {
|
||||
Vote::Approve => approval_count += 1,
|
||||
_ => rejection_count += 1,
|
||||
},
|
||||
);
|
||||
members.iter().filter_map(<DefenderVotes<T, I>>::take).for_each(|v| match v {
|
||||
Vote::Approve => approval_count += 1,
|
||||
_ => rejection_count += 1,
|
||||
});
|
||||
|
||||
if approval_count <= rejection_count {
|
||||
// User has failed the challenge
|
||||
|
||||
@@ -137,20 +137,18 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint {
|
||||
|
||||
if taylor_sum_positive == last_taylor_term_positive {
|
||||
taylor_sum = taylor_sum.add(&last_taylor_term);
|
||||
} else if taylor_sum >= last_taylor_term {
|
||||
taylor_sum = taylor_sum
|
||||
.sub(&last_taylor_term)
|
||||
// NOTE: Should never happen as checked above
|
||||
.unwrap_or_else(|e| e);
|
||||
} else {
|
||||
if taylor_sum >= last_taylor_term {
|
||||
taylor_sum = taylor_sum
|
||||
.sub(&last_taylor_term)
|
||||
// NOTE: Should never happen as checked above
|
||||
.unwrap_or_else(|e| e);
|
||||
} else {
|
||||
taylor_sum_positive = !taylor_sum_positive;
|
||||
taylor_sum = last_taylor_term
|
||||
.clone()
|
||||
.sub(&taylor_sum)
|
||||
// NOTE: Should never happen as checked above
|
||||
.unwrap_or_else(|e| e);
|
||||
}
|
||||
taylor_sum_positive = !taylor_sum_positive;
|
||||
taylor_sum = last_taylor_term
|
||||
.clone()
|
||||
.sub(&taylor_sum)
|
||||
// NOTE: Should never happen as checked above
|
||||
.unwrap_or_else(|e| e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,10 +215,10 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint {
|
||||
return new_a
|
||||
.div(b, false)
|
||||
.map(|res| res.0)
|
||||
.unwrap_or_else(|| BigUint::zero())
|
||||
.unwrap_or_else(BigUint::zero)
|
||||
.div_unit(100_000)
|
||||
.div_unit(100_000)
|
||||
}
|
||||
|
||||
a.div(b, false).map(|res| res.0).unwrap_or_else(|| BigUint::zero())
|
||||
a.div(b, false).map(|res| res.0).unwrap_or_else(BigUint::zero)
|
||||
}
|
||||
|
||||
@@ -183,8 +183,8 @@ impl<T: Config> ListScenario<T> {
|
||||
Default::default(),
|
||||
)?;
|
||||
Staking::<T>::nominate(
|
||||
RawOrigin::Signed(origin_controller2.clone()).into(),
|
||||
vec![T::Lookup::unlookup(account("random_validator", 0, SEED))].clone(),
|
||||
RawOrigin::Signed(origin_controller2).into(),
|
||||
vec![T::Lookup::unlookup(account("random_validator", 0, SEED))],
|
||||
)?;
|
||||
|
||||
// find a destination weight that will trigger the worst case scenario
|
||||
@@ -239,10 +239,10 @@ benchmarks! {
|
||||
// the weight the nominator will start at.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
|
||||
let max_additional = scenario.dest_weight.clone() - origin_weight;
|
||||
let max_additional = scenario.dest_weight - origin_weight;
|
||||
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let controller = scenario.origin_controller1;
|
||||
let original_bonded: BalanceOf<T>
|
||||
= Ledger::<T>::get(&controller).map(|l| l.active).ok_or("ledger not created after")?;
|
||||
|
||||
@@ -271,7 +271,7 @@ benchmarks! {
|
||||
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let amount = origin_weight - scenario.dest_weight.clone();
|
||||
let amount = origin_weight - scenario.dest_weight;
|
||||
let ledger = Ledger::<T>::get(&controller).ok_or("ledger not created before")?;
|
||||
let original_bonded: BalanceOf<T> = ledger.active;
|
||||
|
||||
@@ -315,7 +315,7 @@ benchmarks! {
|
||||
// destination position because we are doing a removal from the list but no insert.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let stash = scenario.origin_stash1;
|
||||
assert!(T::VoterList::contains(&stash));
|
||||
|
||||
let ed = T::Currency::minimum_balance();
|
||||
@@ -450,7 +450,7 @@ benchmarks! {
|
||||
// destination position because we are doing a removal from the list but no insert.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let stash = scenario.origin_stash1;
|
||||
assert!(T::VoterList::contains(&stash));
|
||||
|
||||
whitelist_account!(controller);
|
||||
@@ -518,7 +518,7 @@ benchmarks! {
|
||||
// destination position because we are doing a removal from the list but no insert.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let stash = scenario.origin_stash1;
|
||||
assert!(T::VoterList::contains(&stash));
|
||||
add_slashing_spans::<T>(&stash, s);
|
||||
|
||||
@@ -561,10 +561,10 @@ benchmarks! {
|
||||
let validator_controller = <Bonded<T>>::get(&validator).unwrap();
|
||||
let balance_before = T::Currency::free_balance(&validator_controller);
|
||||
for (_, controller) in &nominators {
|
||||
let balance = T::Currency::free_balance(&controller);
|
||||
let balance = T::Currency::free_balance(controller);
|
||||
ensure!(balance.is_zero(), "Controller has balance, but should be dead.");
|
||||
}
|
||||
}: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era)
|
||||
}: payout_stakers(RawOrigin::Signed(caller), validator, current_era)
|
||||
verify {
|
||||
let balance_after = T::Currency::free_balance(&validator_controller);
|
||||
ensure!(
|
||||
@@ -572,7 +572,7 @@ benchmarks! {
|
||||
"Balance of validator controller should have increased after payout.",
|
||||
);
|
||||
for (_, controller) in &nominators {
|
||||
let balance = T::Currency::free_balance(&controller);
|
||||
let balance = T::Currency::free_balance(controller);
|
||||
ensure!(!balance.is_zero(), "Payout not given to controller.");
|
||||
}
|
||||
}
|
||||
@@ -594,7 +594,7 @@ benchmarks! {
|
||||
let balance_before = T::Currency::free_balance(&validator);
|
||||
let mut nominator_balances_before = Vec::new();
|
||||
for (stash, _) in &nominators {
|
||||
let balance = T::Currency::free_balance(&stash);
|
||||
let balance = T::Currency::free_balance(stash);
|
||||
nominator_balances_before.push(balance);
|
||||
}
|
||||
}: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era)
|
||||
@@ -605,7 +605,7 @@ benchmarks! {
|
||||
"Balance of validator stash should have increased after payout.",
|
||||
);
|
||||
for ((stash, _), balance_before) in nominators.iter().zip(nominator_balances_before.iter()) {
|
||||
let balance_after = T::Currency::free_balance(&stash);
|
||||
let balance_after = T::Currency::free_balance(stash);
|
||||
ensure!(
|
||||
balance_before < &balance_after,
|
||||
"Balance of nominator stash should have increased after payout.",
|
||||
@@ -626,7 +626,7 @@ benchmarks! {
|
||||
|
||||
// setup a worst case list scenario.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let dest_weight = scenario.dest_weight.clone();
|
||||
let dest_weight = scenario.dest_weight;
|
||||
|
||||
// rebond an amount that will give the user dest_weight
|
||||
let rebond_amount = dest_weight - origin_weight;
|
||||
@@ -644,7 +644,7 @@ benchmarks! {
|
||||
};
|
||||
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let controller = scenario.origin_controller1;
|
||||
let mut staking_ledger = Ledger::<T>::get(controller.clone()).unwrap();
|
||||
|
||||
for _ in 0 .. l {
|
||||
@@ -691,7 +691,7 @@ benchmarks! {
|
||||
// destination position because we are doing a removal from the list but no insert.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let stash = scenario.origin_stash1;
|
||||
|
||||
add_slashing_spans::<T>(&stash, s);
|
||||
let l = StakingLedger {
|
||||
@@ -895,7 +895,7 @@ benchmarks! {
|
||||
// destination position because we are doing a removal from the list but no insert.
|
||||
let scenario = ListScenario::<T>::new(origin_weight, true)?;
|
||||
let controller = scenario.origin_controller1.clone();
|
||||
let stash = scenario.origin_stash1.clone();
|
||||
let stash = scenario.origin_stash1;
|
||||
assert!(T::VoterList::contains(&stash));
|
||||
|
||||
Staking::<T>::set_staking_configs(
|
||||
@@ -909,7 +909,7 @@ benchmarks! {
|
||||
)?;
|
||||
|
||||
let caller = whitelisted_caller();
|
||||
}: _(RawOrigin::Signed(caller), controller.clone())
|
||||
}: _(RawOrigin::Signed(caller), controller)
|
||||
verify {
|
||||
assert!(!T::VoterList::contains(&stash));
|
||||
}
|
||||
|
||||
@@ -321,7 +321,7 @@ pub use weights::WeightInfo;
|
||||
|
||||
pub use pallet::{pallet::*, *};
|
||||
|
||||
pub(crate) const LOG_TARGET: &'static str = "runtime::staking";
|
||||
pub(crate) const LOG_TARGET: &str = "runtime::staking";
|
||||
|
||||
// syntactic sugar for logging.
|
||||
#[macro_export]
|
||||
@@ -784,7 +784,7 @@ impl<Balance: AtLeast32BitUnsigned + Clone, T: Get<&'static PiecewiseLinear<'sta
|
||||
era_duration_millis: u64,
|
||||
) -> (Balance, Balance) {
|
||||
let (validator_payout, max_payout) = inflation::compute_total_payout(
|
||||
&T::get(),
|
||||
T::get(),
|
||||
total_staked,
|
||||
total_issuance,
|
||||
// Duration of era; more than u64::MAX is rewarded as u64::MAX.
|
||||
|
||||
@@ -123,8 +123,9 @@ impl<T: Config> Pallet<T> {
|
||||
.claimed_rewards
|
||||
.retain(|&x| x >= current_era.saturating_sub(history_depth));
|
||||
match ledger.claimed_rewards.binary_search(&era) {
|
||||
Ok(_) => Err(Error::<T>::AlreadyClaimed
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))?,
|
||||
Ok(_) =>
|
||||
return Err(Error::<T>::AlreadyClaimed
|
||||
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))),
|
||||
Err(pos) => ledger.claimed_rewards.insert(pos, era),
|
||||
}
|
||||
|
||||
@@ -146,8 +147,8 @@ impl<T: Config> Pallet<T> {
|
||||
let validator_reward_points = era_reward_points
|
||||
.individual
|
||||
.get(&ledger.stash)
|
||||
.map(|points| *points)
|
||||
.unwrap_or_else(|| Zero::zero());
|
||||
.copied()
|
||||
.unwrap_or_else(Zero::zero);
|
||||
|
||||
// Nothing to do if they have no reward points.
|
||||
if validator_reward_points.is_zero() {
|
||||
@@ -260,8 +261,7 @@ impl<T: Config> Pallet<T> {
|
||||
0
|
||||
});
|
||||
|
||||
let era_length =
|
||||
session_index.checked_sub(current_era_start_session_index).unwrap_or(0); // Must never happen.
|
||||
let era_length = session_index.saturating_sub(current_era_start_session_index); // Must never happen.
|
||||
|
||||
match ForceEra::<T>::get() {
|
||||
// Will be set to `NotForcing` again if a new era has been triggered.
|
||||
@@ -1036,7 +1036,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
|
||||
);
|
||||
Self::do_add_nominator(
|
||||
&v,
|
||||
Nominations { targets: t.try_into().unwrap(), submitted_in: 0, suppressed: false },
|
||||
Nominations { targets: t, submitted_in: 0, suppressed: false },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -580,7 +580,7 @@ pub mod pallet {
|
||||
status
|
||||
);
|
||||
assert!(
|
||||
T::Currency::free_balance(&stash) >= balance,
|
||||
T::Currency::free_balance(stash) >= balance,
|
||||
"Stash does not have enough balance to bond."
|
||||
);
|
||||
frame_support::assert_ok!(<Pallet<T>>::bond(
|
||||
@@ -779,18 +779,18 @@ pub mod pallet {
|
||||
let stash = ensure_signed(origin)?;
|
||||
|
||||
if <Bonded<T>>::contains_key(&stash) {
|
||||
Err(Error::<T>::AlreadyBonded)?
|
||||
return Err(Error::<T>::AlreadyBonded.into())
|
||||
}
|
||||
|
||||
let controller = T::Lookup::lookup(controller)?;
|
||||
|
||||
if <Ledger<T>>::contains_key(&controller) {
|
||||
Err(Error::<T>::AlreadyPaired)?
|
||||
return Err(Error::<T>::AlreadyPaired.into())
|
||||
}
|
||||
|
||||
// Reject a bond which is considered to be _dust_.
|
||||
if value < T::Currency::minimum_balance() {
|
||||
Err(Error::<T>::InsufficientBond)?
|
||||
return Err(Error::<T>::InsufficientBond.into())
|
||||
}
|
||||
|
||||
frame_system::Pallet::<T>::inc_consumers(&stash).map_err(|_| Error::<T>::BadState)?;
|
||||
@@ -862,7 +862,7 @@ pub mod pallet {
|
||||
debug_assert_eq!(T::VoterList::sanity_check(), Ok(()));
|
||||
}
|
||||
|
||||
Self::deposit_event(Event::<T>::Bonded(stash.clone(), extra));
|
||||
Self::deposit_event(Event::<T>::Bonded(stash, extra));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1183,7 +1183,7 @@ pub mod pallet {
|
||||
let old_controller = Self::bonded(&stash).ok_or(Error::<T>::NotStash)?;
|
||||
let controller = T::Lookup::lookup(controller)?;
|
||||
if <Ledger<T>>::contains_key(&controller) {
|
||||
Err(Error::<T>::AlreadyPaired)?
|
||||
return Err(Error::<T>::AlreadyPaired.into())
|
||||
}
|
||||
if controller != old_controller {
|
||||
<Bonded<T>>::insert(&stash, &controller);
|
||||
@@ -1466,8 +1466,8 @@ pub mod pallet {
|
||||
ensure_root(origin)?;
|
||||
if let Some(current_era) = Self::current_era() {
|
||||
HistoryDepth::<T>::mutate(|history_depth| {
|
||||
let last_kept = current_era.checked_sub(*history_depth).unwrap_or(0);
|
||||
let new_last_kept = current_era.checked_sub(new_history_depth).unwrap_or(0);
|
||||
let last_kept = current_era.saturating_sub(*history_depth);
|
||||
let new_last_kept = current_era.saturating_sub(new_history_depth);
|
||||
for era_index in last_kept..new_last_kept {
|
||||
Self::clear_era_information(era_index);
|
||||
}
|
||||
|
||||
@@ -389,7 +389,7 @@ fn slash_nominators<T: Config>(
|
||||
|
||||
let mut era_slash =
|
||||
<Pallet<T> as Store>::NominatorSlashInEra::get(¶ms.slash_era, stash)
|
||||
.unwrap_or_else(|| Zero::zero());
|
||||
.unwrap_or_else(Zero::zero);
|
||||
|
||||
era_slash += own_slash_difference;
|
||||
|
||||
@@ -646,7 +646,7 @@ pub(crate) fn apply_slash<T: Config>(
|
||||
|
||||
for &(ref nominator, nominator_slash) in &unapplied_slash.others {
|
||||
do_slash::<T>(
|
||||
&nominator,
|
||||
nominator,
|
||||
nominator_slash,
|
||||
&mut reward_payout,
|
||||
&mut slashed_imbalance,
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn create_stash_controller<T: Config>(
|
||||
amount,
|
||||
destination,
|
||||
)?;
|
||||
return Ok((stash, controller))
|
||||
Ok((stash, controller))
|
||||
}
|
||||
|
||||
/// Create a stash and controller pair with fixed balance.
|
||||
@@ -127,7 +127,7 @@ pub fn create_stash_and_dead_controller<T: Config>(
|
||||
amount,
|
||||
destination,
|
||||
)?;
|
||||
return Ok((stash, controller))
|
||||
Ok((stash, controller))
|
||||
}
|
||||
|
||||
/// create `max` validators.
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
const LOG_TARGET: &'static str = "runtime::state-trie-migration";
|
||||
const LOG_TARGET: &str = "runtime::state-trie-migration";
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! log {
|
||||
@@ -319,12 +319,12 @@ pub mod pallet {
|
||||
let (maybe_current_child, child_root) = match (&self.progress_child, &self.progress_top)
|
||||
{
|
||||
(Progress::LastKey(last_child), Progress::LastKey(last_top)) => {
|
||||
let child_root = Pallet::<T>::transform_child_key_or_halt(&last_top);
|
||||
let maybe_current_child = child_io::next_key(child_root, &last_child);
|
||||
let child_root = Pallet::<T>::transform_child_key_or_halt(last_top);
|
||||
let maybe_current_child = child_io::next_key(child_root, last_child);
|
||||
(maybe_current_child, child_root)
|
||||
},
|
||||
(Progress::ToStart, Progress::LastKey(last_top)) => {
|
||||
let child_root = Pallet::<T>::transform_child_key_or_halt(&last_top);
|
||||
let child_root = Pallet::<T>::transform_child_key_or_halt(last_top);
|
||||
// Start with the empty key as first key.
|
||||
(Some(Vec::new()), child_root)
|
||||
},
|
||||
@@ -336,7 +336,7 @@ pub mod pallet {
|
||||
};
|
||||
|
||||
if let Some(current_child) = maybe_current_child.as_ref() {
|
||||
let added_size = if let Some(data) = child_io::get(child_root, ¤t_child) {
|
||||
let added_size = if let Some(data) = child_io::get(child_root, current_child) {
|
||||
child_io::set(child_root, current_child, &data);
|
||||
data.len() as u32
|
||||
} else {
|
||||
@@ -369,8 +369,8 @@ pub mod pallet {
|
||||
};
|
||||
|
||||
if let Some(current_top) = maybe_current_top.as_ref() {
|
||||
let added_size = if let Some(data) = sp_io::storage::get(¤t_top) {
|
||||
sp_io::storage::set(¤t_top, &data);
|
||||
let added_size = if let Some(data) = sp_io::storage::get(current_top) {
|
||||
sp_io::storage::set(current_top, &data);
|
||||
data.len() as u32
|
||||
} else {
|
||||
Zero::zero()
|
||||
@@ -503,7 +503,7 @@ pub mod pallet {
|
||||
) -> DispatchResult {
|
||||
T::ControlOrigin::ensure_origin(origin)?;
|
||||
AutoLimits::<T>::put(maybe_config);
|
||||
Ok(().into())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Continue the migration for the given `limits`.
|
||||
@@ -616,7 +616,7 @@ pub mod pallet {
|
||||
|
||||
let mut dyn_size = 0u32;
|
||||
for key in &keys {
|
||||
if let Some(data) = sp_io::storage::get(&key) {
|
||||
if let Some(data) = sp_io::storage::get(key) {
|
||||
dyn_size = dyn_size.saturating_add(data.len() as u32);
|
||||
sp_io::storage::set(key, &data);
|
||||
}
|
||||
@@ -678,9 +678,9 @@ pub mod pallet {
|
||||
let mut dyn_size = 0u32;
|
||||
let transformed_child_key = Self::transform_child_key(&root).ok_or("bad child key")?;
|
||||
for child_key in &child_keys {
|
||||
if let Some(data) = child_io::get(transformed_child_key, &child_key) {
|
||||
if let Some(data) = child_io::get(transformed_child_key, child_key) {
|
||||
dyn_size = dyn_size.saturating_add(data.len() as u32);
|
||||
child_io::set(transformed_child_key, &child_key, &data);
|
||||
child_io::set(transformed_child_key, child_key, &data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -839,7 +839,7 @@ mod benchmarks {
|
||||
|
||||
// The size of the key seemingly makes no difference in the read/write time, so we make it
|
||||
// constant.
|
||||
const KEY: &'static [u8] = b"key";
|
||||
const KEY: &[u8] = b"key";
|
||||
|
||||
frame_benchmarking::benchmarks! {
|
||||
continue_migrate {
|
||||
|
||||
@@ -43,12 +43,8 @@ pub fn expand_outer_config(
|
||||
|
||||
types.extend(expand_config_types(runtime, decl, &config, part_is_generic));
|
||||
fields.extend(quote!(pub #field_name: #config,));
|
||||
build_storage_calls.extend(expand_config_build_storage_call(
|
||||
scrate,
|
||||
runtime,
|
||||
decl,
|
||||
&field_name,
|
||||
));
|
||||
build_storage_calls
|
||||
.extend(expand_config_build_storage_call(scrate, runtime, decl, field_name));
|
||||
query_genesis_config_part_macros.push(quote! {
|
||||
#path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name);
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
@@ -201,7 +201,7 @@ fn construct_runtime_intermediary_expansion(
|
||||
);
|
||||
}
|
||||
|
||||
Ok(expansion.into())
|
||||
Ok(expansion)
|
||||
}
|
||||
|
||||
/// All pallets have explicit definition of parts, this will expand to the runtime declaration.
|
||||
@@ -225,16 +225,16 @@ fn construct_runtime_final_expansion(
|
||||
})?;
|
||||
|
||||
let hidden_crate_name = "construct_runtime";
|
||||
let scrate = generate_crate_access(&hidden_crate_name, "frame-support");
|
||||
let scrate_decl = generate_hidden_includes(&hidden_crate_name, "frame-support");
|
||||
let scrate = generate_crate_access(hidden_crate_name, "frame-support");
|
||||
let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support");
|
||||
|
||||
let outer_event = expand::expand_outer_event(&name, &pallets, &scrate)?;
|
||||
|
||||
let outer_origin = expand::expand_outer_origin(&name, &system_pallet, &pallets, &scrate)?;
|
||||
let outer_origin = expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?;
|
||||
let all_pallets = decl_all_pallets(&name, pallets.iter());
|
||||
let pallet_to_index = decl_pallet_runtime_setup(&name, &pallets, &scrate);
|
||||
|
||||
let dispatch = expand::expand_outer_dispatch(&name, &system_pallet, &pallets, &scrate);
|
||||
let dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate);
|
||||
let metadata = expand::expand_runtime_metadata(&name, &pallets, &scrate, &unchecked_extrinsic);
|
||||
let outer_config = expand::expand_outer_config(&name, &pallets, &scrate);
|
||||
let inherent =
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream {
|
||||
.args
|
||||
.iter()
|
||||
.map(|(_, name, _)| {
|
||||
syn::Ident::new(&name.to_string().trim_start_matches('_'), name.span())
|
||||
syn::Ident::new(name.to_string().trim_start_matches('_'), name.span())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream {
|
||||
syn::Item::Enum(syn::ItemEnum { attrs, .. }) |
|
||||
syn::Item::Struct(syn::ItemStruct { attrs, .. }) |
|
||||
syn::Item::Type(syn::ItemType { attrs, .. }) => {
|
||||
if get_doc_literals(&attrs).is_empty() {
|
||||
if get_doc_literals(attrs).is_empty() {
|
||||
attrs.push(syn::parse_quote!(
|
||||
#[doc = r"
|
||||
Can be used to configure the
|
||||
|
||||
@@ -74,9 +74,7 @@ fn check_prefix_duplicates(
|
||||
),
|
||||
);
|
||||
|
||||
if let Some(other_dup_err) =
|
||||
used_prefixes.insert(counter_prefix.clone(), counter_dup_err.clone())
|
||||
{
|
||||
if let Some(other_dup_err) = used_prefixes.insert(counter_prefix, counter_dup_err.clone()) {
|
||||
let mut err = counter_dup_err;
|
||||
err.combine(other_dup_err);
|
||||
return Err(err)
|
||||
@@ -113,7 +111,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> {
|
||||
_ => unreachable!("Checked by def"),
|
||||
};
|
||||
|
||||
let prefix_ident = prefix_ident(&storage_def);
|
||||
let prefix_ident = prefix_ident(storage_def);
|
||||
let type_use_gen = if def.config.has_instance {
|
||||
quote::quote_spanned!(storage_def.attr_span => T, I)
|
||||
} else {
|
||||
@@ -215,7 +213,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> {
|
||||
/// * generate metadatas
|
||||
pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream {
|
||||
if let Err(e) = process_generics(def) {
|
||||
return e.into_compile_error().into()
|
||||
return e.into_compile_error()
|
||||
}
|
||||
|
||||
// Check for duplicate prefixes
|
||||
@@ -393,7 +391,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream {
|
||||
let prefix_structs = def.storages.iter().map(|storage_def| {
|
||||
let type_impl_gen = &def.type_impl_generics(storage_def.attr_span);
|
||||
let type_use_gen = &def.type_use_generics(storage_def.attr_span);
|
||||
let prefix_struct_ident = prefix_ident(&storage_def);
|
||||
let prefix_struct_ident = prefix_ident(storage_def);
|
||||
let prefix_struct_vis = &storage_def.vis;
|
||||
let prefix_struct_const = storage_def.prefix();
|
||||
let config_where_clause = &def.config.where_clause;
|
||||
|
||||
@@ -133,9 +133,10 @@ impl CallDef {
|
||||
return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl"))
|
||||
};
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?);
|
||||
instances.push(helper::check_pallet_struct_usage(&item.self_ty)?);
|
||||
let instances = vec![
|
||||
helper::check_impl_gen(&item.generics, item.impl_token.span())?,
|
||||
helper::check_pallet_struct_usage(&item.self_ty)?,
|
||||
];
|
||||
|
||||
if let Some((_, _, for_)) = item.trait_ {
|
||||
let msg = "Invalid pallet::call, expected no trait ident as in \
|
||||
|
||||
@@ -373,9 +373,10 @@ impl ConfigDef {
|
||||
let found = if item.supertraits.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
let mut found = item.supertraits.iter().fold(String::new(), |acc, s| {
|
||||
format!("{}`{}`, ", acc, quote::quote!(#s).to_string())
|
||||
});
|
||||
let mut found = item
|
||||
.supertraits
|
||||
.iter()
|
||||
.fold(String::new(), |acc, s| format!("{}`{}`, ", acc, quote::quote!(#s)));
|
||||
found.pop();
|
||||
found.pop();
|
||||
found
|
||||
|
||||
@@ -62,8 +62,8 @@ impl ErrorDef {
|
||||
return Err(syn::Error::new(item.span(), msg))
|
||||
}
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?);
|
||||
let instances =
|
||||
vec![helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?];
|
||||
|
||||
if item.generics.where_clause.is_some() {
|
||||
let msg = "Invalid pallet::error, where clause is not allowed on pallet error item";
|
||||
|
||||
@@ -87,9 +87,10 @@ impl ExtraConstantsDef {
|
||||
))
|
||||
};
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?);
|
||||
instances.push(helper::check_pallet_struct_usage(&item.self_ty)?);
|
||||
let instances = vec![
|
||||
helper::check_impl_gen(&item.generics, item.impl_token.span())?,
|
||||
helper::check_pallet_struct_usage(&item.self_ty)?,
|
||||
];
|
||||
|
||||
if let Some((_, _, for_)) = item.trait_ {
|
||||
let msg = "Invalid pallet::call, expected no trait ident as in \
|
||||
|
||||
@@ -53,8 +53,7 @@ impl GenesisBuildDef {
|
||||
})?
|
||||
.1;
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_genesis_builder_usage(&item_trait)?);
|
||||
let instances = vec![helper::check_genesis_builder_usage(item_trait)?];
|
||||
|
||||
Ok(Self { attr_span, index, instances, where_clause: item.generics.where_clause.clone() })
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ impl GenesisConfigDef {
|
||||
let mut instances = vec![];
|
||||
// NOTE: GenesisConfig is not allowed to be only generic on I because it is not supported
|
||||
// by construct_runtime.
|
||||
if let Some(u) = helper::check_type_def_optional_gen(&generics, ident.span())? {
|
||||
if let Some(u) = helper::check_type_def_optional_gen(generics, ident.span())? {
|
||||
instances.push(u);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,10 @@ impl HooksDef {
|
||||
return Err(syn::Error::new(item.span(), msg))
|
||||
};
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_pallet_struct_usage(&item.self_ty)?);
|
||||
instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?);
|
||||
let instances = vec![
|
||||
helper::check_pallet_struct_usage(&item.self_ty)?,
|
||||
helper::check_impl_gen(&item.generics, item.impl_token.span())?,
|
||||
];
|
||||
|
||||
let item_trait = &item
|
||||
.trait_
|
||||
|
||||
@@ -50,9 +50,10 @@ impl InherentDef {
|
||||
return Err(syn::Error::new(item.span(), msg))
|
||||
}
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_pallet_struct_usage(&item.self_ty)?);
|
||||
instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?);
|
||||
let instances = vec![
|
||||
helper::check_pallet_struct_usage(&item.self_ty)?,
|
||||
helper::check_impl_gen(&item.generics, item.impl_token.span())?,
|
||||
];
|
||||
|
||||
Ok(InherentDef { index, instances })
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ impl OriginDef {
|
||||
let is_generic = !generics.params.is_empty();
|
||||
|
||||
let mut instances = vec![];
|
||||
if let Some(u) = helper::check_type_def_optional_gen(&generics, item.span())? {
|
||||
if let Some(u) = helper::check_type_def_optional_gen(generics, item.span())? {
|
||||
instances.push(u);
|
||||
} else {
|
||||
// construct_runtime only allow generic event for instantiable pallet.
|
||||
|
||||
@@ -155,8 +155,8 @@ impl PalletStructDef {
|
||||
return Err(syn::Error::new(item.generics.where_clause.span(), msg))
|
||||
}
|
||||
|
||||
let mut instances = vec![];
|
||||
instances.push(helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?);
|
||||
let instances =
|
||||
vec![helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?];
|
||||
|
||||
Ok(Self {
|
||||
index,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user