style: Migrate to stable-only rustfmt configuration
- Remove nightly-only features from .rustfmt.toml and vendor/ss58-registry/rustfmt.toml - Removed features: imports_granularity, wrap_comments, comment_width, reorder_impl_items, spaces_around_ranges, binop_separator, match_arm_blocks, trailing_semicolon, trailing_comma - Format all 898 affected files with stable rustfmt - Ensures long-term reliability without nightly toolchain dependency
This commit is contained in:
@@ -108,8 +108,8 @@ pub(crate) mod v1_to_v2 {
|
||||
.len()
|
||||
.saturating_add(fellows_vec.len())
|
||||
.saturating_add(allies.len())
|
||||
.saturating_add(retiring.len()) ==
|
||||
0
|
||||
.saturating_add(retiring.len())
|
||||
== 0
|
||||
{
|
||||
return T::DbWeight::get().reads(4);
|
||||
}
|
||||
|
||||
@@ -82,10 +82,10 @@ fn mint_setup_fee_asset<T: Config>(
|
||||
assert_ok!(T::Assets::mint_into(
|
||||
T::PoolSetupFeeAsset::get(),
|
||||
&caller,
|
||||
T::PoolSetupFee::get() +
|
||||
T::Assets::deposit_required(asset1.clone()) +
|
||||
T::Assets::deposit_required(asset2.clone()) +
|
||||
T::PoolAssets::deposit_required(lp_token.clone())
|
||||
T::PoolSetupFee::get()
|
||||
+ T::Assets::deposit_required(asset1.clone())
|
||||
+ T::Assets::deposit_required(asset2.clone())
|
||||
+ T::PoolAssets::deposit_required(lp_token.clone())
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -208,8 +208,8 @@ pub mod pezpallet {
|
||||
// Transfer all pool related assets to the new account.
|
||||
|
||||
ensure!(
|
||||
balance1 ==
|
||||
T::Assets::transfer(
|
||||
balance1
|
||||
== T::Assets::transfer(
|
||||
asset1.clone(),
|
||||
&prior_account,
|
||||
&new_account,
|
||||
@@ -220,8 +220,8 @@ pub mod pezpallet {
|
||||
);
|
||||
|
||||
ensure!(
|
||||
balance2 ==
|
||||
T::Assets::transfer(
|
||||
balance2
|
||||
== T::Assets::transfer(
|
||||
asset2.clone(),
|
||||
&prior_account,
|
||||
&new_account,
|
||||
@@ -232,8 +232,8 @@ pub mod pezpallet {
|
||||
);
|
||||
|
||||
ensure!(
|
||||
lp_balance ==
|
||||
T::PoolAssets::transfer(
|
||||
lp_balance
|
||||
== T::PoolAssets::transfer(
|
||||
info.lp_token.clone(),
|
||||
&prior_account,
|
||||
&new_account,
|
||||
|
||||
@@ -127,10 +127,10 @@ fn mint_setup_fee_asset<T: Config>(
|
||||
assert_ok!(T::Assets::mint_into(
|
||||
T::PoolSetupFeeAsset::get(),
|
||||
&caller,
|
||||
T::PoolSetupFee::get() +
|
||||
T::Assets::deposit_required(asset1.clone()) +
|
||||
T::Assets::deposit_required(asset2.clone()) +
|
||||
T::PoolAssets::deposit_required(lp_token.clone())
|
||||
T::PoolSetupFee::get()
|
||||
+ T::Assets::deposit_required(asset1.clone())
|
||||
+ T::Assets::deposit_required(asset2.clone())
|
||||
+ T::PoolAssets::deposit_required(lp_token.clone())
|
||||
));
|
||||
}
|
||||
|
||||
@@ -387,18 +387,18 @@ mod benchmarks {
|
||||
Box::new(asset2.clone())
|
||||
));
|
||||
|
||||
if n > 0 &&
|
||||
<T as Config>::Assets::deposit_held(asset1.clone(), pool_account.clone()).is_some()
|
||||
if n > 0
|
||||
&& <T as Config>::Assets::deposit_held(asset1.clone(), pool_account.clone()).is_some()
|
||||
{
|
||||
let _ = <T as Config>::Assets::refund(asset1.clone(), pool_account.clone());
|
||||
}
|
||||
if n > 1 &&
|
||||
<T as Config>::Assets::deposit_held(asset2.clone(), pool_account.clone()).is_some()
|
||||
if n > 1
|
||||
&& <T as Config>::Assets::deposit_held(asset2.clone(), pool_account.clone()).is_some()
|
||||
{
|
||||
let _ = <T as Config>::Assets::refund(asset2.clone(), pool_account.clone());
|
||||
}
|
||||
if n > 2 &&
|
||||
<T as Config>::PoolAssets::deposit_held(lp_token.clone(), pool_account.clone())
|
||||
if n > 2
|
||||
&& <T as Config>::PoolAssets::deposit_held(lp_token.clone(), pool_account.clone())
|
||||
.is_some()
|
||||
{
|
||||
let _ = <T as Config>::PoolAssets::refund(lp_token, pool_account);
|
||||
|
||||
@@ -1392,12 +1392,12 @@ fn can_swap_tokens_for_exact_tokens_when_not_liquidity_provider() {
|
||||
assert_ok!(Assets::mint(RuntimeOrigin::signed(user2), 2, user2, base2));
|
||||
|
||||
let pezpallet_account = <Test as Config>::PoolLocator::address(&pool_id).unwrap();
|
||||
let before1 = balance(pezpallet_account, token_1.clone()) +
|
||||
balance(user, token_1.clone()) +
|
||||
balance(user2, token_1.clone());
|
||||
let before2 = balance(pezpallet_account, token_2.clone()) +
|
||||
balance(user, token_2.clone()) +
|
||||
balance(user2, token_2.clone());
|
||||
let before1 = balance(pezpallet_account, token_1.clone())
|
||||
+ balance(user, token_1.clone())
|
||||
+ balance(user2, token_1.clone());
|
||||
let before2 = balance(pezpallet_account, token_2.clone())
|
||||
+ balance(user, token_2.clone())
|
||||
+ balance(user2, token_2.clone());
|
||||
|
||||
let liquidity1 = 10000;
|
||||
let liquidity2 = 200;
|
||||
@@ -1440,15 +1440,15 @@ fn can_swap_tokens_for_exact_tokens_when_not_liquidity_provider() {
|
||||
// native and asset totals should be preserved.
|
||||
assert_eq!(
|
||||
before1,
|
||||
balance(pezpallet_account, token_1.clone()) +
|
||||
balance(user, token_1.clone()) +
|
||||
balance(user2, token_1.clone())
|
||||
balance(pezpallet_account, token_1.clone())
|
||||
+ balance(user, token_1.clone())
|
||||
+ balance(user2, token_1.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
before2,
|
||||
balance(pezpallet_account, token_2.clone()) +
|
||||
balance(user, token_2.clone()) +
|
||||
balance(user2, token_2.clone())
|
||||
balance(pezpallet_account, token_2.clone())
|
||||
+ balance(user, token_2.clone())
|
||||
+ balance(user2, token_2.clone())
|
||||
);
|
||||
|
||||
let lp_token_minted = pool_balance(user2, lp_token);
|
||||
|
||||
@@ -258,8 +258,8 @@ mod benchmarks {
|
||||
}
|
||||
|
||||
let new_reward_rate_per_block =
|
||||
T::Assets::minimum_balance(T::BenchmarkHelper::reward_asset()).max(T::Balance::one()) +
|
||||
T::Balance::one();
|
||||
T::Assets::minimum_balance(T::BenchmarkHelper::reward_asset()).max(T::Balance::one())
|
||||
+ T::Balance::one();
|
||||
|
||||
#[extrinsic_call]
|
||||
_(caller_origin as T::RuntimeOrigin, 0, new_reward_rate_per_block);
|
||||
@@ -296,8 +296,8 @@ mod benchmarks {
|
||||
}
|
||||
|
||||
let new_expiry_block = pool_expire::<T>()
|
||||
.evaluate(T::BlockNumberProvider::current_block_number()) +
|
||||
BlockNumberFor::<T>::one();
|
||||
.evaluate(T::BlockNumberProvider::current_block_number())
|
||||
+ BlockNumberFor::<T>::one();
|
||||
|
||||
#[extrinsic_call]
|
||||
_(create_origin as T::RuntimeOrigin, 0, DispatchTime::At(new_expiry_block));
|
||||
|
||||
@@ -110,7 +110,9 @@ where
|
||||
match input {
|
||||
IERC20Calls::transfer(_) | IERC20Calls::approve(_) | IERC20Calls::transferFrom(_)
|
||||
if env.is_read_only() =>
|
||||
Err(Error::Error(pezpallet_revive::Error::<Self::T>::StateChangeDenied.into())),
|
||||
{
|
||||
Err(Error::Error(pezpallet_revive::Error::<Self::T>::StateChangeDenied.into()))
|
||||
},
|
||||
|
||||
IERC20Calls::transfer(call) => Self::transfer(asset_id, call, env),
|
||||
IERC20Calls::totalSupply(_) => Self::total_supply(asset_id, env),
|
||||
|
||||
@@ -160,8 +160,8 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
if amount < details.min_balance {
|
||||
return DepositConsequence::BelowMinimum;
|
||||
}
|
||||
if !details.is_sufficient &&
|
||||
!pezframe_system::Pezpallet::<T>::can_accrue_consumers(who, 2)
|
||||
if !details.is_sufficient
|
||||
&& !pezframe_system::Pezpallet::<T>::can_accrue_consumers(who, 2)
|
||||
{
|
||||
return DepositConsequence::CannotCreate;
|
||||
}
|
||||
@@ -209,7 +209,7 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
T::Holder::balance_on_hold(id.clone(), who),
|
||||
T::Freezer::frozen_balance(id.clone(), who),
|
||||
) {
|
||||
(None, None) =>
|
||||
(None, None) => {
|
||||
if rest < details.min_balance {
|
||||
if keep_alive {
|
||||
WouldDie
|
||||
@@ -218,7 +218,8 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
}
|
||||
} else {
|
||||
Success
|
||||
},
|
||||
}
|
||||
},
|
||||
(maybe_held, maybe_frozen) => {
|
||||
let frozen = maybe_frozen.unwrap_or_default();
|
||||
let held = maybe_held.unwrap_or_default();
|
||||
|
||||
@@ -251,8 +251,8 @@ fn can_estimate_current_epoch_progress() {
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
Babe::estimate_current_session_progress(i).0.unwrap() <
|
||||
Permill::from_percent(100)
|
||||
Babe::estimate_current_session_progress(i).0.unwrap()
|
||||
< Permill::from_percent(100)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,15 +267,14 @@ impl<T: Config<I>, I: 'static> List<T, I> {
|
||||
// easier; they can just configure `type BagThresholds = ()`.
|
||||
let thresholds = T::BagThresholds::get();
|
||||
let iter = thresholds.iter().copied();
|
||||
let iter: Box<dyn Iterator<Item = T::Score>> = if thresholds.last() ==
|
||||
Some(&T::Score::max_value())
|
||||
{
|
||||
// in the event that they included it, we can just pass the iterator through unchanged.
|
||||
Box::new(iter.rev())
|
||||
} else {
|
||||
// otherwise, insert it here.
|
||||
Box::new(iter.chain(iter::once(T::Score::max_value())).rev())
|
||||
};
|
||||
let iter: Box<dyn Iterator<Item = T::Score>> =
|
||||
if thresholds.last() == Some(&T::Score::max_value()) {
|
||||
// in the event that they included it, we can just pass the iterator through unchanged.
|
||||
Box::new(iter.rev())
|
||||
} else {
|
||||
// otherwise, insert it here.
|
||||
Box::new(iter.chain(iter::once(T::Score::max_value())).rev())
|
||||
};
|
||||
|
||||
iter.filter_map(Bag::get).flat_map(|bag| bag.iter())
|
||||
}
|
||||
@@ -615,15 +614,14 @@ impl<T: Config<I>, I: 'static> List<T, I> {
|
||||
|
||||
let thresholds = T::BagThresholds::get();
|
||||
let iter = thresholds.iter().copied();
|
||||
let iter: Box<dyn Iterator<Item = T::Score>> = if thresholds.last() ==
|
||||
Some(&T::Score::max_value())
|
||||
{
|
||||
// in the event that they included it, we can just pass the iterator through unchanged.
|
||||
Box::new(iter)
|
||||
} else {
|
||||
// otherwise, insert it here.
|
||||
Box::new(iter.chain(core::iter::once(T::Score::max_value())))
|
||||
};
|
||||
let iter: Box<dyn Iterator<Item = T::Score>> =
|
||||
if thresholds.last() == Some(&T::Score::max_value()) {
|
||||
// in the event that they included it, we can just pass the iterator through unchanged.
|
||||
Box::new(iter)
|
||||
} else {
|
||||
// otherwise, insert it here.
|
||||
Box::new(iter.chain(core::iter::once(T::Score::max_value())))
|
||||
};
|
||||
|
||||
iter.filter_map(|t| {
|
||||
Bag::<T, I>::get(t)
|
||||
@@ -960,9 +958,9 @@ impl<T: Config<I>, I: 'static> Node<T, I> {
|
||||
let expected_bag = Bag::<T, I>::get(self.bag_upper).ok_or("bag not found for node")?;
|
||||
let id = self.id();
|
||||
|
||||
let non_terminal_check = !self.is_terminal() &&
|
||||
expected_bag.head.as_ref() != Some(id) &&
|
||||
expected_bag.tail.as_ref() != Some(id);
|
||||
let non_terminal_check = !self.is_terminal()
|
||||
&& expected_bag.head.as_ref() != Some(id)
|
||||
&& expected_bag.tail.as_ref() != Some(id);
|
||||
let terminal_check =
|
||||
expected_bag.head.as_ref() == Some(id) || expected_bag.tail.as_ref() == Some(id);
|
||||
pezframe_support::ensure!(
|
||||
|
||||
@@ -835,8 +835,9 @@ where
|
||||
if slashed == beneficiary {
|
||||
return match status {
|
||||
Status::Free => Ok(Self::unreserve_named(id, slashed, value)),
|
||||
Status::Reserved =>
|
||||
Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))),
|
||||
Status::Reserved => {
|
||||
Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed)))
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1295,16 +1295,18 @@ pub mod pezpallet {
|
||||
ensure!(!is_new, Error::<T, I>::DeadAccount);
|
||||
Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult {
|
||||
match status {
|
||||
Status::Free =>
|
||||
Status::Free => {
|
||||
to_account.free = to_account
|
||||
.free
|
||||
.checked_add(&actual)
|
||||
.ok_or(ArithmeticError::Overflow)?,
|
||||
Status::Reserved =>
|
||||
.ok_or(ArithmeticError::Overflow)?
|
||||
},
|
||||
Status::Reserved => {
|
||||
to_account.reserved = to_account
|
||||
.reserved
|
||||
.checked_add(&actual)
|
||||
.ok_or(ArithmeticError::Overflow)?,
|
||||
.ok_or(ArithmeticError::Overflow)?
|
||||
},
|
||||
}
|
||||
from_account.reserved.saturating_reduce(actual);
|
||||
Ok(())
|
||||
@@ -1377,8 +1379,8 @@ pub mod pezpallet {
|
||||
|
||||
fn hold_and_freeze_count() -> Result<(), pezsp_runtime::TryRuntimeError> {
|
||||
Holds::<T, I>::iter_keys().try_for_each(|k| {
|
||||
if Holds::<T, I>::decode_len(k).unwrap_or(0) >
|
||||
T::RuntimeHoldReason::VARIANT_COUNT as usize
|
||||
if Holds::<T, I>::decode_len(k).unwrap_or(0)
|
||||
> T::RuntimeHoldReason::VARIANT_COUNT as usize
|
||||
{
|
||||
Err("Found `Hold` with too many elements")
|
||||
} else {
|
||||
|
||||
@@ -155,36 +155,45 @@ impl<T: Config> EquivocationEvidenceFor<T> {
|
||||
/// Returns the authority id of the equivocator.
|
||||
fn offender_id(&self) -> &T::BeefyId {
|
||||
match self {
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) =>
|
||||
equivocation_proof.offender_id(),
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) =>
|
||||
&equivocation_proof.vote.id,
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) =>
|
||||
&equivocation_proof.vote.id,
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => {
|
||||
equivocation_proof.offender_id()
|
||||
},
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => {
|
||||
&equivocation_proof.vote.id
|
||||
},
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => {
|
||||
&equivocation_proof.vote.id
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the round number at which the equivocation occurred.
|
||||
fn round_number(&self) -> &BlockNumberFor<T> {
|
||||
match self {
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) =>
|
||||
equivocation_proof.round_number(),
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) =>
|
||||
&equivocation_proof.vote.commitment.block_number,
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) =>
|
||||
&equivocation_proof.vote.commitment.block_number,
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => {
|
||||
equivocation_proof.round_number()
|
||||
},
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => {
|
||||
&equivocation_proof.vote.commitment.block_number
|
||||
},
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => {
|
||||
&equivocation_proof.vote.commitment.block_number
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the set id at which the equivocation occurred.
|
||||
fn set_id(&self) -> ValidatorSetId {
|
||||
match self {
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) =>
|
||||
equivocation_proof.set_id(),
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) =>
|
||||
equivocation_proof.vote.commitment.validator_set_id,
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) =>
|
||||
equivocation_proof.vote.commitment.validator_set_id,
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => {
|
||||
equivocation_proof.set_id()
|
||||
},
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => {
|
||||
equivocation_proof.vote.commitment.validator_set_id
|
||||
},
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => {
|
||||
equivocation_proof.vote.commitment.validator_set_id
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,8 +282,8 @@ impl<T: Config> EquivocationEvidenceFor<T> {
|
||||
fn slash_fraction(&self) -> Option<Perbill> {
|
||||
match self {
|
||||
EquivocationEvidenceFor::DoubleVotingProof(_, _) => None,
|
||||
EquivocationEvidenceFor::ForkVotingProof(_, _) |
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(_, _) => Some(Perbill::from_percent(50)),
|
||||
EquivocationEvidenceFor::ForkVotingProof(_, _)
|
||||
| EquivocationEvidenceFor::FutureBlockVotingProof(_, _) => Some(Perbill::from_percent(50)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,16 +439,18 @@ pub mod pezpallet {
|
||||
impl<T: Config> Call<T> {
|
||||
pub fn to_equivocation_evidence_for(&self) -> Option<EquivocationEvidenceFor<T>> {
|
||||
match self {
|
||||
Call::report_double_voting_unsigned { equivocation_proof, key_owner_proof } =>
|
||||
Call::report_double_voting_unsigned { equivocation_proof, key_owner_proof } => {
|
||||
Some(EquivocationEvidenceFor::<T>::DoubleVotingProof(
|
||||
*equivocation_proof.clone(),
|
||||
key_owner_proof.clone(),
|
||||
)),
|
||||
Call::report_fork_voting_unsigned { equivocation_proof, key_owner_proof } =>
|
||||
))
|
||||
},
|
||||
Call::report_fork_voting_unsigned { equivocation_proof, key_owner_proof } => {
|
||||
Some(EquivocationEvidenceFor::<T>::ForkVotingProof(
|
||||
*equivocation_proof.clone(),
|
||||
key_owner_proof.clone(),
|
||||
)),
|
||||
))
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -457,16 +459,18 @@ pub mod pezpallet {
|
||||
impl<T: Config> From<EquivocationEvidenceFor<T>> for Call<T> {
|
||||
fn from(evidence: EquivocationEvidenceFor<T>) -> Self {
|
||||
match evidence {
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, key_owner_proof) =>
|
||||
EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, key_owner_proof) => {
|
||||
Call::report_double_voting_unsigned {
|
||||
equivocation_proof: Box::new(equivocation_proof),
|
||||
key_owner_proof,
|
||||
},
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, key_owner_proof) =>
|
||||
}
|
||||
},
|
||||
EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, key_owner_proof) => {
|
||||
Call::report_fork_voting_unsigned {
|
||||
equivocation_proof: Box::new(equivocation_proof),
|
||||
key_owner_proof,
|
||||
},
|
||||
}
|
||||
},
|
||||
EquivocationEvidenceFor::FutureBlockVotingProof(
|
||||
equivocation_proof,
|
||||
key_owner_proof,
|
||||
|
||||
@@ -923,7 +923,7 @@ macro_rules! impl_bench_name_tests {
|
||||
// Every variant must implement [`BenchmarkingSetup`].
|
||||
//
|
||||
// ```nocompile
|
||||
//
|
||||
//
|
||||
// struct Transfer;
|
||||
// impl BenchmarkingSetup for Transfer { ... }
|
||||
//
|
||||
|
||||
@@ -66,8 +66,8 @@ fn setup_bounty<T: Config<I>, I: 'static>(
|
||||
let caller = account("caller", u, SEED);
|
||||
let value: BalanceOf<T, I> = T::BountyValueMinimum::get().saturating_mul(100u32.into());
|
||||
let fee = value / 2u32.into();
|
||||
let deposit = T::BountyDepositBase::get() +
|
||||
T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into();
|
||||
let deposit = T::BountyDepositBase::get()
|
||||
+ T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into();
|
||||
let _ = T::Currency::make_free_balance_be(&caller, deposit + minimum_balance::<T, I>());
|
||||
let curator = account("curator", u, SEED);
|
||||
let _ =
|
||||
|
||||
@@ -270,8 +270,8 @@ mod benches {
|
||||
_(origin as T::RuntimeOrigin, initial_price, extra_cores.try_into().unwrap());
|
||||
|
||||
assert!(SaleInfo::<T>::get().is_some());
|
||||
let sale_start = RCBlockNumberProviderOf::<T::Coretime>::current_block_number() +
|
||||
config.interlude_length;
|
||||
let sale_start = RCBlockNumberProviderOf::<T::Coretime>::current_block_number()
|
||||
+ config.interlude_length;
|
||||
assert_last_event::<T>(
|
||||
Event::SaleInitialized {
|
||||
sale_start,
|
||||
|
||||
@@ -109,9 +109,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
let config = Configuration::<T>::get().ok_or(Error::<T>::Uninitialized)?;
|
||||
|
||||
// Determine the core count
|
||||
let core_count = Leases::<T>::decode_len().unwrap_or(0) as CoreIndex +
|
||||
Reservations::<T>::decode_len().unwrap_or(0) as CoreIndex +
|
||||
extra_cores;
|
||||
let core_count = Leases::<T>::decode_len().unwrap_or(0) as CoreIndex
|
||||
+ Reservations::<T>::decode_len().unwrap_or(0) as CoreIndex
|
||||
+ extra_cores;
|
||||
|
||||
Self::do_request_core_count(core_count)?;
|
||||
|
||||
@@ -352,7 +352,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
let assigned = match PotentialRenewals::<T>::get(renewal_id) {
|
||||
Some(PotentialRenewalRecord { completion: Partial(w), price: p })
|
||||
if price == p =>
|
||||
w,
|
||||
{
|
||||
w
|
||||
},
|
||||
_ => CoreMask::void(),
|
||||
} | region_id.mask;
|
||||
let workload =
|
||||
|
||||
@@ -66,8 +66,8 @@ fn setup_bounty<T: Config>(
|
||||
let caller = account("caller", user, SEED);
|
||||
let value: BalanceOf<T> = T::BountyValueMinimum::get().saturating_mul(100u32.into());
|
||||
let fee = value / 2u32.into();
|
||||
let deposit = T::BountyDepositBase::get() +
|
||||
T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into();
|
||||
let deposit = T::BountyDepositBase::get()
|
||||
+ T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into();
|
||||
let _ = T::Currency::make_free_balance_be(&caller, deposit + T::Currency::minimum_balance());
|
||||
let curator = account("curator", user, SEED);
|
||||
let _ = T::Currency::make_free_balance_be(
|
||||
|
||||
@@ -288,8 +288,8 @@ pub mod pezpallet {
|
||||
description.try_into().map_err(|_| BountiesError::<T>::ReasonTooBig)?;
|
||||
ensure!(value >= T::ChildBountyValueMinimum::get(), BountiesError::<T>::InvalidValue);
|
||||
ensure!(
|
||||
ParentChildBounties::<T>::get(parent_bounty_id) <=
|
||||
T::MaxActiveChildBountyCount::get() as u32,
|
||||
ParentChildBounties::<T>::get(parent_bounty_id)
|
||||
<= T::MaxActiveChildBountyCount::get() as u32,
|
||||
Error::<T>::TooManyChildBounties,
|
||||
);
|
||||
|
||||
@@ -536,8 +536,8 @@ pub mod pezpallet {
|
||||
// child-bounty curator can unassign the child-bounty curator.
|
||||
ensure!(
|
||||
maybe_sender.map_or(true, |sender| {
|
||||
sender == *curator ||
|
||||
Self::ensure_bounty_active(parent_bounty_id)
|
||||
sender == *curator
|
||||
|| Self::ensure_bounty_active(parent_bounty_id)
|
||||
.map_or(false, |(parent_curator, _)| {
|
||||
sender == parent_curator
|
||||
})
|
||||
@@ -566,8 +566,8 @@ pub mod pezpallet {
|
||||
Some(sender) => {
|
||||
let (parent_curator, update_due) =
|
||||
Self::ensure_bounty_active(parent_bounty_id)?;
|
||||
if sender == parent_curator ||
|
||||
update_due < Self::treasury_block_number()
|
||||
if sender == parent_curator
|
||||
|| update_due < Self::treasury_block_number()
|
||||
{
|
||||
// Slash the child-bounty curator if
|
||||
// + the call is made by the parent bounty curator.
|
||||
@@ -646,8 +646,8 @@ pub mod pezpallet {
|
||||
child_bounty.status = ChildBountyStatus::PendingPayout {
|
||||
curator: signer,
|
||||
beneficiary: beneficiary.clone(),
|
||||
unlock_at: Self::treasury_block_number() +
|
||||
T::BountyDepositPayoutDelay::get(),
|
||||
unlock_at: Self::treasury_block_number()
|
||||
+ T::BountyDepositPayoutDelay::get(),
|
||||
};
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -224,8 +224,8 @@ fn post_process_wasm(input_path: &Path, output_path: &Path) -> Result<()> {
|
||||
deserialize_file(input_path).with_context(|| format!("Failed to read {:?}", input_path))?;
|
||||
if let Some(section) = module.export_section_mut() {
|
||||
section.entries_mut().retain(|entry| {
|
||||
matches!(entry.internal(), Internal::Function(_)) &&
|
||||
(entry.field() == "call" || entry.field() == "deploy")
|
||||
matches!(entry.internal(), Internal::Function(_))
|
||||
&& (entry.field() == "call" || entry.field() == "deploy")
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -114,8 +114,9 @@ pub mod pezpallet {
|
||||
max_weight,
|
||||
Weight::zero(),
|
||||
) {
|
||||
Outcome::Error(InstructionError { error, .. }) =>
|
||||
(Err(error), Event::Fail(Some(hash), error)),
|
||||
Outcome::Error(InstructionError { error, .. }) => {
|
||||
(Err(error), Event::Fail(Some(hash), error))
|
||||
},
|
||||
Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))),
|
||||
// As far as the caller is concerned, this was dispatched without error, so
|
||||
// we just report the weight used.
|
||||
|
||||
@@ -177,8 +177,8 @@ pub fn estimate_weight(number_of_instructions: u64) -> Weight {
|
||||
pub fn estimate_fee_for_weight(weight: Weight) -> u128 {
|
||||
let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get();
|
||||
|
||||
units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) +
|
||||
units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)
|
||||
units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128)
|
||||
+ units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)
|
||||
}
|
||||
|
||||
pub type LocalBalancesTransactor =
|
||||
|
||||
@@ -391,7 +391,8 @@ impl EnvDef {
|
||||
|
||||
fn is_valid_special_arg(idx: usize, arg: &FnArg) -> bool {
|
||||
let FnArg::Typed(pat) = arg else { return false };
|
||||
let ident = if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false };
|
||||
let ident =
|
||||
if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false };
|
||||
let name_ok = match idx {
|
||||
0 => ident == "ctx" || ident == "_ctx",
|
||||
1 => ident == "memory" || ident == "_memory",
|
||||
|
||||
@@ -568,10 +568,10 @@ mod benchmarks {
|
||||
// value and value transferred via call should be removed from the caller
|
||||
assert_eq!(
|
||||
T::Currency::balance(&instance.caller),
|
||||
caller_funding::<T>() -
|
||||
instance.value -
|
||||
value - deposit -
|
||||
Pezpallet::<T>::min_balance(),
|
||||
caller_funding::<T>()
|
||||
- instance.value
|
||||
- value - deposit
|
||||
- Pezpallet::<T>::min_balance(),
|
||||
);
|
||||
// contract should have received the value
|
||||
assert_eq!(T::Currency::balance(&instance.account_id), before + value);
|
||||
|
||||
@@ -884,9 +884,9 @@ where
|
||||
|
||||
// `Relaxed` will only be ever set in case of off-chain execution.
|
||||
// Instantiations are never allowed even when executing off-chain.
|
||||
if !(executable.is_deterministic() ||
|
||||
(matches!(determinism, Determinism::Relaxed) &&
|
||||
matches!(entry_point, ExportedFunction::Call)))
|
||||
if !(executable.is_deterministic()
|
||||
|| (matches!(determinism, Determinism::Relaxed)
|
||||
&& matches!(entry_point, ExportedFunction::Call)))
|
||||
{
|
||||
return Err(Error::<T>::Indeterministic.into());
|
||||
}
|
||||
@@ -1064,8 +1064,9 @@ where
|
||||
with_transaction(|| -> TransactionOutcome<Result<_, DispatchError>> {
|
||||
let output = do_transaction();
|
||||
match &output {
|
||||
Ok(result) if !result.did_revert() =>
|
||||
TransactionOutcome::Commit(Ok((true, output))),
|
||||
Ok(result) if !result.did_revert() => {
|
||||
TransactionOutcome::Commit(Ok((true, output)))
|
||||
},
|
||||
_ => TransactionOutcome::Rollback(Ok((false, output))),
|
||||
}
|
||||
});
|
||||
|
||||
@@ -694,8 +694,8 @@ pub mod pezpallet {
|
||||
|
||||
// We can use storage to store items using the available block ref_time with the
|
||||
// `set_storage` host function.
|
||||
let max_storage_size: u32 = ((max_block_ref_time /
|
||||
(<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::SetStorage {
|
||||
let max_storage_size: u32 = ((max_block_ref_time
|
||||
/ (<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::SetStorage {
|
||||
new_bytes: max_payload_size,
|
||||
old_bytes: 0,
|
||||
})
|
||||
@@ -717,8 +717,8 @@ pub mod pezpallet {
|
||||
// We can use storage to store events using the available block ref_time with the
|
||||
// `deposit_event` host function. The overhead of stored events, which is around 100B,
|
||||
// is not taken into account to simplify calculations, as it does not change much.
|
||||
let max_events_size: u32 = ((max_block_ref_time /
|
||||
(<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::DepositEvent {
|
||||
let max_events_size: u32 = ((max_block_ref_time
|
||||
/ (<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::DepositEvent {
|
||||
num_topic: 0,
|
||||
len: max_payload_size,
|
||||
})
|
||||
@@ -1570,12 +1570,13 @@ impl<T: Config> Invokable<T> for CallInput<T> {
|
||||
let mut storage_meter =
|
||||
match StorageMeter::new(&origin, common.storage_deposit_limit, common.value) {
|
||||
Ok(meter) => meter,
|
||||
Err(err) =>
|
||||
Err(err) => {
|
||||
return InternalOutput {
|
||||
result: Err(err.into()),
|
||||
gas_meter,
|
||||
storage_deposit: Default::default(),
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
let schedule = T::Schedule::get();
|
||||
let result = ExecStack::<T, WasmBlob<T>>::run_call(
|
||||
@@ -1780,7 +1781,7 @@ impl<T: Config> Pezpallet<T> {
|
||||
|
||||
let (module, deposit) = match result {
|
||||
Ok(result) => result,
|
||||
Err(error) =>
|
||||
Err(error) => {
|
||||
return ContractResult {
|
||||
gas_consumed: Zero::zero(),
|
||||
gas_required: Zero::zero(),
|
||||
@@ -1788,7 +1789,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
debug_message: debug_message.unwrap_or(Default::default()).into(),
|
||||
result: Err(error),
|
||||
events: events(),
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
storage_deposit_limit =
|
||||
|
||||
@@ -308,8 +308,8 @@ where
|
||||
&contract.deposit_account,
|
||||
);
|
||||
ensure!(
|
||||
deposit ==
|
||||
contract
|
||||
deposit
|
||||
== contract
|
||||
.storage_base_deposit
|
||||
.saturating_add(contract.storage_item_deposit)
|
||||
.saturating_add(contract.storage_byte_deposit),
|
||||
|
||||
@@ -249,8 +249,8 @@ where
|
||||
old_balance_allocation.total
|
||||
);
|
||||
ensure!(
|
||||
T::Currency::total_balance(&owner) ==
|
||||
BalanceOf::<T>::decode(&mut &old_balance_allocation.total.encode()[..])
|
||||
T::Currency::total_balance(&owner)
|
||||
== BalanceOf::<T>::decode(&mut &old_balance_allocation.total.encode()[..])
|
||||
.unwrap(),
|
||||
"Balance mismatch "
|
||||
);
|
||||
|
||||
@@ -315,18 +315,18 @@ impl<T: Config> MigrationStep for Migration<T> {
|
||||
"code_hash mismatch"
|
||||
);
|
||||
ensure!(
|
||||
migration_contract_info.storage_byte_deposit ==
|
||||
crate_contract_info.storage_byte_deposit,
|
||||
migration_contract_info.storage_byte_deposit
|
||||
== crate_contract_info.storage_byte_deposit,
|
||||
"storage_byte_deposit mismatch"
|
||||
);
|
||||
ensure!(
|
||||
migration_contract_info.storage_base_deposit ==
|
||||
crate_contract_info.storage_base_deposit(),
|
||||
migration_contract_info.storage_base_deposit
|
||||
== crate_contract_info.storage_base_deposit(),
|
||||
"storage_base_deposit mismatch"
|
||||
);
|
||||
ensure!(
|
||||
&migration_contract_info.delegate_dependencies ==
|
||||
crate_contract_info.delegate_dependencies(),
|
||||
&migration_contract_info.delegate_dependencies
|
||||
== crate_contract_info.delegate_dependencies(),
|
||||
"delegate_dependencies mismatch"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -200,18 +200,20 @@ where
|
||||
match (self, rhs) {
|
||||
(Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)),
|
||||
(Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)),
|
||||
(Charge(lhs), Refund(rhs)) =>
|
||||
(Charge(lhs), Refund(rhs)) => {
|
||||
if lhs >= rhs {
|
||||
Charge(lhs.saturating_sub(*rhs))
|
||||
} else {
|
||||
Refund(rhs.saturating_sub(*lhs))
|
||||
},
|
||||
(Refund(lhs), Charge(rhs)) =>
|
||||
}
|
||||
},
|
||||
(Refund(lhs), Charge(rhs)) => {
|
||||
if lhs > rhs {
|
||||
Refund(lhs.saturating_sub(*rhs))
|
||||
} else {
|
||||
Charge(rhs.saturating_sub(*lhs))
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,18 +223,20 @@ where
|
||||
match (self, rhs) {
|
||||
(Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)),
|
||||
(Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)),
|
||||
(Charge(lhs), Charge(rhs)) =>
|
||||
(Charge(lhs), Charge(rhs)) => {
|
||||
if lhs >= rhs {
|
||||
Charge(lhs.saturating_sub(*rhs))
|
||||
} else {
|
||||
Refund(rhs.saturating_sub(*lhs))
|
||||
},
|
||||
(Refund(lhs), Refund(rhs)) =>
|
||||
}
|
||||
},
|
||||
(Refund(lhs), Refund(rhs)) => {
|
||||
if lhs > rhs {
|
||||
Refund(lhs.saturating_sub(*rhs))
|
||||
} else {
|
||||
Charge(rhs.saturating_sub(*lhs))
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -198,12 +198,13 @@ impl<T: Config> ContractInfo<T> {
|
||||
if let Some(storage_meter) = storage_meter {
|
||||
let mut diff = meter::Diff::default();
|
||||
match (old_len, new_value.as_ref().map(|v| v.len() as u32)) {
|
||||
(Some(old_len), Some(new_len)) =>
|
||||
(Some(old_len), Some(new_len)) => {
|
||||
if new_len > old_len {
|
||||
diff.bytes_added = new_len - old_len;
|
||||
} else {
|
||||
diff.bytes_removed = old_len - new_len;
|
||||
},
|
||||
}
|
||||
},
|
||||
(None, Some(new_len)) => {
|
||||
diff.bytes_added = new_len;
|
||||
diff.items_added = 1;
|
||||
@@ -297,8 +298,8 @@ impl<T: Config> ContractInfo<T> {
|
||||
/// of those keys can be deleted from the deletion queue given the supplied weight limit.
|
||||
pub fn deletion_budget(meter: &WeightMeter) -> (Weight, u32) {
|
||||
let base_weight = T::WeightInfo::on_process_deletion_queue_batch();
|
||||
let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) -
|
||||
T::WeightInfo::on_initialize_per_trie_key(0);
|
||||
let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1)
|
||||
- T::WeightInfo::on_initialize_per_trie_key(0);
|
||||
|
||||
// `weight_per_key` being zero makes no sense and would constitute a failure to
|
||||
// benchmark properly. We opt for not removing any keys at all in this case.
|
||||
|
||||
@@ -194,16 +194,20 @@ impl Diff {
|
||||
info.storage_items =
|
||||
info.storage_items.saturating_add(items_added).saturating_sub(items_removed);
|
||||
match &bytes_deposit {
|
||||
Deposit::Charge(amount) =>
|
||||
info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount),
|
||||
Deposit::Refund(amount) =>
|
||||
info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount),
|
||||
Deposit::Charge(amount) => {
|
||||
info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount)
|
||||
},
|
||||
Deposit::Refund(amount) => {
|
||||
info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount)
|
||||
},
|
||||
}
|
||||
match &items_deposit {
|
||||
Deposit::Charge(amount) =>
|
||||
info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount),
|
||||
Deposit::Refund(amount) =>
|
||||
info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount),
|
||||
Deposit::Charge(amount) => {
|
||||
info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount)
|
||||
},
|
||||
Deposit::Refund(amount) => {
|
||||
info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount)
|
||||
},
|
||||
}
|
||||
|
||||
bytes_deposit.saturating_add(&items_deposit)
|
||||
@@ -265,8 +269,9 @@ impl<T: Config> Contribution<T> {
|
||||
fn update_contract(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
|
||||
match self {
|
||||
Self::Alive(diff) => diff.update_contract::<T>(info),
|
||||
Self::Terminated { deposit, beneficiary: _ } | Self::Checked(deposit) =>
|
||||
deposit.clone(),
|
||||
Self::Terminated { deposit, beneficiary: _ } | Self::Checked(deposit) => {
|
||||
deposit.clone()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,8 +351,9 @@ where
|
||||
/// Returns the state of the currently executed contract.
|
||||
fn contract_state(&self) -> ContractState<T> {
|
||||
match &self.own_contribution {
|
||||
Contribution::Terminated { deposit: _, beneficiary } =>
|
||||
ContractState::Terminated { beneficiary: beneficiary.clone() },
|
||||
Contribution::Terminated { deposit: _, beneficiary } => {
|
||||
ContractState::Terminated { beneficiary: beneficiary.clone() }
|
||||
},
|
||||
_ => ContractState::Alive,
|
||||
}
|
||||
}
|
||||
@@ -524,8 +530,8 @@ impl<T: Config> Ext<T> for ReservingExt {
|
||||
let default = max.min(T::DefaultDepositLimit::get());
|
||||
let limit = limit.unwrap_or(default);
|
||||
ensure!(
|
||||
limit <= max &&
|
||||
matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success),
|
||||
limit <= max
|
||||
&& matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success),
|
||||
<Error<T>>::StorageDepositNotEnoughFunds,
|
||||
);
|
||||
Ok(limit)
|
||||
|
||||
@@ -150,8 +150,8 @@ pub mod test_utils {
|
||||
let code_info_len = CodeInfo::<Test>::max_encoded_len() as u64;
|
||||
// Calculate deposit to be reserved.
|
||||
// We add 2 storage items: one for code, other for code_info
|
||||
DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) +
|
||||
DepositPerItem::get().saturating_mul(2)
|
||||
DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len)
|
||||
+ DepositPerItem::get().saturating_mul(2)
|
||||
}
|
||||
pub fn ensure_stored(code_hash: CodeHash<Test>) -> usize {
|
||||
// Assert that code_info is stored
|
||||
|
||||
@@ -690,8 +690,9 @@ mod tests {
|
||||
let entry = self.storage.entry(key.clone());
|
||||
let result = match (entry, take_old) {
|
||||
(Entry::Vacant(_), _) => WriteOutcome::New,
|
||||
(Entry::Occupied(entry), false) =>
|
||||
WriteOutcome::Overwritten(entry.remove().len() as u32),
|
||||
(Entry::Occupied(entry), false) => {
|
||||
WriteOutcome::Overwritten(entry.remove().len() as u32)
|
||||
},
|
||||
(Entry::Occupied(entry), true) => WriteOutcome::Taken(entry.remove()),
|
||||
};
|
||||
if let Some(value) = value {
|
||||
|
||||
@@ -133,16 +133,17 @@ impl LoadedModule {
|
||||
match export.name() {
|
||||
"call" => call_found = true,
|
||||
"deploy" => deploy_found = true,
|
||||
_ =>
|
||||
_ => {
|
||||
return Err(
|
||||
"unknown function export: expecting only deploy and call functions",
|
||||
),
|
||||
)
|
||||
},
|
||||
}
|
||||
// Check the signature.
|
||||
// Both "call" and "deploy" have the () -> () function type.
|
||||
// We still support () -> (i32) for backwards compatibility.
|
||||
if !(ft.params().is_empty() &&
|
||||
(ft.results().is_empty() || ft.results() == [WasmiValueType::I32]))
|
||||
if !(ft.params().is_empty()
|
||||
&& (ft.results().is_empty() || ft.results() == [WasmiValueType::I32]))
|
||||
{
|
||||
return Err("entry point has wrong signature");
|
||||
}
|
||||
@@ -194,9 +195,9 @@ impl LoadedModule {
|
||||
ExternType::Func(_) => {
|
||||
import.ty().func().ok_or("expected a function")?;
|
||||
|
||||
if !<T as Config>::ChainExtension::enabled() &&
|
||||
(import.name().as_bytes() == b"seal_call_chain_extension" ||
|
||||
import.name().as_bytes() == b"call_chain_extension")
|
||||
if !<T as Config>::ChainExtension::enabled()
|
||||
&& (import.name().as_bytes() == b"seal_call_chain_extension"
|
||||
|| import.name().as_bytes() == b"call_chain_extension")
|
||||
{
|
||||
return Err(
|
||||
"Module uses chain extensions but chain extensions are disabled",
|
||||
|
||||
@@ -364,8 +364,9 @@ impl<T: Config> Token<T> for RuntimeCosts {
|
||||
DelegateCallBase => T::WeightInfo::seal_delegate_call(),
|
||||
CallTransferSurcharge => cost_args!(seal_call, 1, 0),
|
||||
CallInputCloned(len) => cost_args!(seal_call, 0, len),
|
||||
Instantiate { input_data_len, salt_len } =>
|
||||
T::WeightInfo::seal_instantiate(input_data_len, salt_len),
|
||||
Instantiate { input_data_len, salt_len } => {
|
||||
T::WeightInfo::seal_instantiate(input_data_len, salt_len)
|
||||
},
|
||||
HashSha256(len) => T::WeightInfo::seal_hash_sha2_256(len),
|
||||
HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len),
|
||||
HashBlake256(len) => T::WeightInfo::seal_hash_blake2_256(len),
|
||||
@@ -481,8 +482,9 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> {
|
||||
ReturnFlags::from_bits(*flags).ok_or(Error::<E::T>::InvalidCallFlags)?;
|
||||
return Ok(ExecReturnValue { flags, data: data.to_vec() });
|
||||
},
|
||||
Termination =>
|
||||
return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }),
|
||||
Termination => {
|
||||
return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() })
|
||||
},
|
||||
SupervisorError(error) => return Err((*error).into()),
|
||||
}
|
||||
}
|
||||
@@ -2271,8 +2273,9 @@ pub mod env {
|
||||
Environment::new(ctx, memory, id, input_ptr, input_len, output_ptr, output_len_ptr);
|
||||
let ret = match chain_extension.call(env)? {
|
||||
RetVal::Converging(val) => Ok(val),
|
||||
RetVal::Diverging { flags, data } =>
|
||||
Err(TrapReason::Return(ReturnData { flags: flags.bits(), data })),
|
||||
RetVal::Diverging { flags, data } => {
|
||||
Err(TrapReason::Return(ReturnData { flags: flags.bits(), data }))
|
||||
},
|
||||
};
|
||||
ctx.chain_extension = Some(chain_extension);
|
||||
ret
|
||||
|
||||
@@ -308,7 +308,7 @@ mod sys {
|
||||
// (v1) => [gas_left],
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
//
|
||||
// Expands to:
|
||||
// ```nocompile
|
||||
// fn gas_left(output: &mut &mut [u8]) {
|
||||
|
||||
@@ -645,8 +645,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
}),
|
||||
);
|
||||
match old {
|
||||
Voting::Delegating(Delegating { .. }) =>
|
||||
return Err(Error::<T, I>::AlreadyDelegating.into()),
|
||||
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);
|
||||
|
||||
@@ -99,8 +99,9 @@ impl Polling<TallyOf<Test>> for TestPolls {
|
||||
let mut polls = Polls::get();
|
||||
let entry = polls.get_mut(&index);
|
||||
let r = match entry {
|
||||
Some(Ongoing(ref mut tally_mut_ref, class)) =>
|
||||
f(PollStatus::Ongoing(tally_mut_ref, *class)),
|
||||
Some(Ongoing(ref mut tally_mut_ref, class)) => {
|
||||
f(PollStatus::Ongoing(tally_mut_ref, *class))
|
||||
},
|
||||
Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)),
|
||||
None => f(PollStatus::None),
|
||||
};
|
||||
@@ -114,8 +115,9 @@ impl Polling<TallyOf<Test>> for TestPolls {
|
||||
let mut polls = Polls::get();
|
||||
let entry = polls.get_mut(&index);
|
||||
let r = match entry {
|
||||
Some(Ongoing(ref mut tally_mut_ref, class)) =>
|
||||
f(PollStatus::Ongoing(tally_mut_ref, *class)),
|
||||
Some(Ongoing(ref mut tally_mut_ref, class)) => {
|
||||
f(PollStatus::Ongoing(tally_mut_ref, *class))
|
||||
},
|
||||
Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)),
|
||||
None => f(PollStatus::None),
|
||||
}?;
|
||||
|
||||
@@ -110,17 +110,21 @@ impl<Balance: Saturating> AccountVote<Balance> {
|
||||
// winning side: can only be removed after the lock period ends.
|
||||
match (self, approved) {
|
||||
// If the vote has no conviction, always return None
|
||||
(AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. }, _) =>
|
||||
None,
|
||||
(AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. }, _) => {
|
||||
None
|
||||
},
|
||||
|
||||
// For Standard votes, check the approval condition
|
||||
(AccountVote::Standard { vote, balance }, LockedIf::Status(is_approved))
|
||||
if vote.aye == is_approved =>
|
||||
Some((vote.conviction.lock_periods(), balance)),
|
||||
{
|
||||
Some((vote.conviction.lock_periods(), balance))
|
||||
},
|
||||
|
||||
// If LockedIf::Always, return the lock period regardless of the vote
|
||||
(AccountVote::Standard { vote, balance }, LockedIf::Always) =>
|
||||
Some((vote.conviction.lock_periods(), balance)),
|
||||
(AccountVote::Standard { vote, balance }, LockedIf::Always) => {
|
||||
Some((vote.conviction.lock_periods(), balance))
|
||||
},
|
||||
|
||||
// All other cases return None
|
||||
_ => None,
|
||||
@@ -132,8 +136,9 @@ impl<Balance: Saturating> AccountVote<Balance> {
|
||||
match self {
|
||||
AccountVote::Standard { balance, .. } => balance,
|
||||
AccountVote::Split { aye, nay } => aye.saturating_add(nay),
|
||||
AccountVote::SplitAbstain { aye, nay, abstain } =>
|
||||
aye.saturating_add(nay).saturating_add(abstain),
|
||||
AccountVote::SplitAbstain { aye, nay, abstain } => {
|
||||
aye.saturating_add(nay).saturating_add(abstain)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,8 +312,9 @@ where
|
||||
/// The amount of this account's balance that must currently be locked due to voting.
|
||||
pub fn locked_balance(&self) -> Balance {
|
||||
match self {
|
||||
Voting::Casting(Casting { votes, prior, .. }) =>
|
||||
votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)),
|
||||
Voting::Casting(Casting { votes, prior, .. }) => {
|
||||
votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i))
|
||||
},
|
||||
Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()),
|
||||
}
|
||||
}
|
||||
@@ -319,10 +325,12 @@ where
|
||||
prior: PriorLock<BlockNumber, Balance>,
|
||||
) {
|
||||
let (d, p) = match self {
|
||||
Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) =>
|
||||
(delegations, prior),
|
||||
Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) =>
|
||||
(delegations, prior),
|
||||
Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) => {
|
||||
(delegations, prior)
|
||||
},
|
||||
Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) => {
|
||||
(delegations, prior)
|
||||
},
|
||||
};
|
||||
*d = delegations;
|
||||
*p = prior;
|
||||
|
||||
@@ -326,9 +326,9 @@ pub mod pezpallet {
|
||||
let ledger = AgentLedger::<T>::get(&who).ok_or(Error::<T>::NotAgent)?;
|
||||
|
||||
ensure!(
|
||||
ledger.total_delegated == Zero::zero() &&
|
||||
ledger.pending_slash == Zero::zero() &&
|
||||
ledger.unclaimed_withdrawals == Zero::zero(),
|
||||
ledger.total_delegated == Zero::zero()
|
||||
&& ledger.pending_slash == Zero::zero()
|
||||
&& ledger.unclaimed_withdrawals == Zero::zero(),
|
||||
Error::<T>::NotAllowed
|
||||
);
|
||||
|
||||
@@ -788,16 +788,16 @@ impl<T: Config> Pezpallet<T> {
|
||||
ensure!(
|
||||
matches!(
|
||||
T::CoreStaking::status(&agent).expect("agent should be bonded"),
|
||||
pezsp_staking::StakerStatus::Nominator(_) |
|
||||
pezsp_staking::StakerStatus::Idle
|
||||
pezsp_staking::StakerStatus::Nominator(_)
|
||||
| pezsp_staking::StakerStatus::Idle
|
||||
),
|
||||
"agent should be bonded and not validator"
|
||||
);
|
||||
}
|
||||
|
||||
ensure!(
|
||||
ledger.stakeable_balance() >=
|
||||
T::CoreStaking::total_stake(&agent).unwrap_or_default(),
|
||||
ledger.stakeable_balance()
|
||||
>= T::CoreStaking::total_stake(&agent).unwrap_or_default(),
|
||||
"Cannot stake more than balance"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -303,8 +303,8 @@ pub(crate) fn start_era(era: pezsp_staking::EraIndex) {
|
||||
}
|
||||
|
||||
pub(crate) fn eq_stake(who: AccountId, total: Balance, active: Balance) -> bool {
|
||||
Staking::stake(&who).unwrap() == Stake { total, active } &&
|
||||
get_agent_ledger(&who).ledger.stakeable_balance() == total
|
||||
Staking::stake(&who).unwrap() == Stake { total, active }
|
||||
&& get_agent_ledger(&who).ledger.stakeable_balance() == total
|
||||
}
|
||||
|
||||
pub(crate) fn get_agent_ledger(agent: &AccountId) -> AgentLedgerOuter<T> {
|
||||
|
||||
@@ -551,8 +551,9 @@ mod benchmarks {
|
||||
for i in 0..r {
|
||||
if let Some(value) = ReferendumInfoOf::<T>::get(i) {
|
||||
match value {
|
||||
ReferendumInfo::Finished { .. } =>
|
||||
return Err("Referendum has been finished".into()),
|
||||
ReferendumInfo::Finished { .. } => {
|
||||
return Err("Referendum has been finished".into())
|
||||
},
|
||||
ReferendumInfo::Ongoing(_) => (),
|
||||
}
|
||||
}
|
||||
@@ -589,8 +590,9 @@ mod benchmarks {
|
||||
for i in 0..r {
|
||||
if let Some(value) = ReferendumInfoOf::<T>::get(i) {
|
||||
match value {
|
||||
ReferendumInfo::Finished { .. } =>
|
||||
return Err("Referendum has been finished".into()),
|
||||
ReferendumInfo::Finished { .. } => {
|
||||
return Err("Referendum has been finished".into())
|
||||
},
|
||||
ReferendumInfo::Ongoing(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1670,8 +1670,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
// of unbaked referendum is bounded by this number. In case those number have changed in a
|
||||
// runtime upgrade the formula should be adjusted but the bound should still be sensible.
|
||||
LowestUnbaked::<T>::mutate(|ref_index| {
|
||||
while *ref_index < last &&
|
||||
ReferendumInfoOf::<T>::get(*ref_index)
|
||||
while *ref_index < last
|
||||
&& ReferendumInfoOf::<T>::get(*ref_index)
|
||||
.map_or(true, |info| matches!(info, ReferendumInfo::Finished { .. }))
|
||||
{
|
||||
*ref_index += 1
|
||||
|
||||
@@ -192,8 +192,8 @@ where
|
||||
let bugged_deposits = all_accounts
|
||||
.iter()
|
||||
.filter(|account| {
|
||||
account_deposits.get(&account).unwrap_or(&Zero::zero()) >
|
||||
account_reserved_before.get(&account).unwrap_or(&Zero::zero())
|
||||
account_deposits.get(&account).unwrap_or(&Zero::zero())
|
||||
> account_reserved_before.get(&account).unwrap_or(&Zero::zero())
|
||||
})
|
||||
.count();
|
||||
|
||||
|
||||
@@ -92,16 +92,18 @@ pub mod v1 {
|
||||
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
|
||||
log::info!(target: TARGET, "migrating referendum #{:?}", &index);
|
||||
Some(match old {
|
||||
ReferendumInfo::Ongoing(status) =>
|
||||
ReferendumInfo::Ongoing(status) => {
|
||||
ReferendumInfo::Ongoing(ReferendumStatus {
|
||||
end: status.end,
|
||||
proposal: Bounded::from_legacy_hash(status.proposal),
|
||||
threshold: status.threshold,
|
||||
delay: status.delay,
|
||||
tally: status.tally,
|
||||
}),
|
||||
ReferendumInfo::Finished { approved, end } =>
|
||||
ReferendumInfo::Finished { approved, end },
|
||||
})
|
||||
},
|
||||
ReferendumInfo::Finished { approved, end } => {
|
||||
ReferendumInfo::Finished { approved, end }
|
||||
},
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
@@ -98,8 +98,9 @@ impl<Balance: Saturating> AccountVote<Balance> {
|
||||
pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> {
|
||||
// winning side: can only be removed after the lock period ends.
|
||||
match self {
|
||||
AccountVote::Standard { vote, balance } if vote.aye == approved =>
|
||||
Some((vote.conviction.lock_periods(), balance)),
|
||||
AccountVote::Standard { vote, balance } if vote.aye == approved => {
|
||||
Some((vote.conviction.lock_periods(), balance))
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -215,8 +216,9 @@ impl<
|
||||
/// The amount of this account's balance that must currently be locked due to voting.
|
||||
pub fn locked_balance(&self) -> Balance {
|
||||
match self {
|
||||
Voting::Direct { votes, prior, .. } =>
|
||||
votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)),
|
||||
Voting::Direct { votes, prior, .. } => {
|
||||
votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i))
|
||||
},
|
||||
Voting::Delegating { balance, prior, .. } => *balance.max(&prior.locked()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,10 +107,12 @@ impl<
|
||||
return false;
|
||||
}
|
||||
match *self {
|
||||
VoteThreshold::SuperMajorityApprove =>
|
||||
compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate),
|
||||
VoteThreshold::SuperMajorityAgainst =>
|
||||
compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters),
|
||||
VoteThreshold::SuperMajorityApprove => {
|
||||
compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate)
|
||||
},
|
||||
VoteThreshold::SuperMajorityAgainst => {
|
||||
compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters)
|
||||
},
|
||||
VoteThreshold::SimpleMajority => tally.ayes > tally.nays,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,9 +211,10 @@ impl<Registry: DerivativesRegistry<NonFungibleAsset, DerivativeId>, DerivativeId
|
||||
{
|
||||
fn matches_instance(asset: &Asset) -> Result<DerivativeId, Error> {
|
||||
match asset.fun {
|
||||
Fungibility::NonFungible(asset_instance) =>
|
||||
Fungibility::NonFungible(asset_instance) => {
|
||||
Registry::get_derivative(&(asset.id.clone(), asset_instance))
|
||||
.map_err(|_| Error::AssetNotHandled),
|
||||
.map_err(|_| Error::AssetNotHandled)
|
||||
},
|
||||
Fungibility::Fungible(_) => Err(Error::AssetNotHandled),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,16 +66,18 @@ impl Update<ChangeOwnerFrom<AccountId>> for PredefinedIdNfts {
|
||||
|
||||
unique_items::ItemOwner::<Test, PredefinedIdNftsInstance>::try_mutate(id, |owner| {
|
||||
match owner {
|
||||
Some(current_owner) =>
|
||||
Some(current_owner) => {
|
||||
if *current_owner == check_owner {
|
||||
*owner = Some(*new_owner);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unique_items::Error::<Test, PredefinedIdNftsInstance>::NoPermission
|
||||
.into())
|
||||
},
|
||||
None =>
|
||||
Err(unique_items::Error::<Test, PredefinedIdNftsInstance>::UnknownItem.into()),
|
||||
}
|
||||
},
|
||||
None => {
|
||||
Err(unique_items::Error::<Test, PredefinedIdNftsInstance>::UnknownItem.into())
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,7 +169,9 @@ impl ContainsPair<Asset, Location> for TrustAssetsFromSiblings {
|
||||
match (asset_location.unpack(), origin.unpack()) {
|
||||
((1, [Teyrchain(asset_para_id), ..]), (1, [Teyrchain(origin_para_id)]))
|
||||
if asset_para_id == origin_para_id =>
|
||||
true,
|
||||
{
|
||||
true
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -210,8 +212,9 @@ pub struct SiblingAssetToReserveLocationConvert;
|
||||
impl ConvertLocation<AccountId> for SiblingAssetToReserveLocationConvert {
|
||||
fn convert_location(location: &Location) -> Option<AccountId> {
|
||||
match location.unpack() {
|
||||
(1, [Teyrchain(para_id), ..]) =>
|
||||
LocationToAccountId::convert_location(&Location::new(1, Teyrchain(*para_id))),
|
||||
(1, [Teyrchain(para_id), ..]) => {
|
||||
LocationToAccountId::convert_location(&Location::new(1, Teyrchain(*para_id)))
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -732,8 +732,9 @@ pub mod pezpallet {
|
||||
|
||||
let weight2 = match next_phase {
|
||||
Phase::Signed(_) => T::WeightInfo::on_initialize_into_signed(),
|
||||
Phase::SignedValidation(_) =>
|
||||
T::WeightInfo::on_initialize_into_signed_validation(),
|
||||
Phase::SignedValidation(_) => {
|
||||
T::WeightInfo::on_initialize_into_signed_validation()
|
||||
},
|
||||
Phase::Unsigned(_) => T::WeightInfo::on_initialize_into_unsigned(),
|
||||
_ => T::WeightInfo::on_initialize_nothing(),
|
||||
};
|
||||
@@ -777,8 +778,8 @@ pub mod pezpallet {
|
||||
let max_vote: usize = <SolutionOf<T::MinerConfig> as NposSolution>::LIMIT;
|
||||
|
||||
// 2. Maximum sum of [SolutionAccuracy; 16] must fit into `UpperOf<OffchainAccuracy>`.
|
||||
let maximum_chain_accuracy: Vec<UpperOf<SolutionAccuracyOf<T::MinerConfig>>> = (0..
|
||||
max_vote)
|
||||
let maximum_chain_accuracy: Vec<UpperOf<SolutionAccuracyOf<T::MinerConfig>>> = (0
|
||||
..max_vote)
|
||||
.map(|_| {
|
||||
<UpperOf<SolutionAccuracyOf<T::MinerConfig>>>::from(
|
||||
<SolutionAccuracyOf<T::MinerConfig>>::one().deconstruct(),
|
||||
@@ -809,8 +810,8 @@ pub mod pezpallet {
|
||||
"Signed phase not set correct -- both should be set or unset"
|
||||
);
|
||||
assert!(
|
||||
signed_validation.is_zero() ||
|
||||
signed_validation % T::Pages::get().into() == Zero::zero(),
|
||||
signed_validation.is_zero()
|
||||
|| signed_validation % T::Pages::get().into() == Zero::zero(),
|
||||
"signed validation phase should be a multiple of the number of pages."
|
||||
);
|
||||
|
||||
@@ -1041,8 +1042,8 @@ pub mod pezpallet {
|
||||
.take(up_to_page as usize)
|
||||
{
|
||||
ensure!(
|
||||
(exists ^ Self::voters(p).is_none()) &&
|
||||
(exists ^ Self::voters_hash(p).is_none()),
|
||||
(exists ^ Self::voters(p).is_none())
|
||||
&& (exists ^ Self::voters_hash(p).is_none()),
|
||||
"voter page existence mismatch"
|
||||
);
|
||||
|
||||
@@ -1058,8 +1059,8 @@ pub mod pezpallet {
|
||||
.take((T::Pages::get() - up_to_page) as usize)
|
||||
{
|
||||
ensure!(
|
||||
(exists ^ Self::voters(p).is_some()) &&
|
||||
(exists ^ Self::voters_hash(p).is_some()),
|
||||
(exists ^ Self::voters(p).is_some())
|
||||
&& (exists ^ Self::voters_hash(p).is_some()),
|
||||
"voter page non-existence mismatch"
|
||||
);
|
||||
}
|
||||
@@ -1079,17 +1080,17 @@ pub mod pezpallet {
|
||||
ensure!(Self::desired_targets().is_some(), "desired target mismatch");
|
||||
ensure!(Self::targets_hash().is_some(), "targets hash mismatch");
|
||||
ensure!(
|
||||
Self::targets_decode_len().unwrap_or_default() as u32 ==
|
||||
T::TargetSnapshotPerBlock::get(),
|
||||
Self::targets_decode_len().unwrap_or_default() as u32
|
||||
== T::TargetSnapshotPerBlock::get(),
|
||||
"targets decode length mismatch"
|
||||
);
|
||||
|
||||
// ensure that voter pages that should exist, indeed to exist..
|
||||
for p in crate::Pezpallet::<T>::lsp()..=crate::Pezpallet::<T>::msp() {
|
||||
ensure!(
|
||||
Self::voters_hash(p).is_some() &&
|
||||
Self::voters_decode_len(p).unwrap_or_default() as u32 ==
|
||||
T::VoterSnapshotPerBlock::get(),
|
||||
Self::voters_hash(p).is_some()
|
||||
&& Self::voters_decode_len(p).unwrap_or_default() as u32
|
||||
== T::VoterSnapshotPerBlock::get(),
|
||||
"voter page existence mismatch"
|
||||
);
|
||||
}
|
||||
@@ -1118,21 +1119,23 @@ pub mod pezpallet {
|
||||
Phase::Off => Self::ensure_snapshot(false, T::Pages::get()),
|
||||
|
||||
// we will star the snapshot in the next phase.
|
||||
Phase::Snapshot(p) if p == T::Pages::get() =>
|
||||
Self::ensure_snapshot(false, T::Pages::get()),
|
||||
Phase::Snapshot(p) if p == T::Pages::get() => {
|
||||
Self::ensure_snapshot(false, T::Pages::get())
|
||||
},
|
||||
// we are mid voter snapshot.
|
||||
Phase::Snapshot(p) if p < T::Pages::get() && p > 0 =>
|
||||
Self::ensure_snapshot(true, T::Pages::get() - p - 1),
|
||||
Phase::Snapshot(p) if p < T::Pages::get() && p > 0 => {
|
||||
Self::ensure_snapshot(true, T::Pages::get() - p - 1)
|
||||
},
|
||||
// we cannot check anything in this block -- we take the last page of the snapshot.
|
||||
Phase::Snapshot(_) => Ok(()),
|
||||
|
||||
// full snapshot must exist in these phases.
|
||||
Phase::Emergency |
|
||||
Phase::Signed(_) |
|
||||
Phase::SignedValidation(_) |
|
||||
Phase::Export(_) |
|
||||
Phase::Done |
|
||||
Phase::Unsigned(_) => Self::ensure_snapshot(true, T::Pages::get()),
|
||||
Phase::Emergency
|
||||
| Phase::Signed(_)
|
||||
| Phase::SignedValidation(_)
|
||||
| Phase::Export(_)
|
||||
| Phase::Done
|
||||
| Phase::Unsigned(_) => Self::ensure_snapshot(true, T::Pages::get()),
|
||||
}?;
|
||||
|
||||
Ok(())
|
||||
@@ -1316,8 +1319,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
// check the snapshot fingerprint, if asked for.
|
||||
ensure!(
|
||||
maybe_snapshot_fingerprint
|
||||
.map_or(true, |snapshot_fingerprint| Snapshot::<T>::fingerprint() ==
|
||||
snapshot_fingerprint),
|
||||
.map_or(true, |snapshot_fingerprint| Snapshot::<T>::fingerprint()
|
||||
== snapshot_fingerprint),
|
||||
CommonError::WrongFingerprint
|
||||
);
|
||||
|
||||
@@ -1676,11 +1679,11 @@ impl<T: Config> ElectionProvider for Pezpallet<T> {
|
||||
Phase::Off => Err(()),
|
||||
|
||||
// we're doing sth but not read.
|
||||
Phase::Signed(_) |
|
||||
Phase::SignedValidation(_) |
|
||||
Phase::Unsigned(_) |
|
||||
Phase::Snapshot(_) |
|
||||
Phase::Emergency => Ok(false),
|
||||
Phase::Signed(_)
|
||||
| Phase::SignedValidation(_)
|
||||
| Phase::Unsigned(_)
|
||||
| Phase::Snapshot(_)
|
||||
| Phase::Emergency => Ok(false),
|
||||
|
||||
// we're ready
|
||||
Phase::Done | Phase::Export(_) => Ok(true),
|
||||
|
||||
@@ -285,9 +285,10 @@ impl InstantElectionProvider for MockFallback {
|
||||
desired_targets: u32,
|
||||
) -> Result<BoundedSupportsOf<Self>, Self::Error> {
|
||||
match FallbackMode::get() {
|
||||
FallbackModes::Continue =>
|
||||
FallbackModes::Continue => {
|
||||
crate::Continue::<Runtime>::instant_elect(voters, targets, desired_targets)
|
||||
.map_err(|x| x.to_string()),
|
||||
.map_err(|x| x.to_string())
|
||||
},
|
||||
FallbackModes::Emergency => crate::InitiateEmergencyPhase::<Runtime>::instant_elect(
|
||||
voters,
|
||||
targets,
|
||||
|
||||
@@ -334,14 +334,17 @@ impl<T: crate::Config> Phase<T> {
|
||||
Self::are_we_done()
|
||||
}
|
||||
},
|
||||
Self::Snapshot(non_zero_remaining) =>
|
||||
Self::Snapshot(non_zero_remaining.defensive_saturating_sub(One::one())),
|
||||
Self::Snapshot(non_zero_remaining) => {
|
||||
Self::Snapshot(non_zero_remaining.defensive_saturating_sub(One::one()))
|
||||
},
|
||||
|
||||
// signed phase
|
||||
Self::Signed(zero) if zero == BlockNumberFor::<T>::zero() =>
|
||||
Self::SignedValidation(T::SignedValidationPhase::get()),
|
||||
Self::Signed(non_zero_left) =>
|
||||
Self::Signed(non_zero_left.defensive_saturating_sub(One::one())),
|
||||
Self::Signed(zero) if zero == BlockNumberFor::<T>::zero() => {
|
||||
Self::SignedValidation(T::SignedValidationPhase::get())
|
||||
},
|
||||
Self::Signed(non_zero_left) => {
|
||||
Self::Signed(non_zero_left.defensive_saturating_sub(One::one()))
|
||||
},
|
||||
|
||||
// signed validation
|
||||
Self::SignedValidation(zero)
|
||||
@@ -353,21 +356,24 @@ impl<T: crate::Config> Phase<T> {
|
||||
Self::are_we_done()
|
||||
}
|
||||
},
|
||||
Self::SignedValidation(non_zero_left) =>
|
||||
Self::SignedValidation(non_zero_left.saturating_sub(One::one())),
|
||||
Self::SignedValidation(non_zero_left) => {
|
||||
Self::SignedValidation(non_zero_left.saturating_sub(One::one()))
|
||||
},
|
||||
|
||||
// unsigned phase -- at this phase we will
|
||||
Self::Unsigned(zero) if zero == BlockNumberFor::<T>::zero() => Self::are_we_done(),
|
||||
Self::Unsigned(non_zero_left) =>
|
||||
Self::Unsigned(non_zero_left.defensive_saturating_sub(One::one())),
|
||||
Self::Unsigned(non_zero_left) => {
|
||||
Self::Unsigned(non_zero_left.defensive_saturating_sub(One::one()))
|
||||
},
|
||||
|
||||
// Done. Wait for export to start.
|
||||
Self::Done => Self::Done,
|
||||
|
||||
// Export
|
||||
Self::Export(0) => Self::Off,
|
||||
Self::Export(non_zero_left) =>
|
||||
Self::Export(non_zero_left.defensive_saturating_sub(One::one())),
|
||||
Self::Export(non_zero_left) => {
|
||||
Self::Export(non_zero_left.defensive_saturating_sub(One::one()))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -925,8 +925,9 @@ impl<T: Config> OffchainWorkerMiner<T> {
|
||||
|maybe_head: Result<Option<BlockNumberFor<T>>, _>| {
|
||||
match maybe_head {
|
||||
Ok(Some(head)) if now < head => Err("fork."),
|
||||
Ok(Some(head)) if now >= head && now <= head + threshold =>
|
||||
Err("recently executed."),
|
||||
Ok(Some(head)) if now >= head && now <= head + threshold => {
|
||||
Err("recently executed.")
|
||||
},
|
||||
Ok(Some(head)) if now > head + threshold => {
|
||||
// we can run again now. Write the new head.
|
||||
Ok(now)
|
||||
@@ -961,8 +962,9 @@ impl<T: Config> OffchainWorkerMiner<T> {
|
||||
let storage = StorageValueRef::persistent(&Self::OFFCHAIN_CACHED_CALL);
|
||||
match storage.mutate::<_, (), _>(|_| Ok((call.clone(), snapshot_fingerprint))) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) =>
|
||||
Err(OffchainMinerError::FailedToStoreSolution),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) => {
|
||||
Err(OffchainMinerError::FailedToStoreSolution)
|
||||
},
|
||||
Err(MutateStorageError::ValueFunctionFailed(_)) => {
|
||||
// this branch should be unreachable according to the definition of
|
||||
// `StorageValueRef::mutate`: that function should only ever `Err` if the closure we
|
||||
|
||||
@@ -240,8 +240,8 @@ mod pezpallet {
|
||||
"weight of `submit_unsigned` is too high"
|
||||
);
|
||||
assert!(
|
||||
<T as Config>::MinerPages::get() as usize <=
|
||||
<T as crate::Config>::Pages::get() as usize,
|
||||
<T as Config>::MinerPages::get() as usize
|
||||
<= <T as crate::Config>::Pages::get() as usize,
|
||||
"number of pages in the unsigned phase is too high"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -341,10 +341,12 @@ pub(crate) mod pezpallet {
|
||||
// store the valid pages
|
||||
for (support, page) in supports.into_iter().zip(pages.iter()) {
|
||||
match Self::valid() {
|
||||
ValidSolution::X =>
|
||||
QueuedSolutionX::<T>::insert(Self::round(), page, support),
|
||||
ValidSolution::Y =>
|
||||
QueuedSolutionY::<T>::insert(Self::round(), page, support),
|
||||
ValidSolution::X => {
|
||||
QueuedSolutionX::<T>::insert(Self::round(), page, support)
|
||||
},
|
||||
ValidSolution::Y => {
|
||||
QueuedSolutionY::<T>::insert(Self::round(), page, support)
|
||||
},
|
||||
}
|
||||
}
|
||||
QueuedSolutionScore::<T>::insert(Self::round(), score);
|
||||
@@ -490,8 +492,8 @@ pub(crate) mod pezpallet {
|
||||
// The number of existing keys in `QueuedSolutionBackings` must always match that of
|
||||
// the INVALID variant.
|
||||
ensure!(
|
||||
QueuedSolutionBackings::<T>::iter_prefix(Self::round()).count() ==
|
||||
Self::invalid_iter().count(),
|
||||
QueuedSolutionBackings::<T>::iter_prefix(Self::round()).count()
|
||||
== Self::invalid_iter().count(),
|
||||
"incorrect number of backings pages",
|
||||
);
|
||||
|
||||
|
||||
@@ -1769,7 +1769,7 @@ impl<T: Config> Pezpallet<T> {
|
||||
|
||||
match SignedSubmissionNextIndex::<T>::get() {
|
||||
0 => Ok(()),
|
||||
next =>
|
||||
next => {
|
||||
if SignedSubmissionsMap::<T>::get(next).is_some() {
|
||||
return Err(
|
||||
"The next submissions index should not be in the submissions maps already"
|
||||
@@ -1777,7 +1777,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
);
|
||||
} else {
|
||||
Ok(())
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1786,12 +1787,13 @@ impl<T: Config> Pezpallet<T> {
|
||||
fn try_state_phase_off() -> Result<(), TryRuntimeError> {
|
||||
match CurrentPhase::<T>::get().is_off() {
|
||||
false => Ok(()),
|
||||
true =>
|
||||
true => {
|
||||
if Snapshot::<T>::get().is_some() {
|
||||
Err("Snapshot must be none when in Phase::Off".into())
|
||||
} else {
|
||||
Ok(())
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2749,8 +2751,8 @@ mod tests {
|
||||
|
||||
let mut active = 1;
|
||||
while weight_with(active)
|
||||
.all_lte(<Runtime as pezframe_system::Config>::BlockWeights::get().max_block) ||
|
||||
active == all_voters
|
||||
.all_lte(<Runtime as pezframe_system::Config>::BlockWeights::get().max_block)
|
||||
|| active == all_voters
|
||||
{
|
||||
active += 1;
|
||||
}
|
||||
|
||||
@@ -400,10 +400,12 @@ impl MinerConfig for Runtime {
|
||||
(10 as u64).saturating_add((5 as u64).saturating_mul(a as u64)),
|
||||
0,
|
||||
),
|
||||
MockedWeightInfo::Complex =>
|
||||
Weight::from_parts((0 * v + 0 * t + 1000 * a + 0 * d) as u64, 0),
|
||||
MockedWeightInfo::Real =>
|
||||
<() as multi_phase::weights::WeightInfo>::feasibility_check(v, t, a, d),
|
||||
MockedWeightInfo::Complex => {
|
||||
Weight::from_parts((0 * v + 0 * t + 1000 * a + 0 * d) as u64, 0)
|
||||
},
|
||||
MockedWeightInfo::Real => {
|
||||
<() as multi_phase::weights::WeightInfo>::feasibility_check(v, t, a, d)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,8 +496,8 @@ impl ElectionDataProvider for StakingMock {
|
||||
|
||||
let targets = Targets::get();
|
||||
|
||||
if !DataProviderAllowBadData::get() &&
|
||||
bounds.count.map_or(false, |max_len| targets.len() > max_len.0 as usize)
|
||||
if !DataProviderAllowBadData::get()
|
||||
&& bounds.count.map_or(false, |max_len| targets.len() > max_len.0 as usize)
|
||||
{
|
||||
return Err("Targets too big");
|
||||
}
|
||||
|
||||
@@ -152,8 +152,9 @@ fn save_solution<T: Config>(call: &Call<T>) -> Result<(), MinerError> {
|
||||
let storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL);
|
||||
match storage.mutate::<_, (), _>(|_| Ok(call.clone())) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) =>
|
||||
Err(MinerError::FailedToStoreSolution),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) => {
|
||||
Err(MinerError::FailedToStoreSolution)
|
||||
},
|
||||
Err(MutateStorageError::ValueFunctionFailed(_)) => {
|
||||
// this branch should be unreachable according to the definition of
|
||||
// `StorageValueRef::mutate`: that function should only ever `Err` if the closure we
|
||||
@@ -354,8 +355,9 @@ impl<T: Config + CreateBare<Call<T>>> Pezpallet<T> {
|
||||
|maybe_head: Result<Option<BlockNumberFor<T>>, _>| {
|
||||
match maybe_head {
|
||||
Ok(Some(head)) if now < head => Err("fork."),
|
||||
Ok(Some(head)) if now >= head && now <= head + threshold =>
|
||||
Err("recently executed."),
|
||||
Ok(Some(head)) if now >= head && now <= head + threshold => {
|
||||
Err("recently executed.")
|
||||
},
|
||||
Ok(Some(head)) if now > head + threshold => {
|
||||
// we can run again now. Write the new head.
|
||||
Ok(now)
|
||||
@@ -372,8 +374,9 @@ impl<T: Config + CreateBare<Call<T>>> Pezpallet<T> {
|
||||
// all good
|
||||
Ok(_) => Ok(()),
|
||||
// failed to write.
|
||||
Err(MutateStorageError::ConcurrentModification(_)) =>
|
||||
Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")),
|
||||
Err(MutateStorageError::ConcurrentModification(_)) => {
|
||||
Err(MinerError::Lock("failed to write to offchain db (concurrent modification)."))
|
||||
},
|
||||
// fork etc.
|
||||
Err(MutateStorageError::ValueFunctionFailed(why)) => Err(MinerError::Lock(why)),
|
||||
}
|
||||
@@ -400,8 +403,8 @@ impl<T: Config + CreateBare<Call<T>>> Pezpallet<T> {
|
||||
|
||||
// ensure correct number of winners.
|
||||
ensure!(
|
||||
DesiredTargets::<T>::get().unwrap_or_default() ==
|
||||
raw_solution.solution.unique_targets().len() as u32,
|
||||
DesiredTargets::<T>::get().unwrap_or_default()
|
||||
== raw_solution.solution.unique_targets().len() as u32,
|
||||
Error::<T>::PreDispatchWrongWinnerCount,
|
||||
);
|
||||
|
||||
@@ -669,8 +672,8 @@ impl<T: MinerConfig> Miner<T> {
|
||||
high = test;
|
||||
}
|
||||
}
|
||||
let maximum_allowed_voters = if low < assignments.len() &&
|
||||
encoded_size_of(&assignments[..low + 1])? <= max_allowed_length
|
||||
let maximum_allowed_voters = if low < assignments.len()
|
||||
&& encoded_size_of(&assignments[..low + 1])? <= max_allowed_length
|
||||
{
|
||||
low + 1
|
||||
} else {
|
||||
@@ -682,8 +685,8 @@ impl<T: MinerConfig> Miner<T> {
|
||||
encoded_size_of(&assignments[..maximum_allowed_voters]).unwrap() <= max_allowed_length
|
||||
);
|
||||
debug_assert!(if maximum_allowed_voters < assignments.len() {
|
||||
encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() >
|
||||
max_allowed_length
|
||||
encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap()
|
||||
> max_allowed_length
|
||||
} else {
|
||||
true
|
||||
});
|
||||
|
||||
@@ -151,8 +151,8 @@ impl DataProviderBounds {
|
||||
/// Returns true if `given_size` or `given_count` exhausts `self.size` or `self_count`,
|
||||
/// respectively.
|
||||
pub fn exhausted(self, given_size: Option<SizeBound>, given_count: Option<CountBound>) -> bool {
|
||||
self.count_exhausted(given_count.unwrap_or(CountBound::zero())) ||
|
||||
self.size_exhausted(given_size.unwrap_or(SizeBound::zero()))
|
||||
self.count_exhausted(given_count.unwrap_or(CountBound::zero()))
|
||||
|| self.size_exhausted(given_size.unwrap_or(SizeBound::zero()))
|
||||
}
|
||||
|
||||
/// Ensures the given encode-able slice meets both the length and count bounds.
|
||||
|
||||
@@ -311,8 +311,8 @@ pub mod pezpallet {
|
||||
);
|
||||
|
||||
let to_seconds = |w: &Weight| {
|
||||
w.ref_time() as f32 /
|
||||
pezframe_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as f32
|
||||
w.ref_time() as f32
|
||||
/ pezframe_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as f32
|
||||
};
|
||||
|
||||
log::debug!(
|
||||
@@ -1099,8 +1099,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
// 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()
|
||||
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);
|
||||
@@ -1268,11 +1268,12 @@ impl<T: Config> Pezpallet<T> {
|
||||
// - Members and candidates sets are disjoint;
|
||||
// - Members and runners-ups sets are disjoint.
|
||||
fn try_state_members_disjoint() -> Result<(), TryRuntimeError> {
|
||||
match Self::intersects(&Pezpallet::<T>::members_ids(), &Self::candidates_ids()) &&
|
||||
Self::intersects(&Pezpallet::<T>::members_ids(), &Self::runners_up_ids())
|
||||
match Self::intersects(&Pezpallet::<T>::members_ids(), &Self::candidates_ids())
|
||||
&& Self::intersects(&Pezpallet::<T>::members_ids(), &Self::runners_up_ids())
|
||||
{
|
||||
true =>
|
||||
Err("Members set should be disjoint from candidates and runners-up sets".into()),
|
||||
true => {
|
||||
Err("Members set should be disjoint from candidates and runners-up sets".into())
|
||||
},
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -211,8 +211,8 @@ where
|
||||
let bugged_deposits = all_accounts
|
||||
.iter()
|
||||
.filter(|account| {
|
||||
account_deposited_sums.get(&account).unwrap_or(&Zero::zero()) >
|
||||
account_reserved_before.get(&account).unwrap_or(&Zero::zero())
|
||||
account_deposited_sums.get(&account).unwrap_or(&Zero::zero())
|
||||
> account_reserved_before.get(&account).unwrap_or(&Zero::zero())
|
||||
})
|
||||
.count();
|
||||
|
||||
|
||||
@@ -99,8 +99,9 @@ mod example_runtime {
|
||||
|
||||
fn try_origin(o: RuntimeOrigin) -> Result<Self::Success, RuntimeOrigin> {
|
||||
match o.clone().into() {
|
||||
Ok(pezpallet_coownership::Origin::<Runtime>::Coowners(first, second)) =>
|
||||
Ok((first, second)),
|
||||
Ok(pezpallet_coownership::Origin::<Runtime>::Coowners(first, second)) => {
|
||||
Ok((first, second))
|
||||
},
|
||||
_ => Err(o),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,9 +41,9 @@ fn lazy_migration_works() {
|
||||
}
|
||||
|
||||
// Give it enough weight do do exactly 16 iterations:
|
||||
let limit = <T as pezpallet_migrations::Config>::WeightInfo::progress_mbms_none() +
|
||||
pezpallet_migrations::Pezpallet::<T>::exec_migration_max_weight() +
|
||||
weights::BizinikiwiWeight::<T>::step() * 16;
|
||||
let limit = <T as pezpallet_migrations::Config>::WeightInfo::progress_mbms_none()
|
||||
+ pezpallet_migrations::Pezpallet::<T>::exec_migration_max_weight()
|
||||
+ weights::BizinikiwiWeight::<T>::step() * 16;
|
||||
MigratorServiceWeight::set(&limit);
|
||||
|
||||
System::set_block_number(1);
|
||||
|
||||
@@ -207,10 +207,12 @@ pub mod pezpallet {
|
||||
let should_send = Self::choose_transaction_type(block_number);
|
||||
let res = match should_send {
|
||||
TransactionType::Signed => Self::fetch_price_and_send_signed(),
|
||||
TransactionType::UnsignedForAny =>
|
||||
Self::fetch_price_and_send_unsigned_for_any_account(block_number),
|
||||
TransactionType::UnsignedForAll =>
|
||||
Self::fetch_price_and_send_unsigned_for_all_accounts(block_number),
|
||||
TransactionType::UnsignedForAny => {
|
||||
Self::fetch_price_and_send_unsigned_for_any_account(block_number)
|
||||
},
|
||||
TransactionType::UnsignedForAll => {
|
||||
Self::fetch_price_and_send_unsigned_for_all_accounts(block_number)
|
||||
},
|
||||
TransactionType::Raw => Self::fetch_price_and_send_raw_unsigned(block_number),
|
||||
TransactionType::None => Ok(()),
|
||||
};
|
||||
@@ -403,8 +405,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
match last_send {
|
||||
// If we already have a value in storage and the block number is recent enough
|
||||
// we avoid sending another transaction at this time.
|
||||
Ok(Some(block)) if block_number < block + T::GracePeriod::get() =>
|
||||
Err(RECENTLY_SENT),
|
||||
Ok(Some(block)) if block_number < block + T::GracePeriod::get() => {
|
||||
Err(RECENTLY_SENT)
|
||||
},
|
||||
// In every other case we attempt to acquire the lock and send a transaction.
|
||||
_ => Ok(block_number),
|
||||
}
|
||||
|
||||
@@ -687,8 +687,8 @@ where
|
||||
// Check that `parent_hash` is correct.
|
||||
let n = *header.number();
|
||||
assert!(
|
||||
n > BlockNumberFor::<System>::zero() &&
|
||||
<pezframe_system::Pezpallet<System>>::block_hash(
|
||||
n > BlockNumberFor::<System>::zero()
|
||||
&& <pezframe_system::Pezpallet<System>>::block_hash(
|
||||
n - BlockNumberFor::<System>::one()
|
||||
) == *header.parent_hash(),
|
||||
"Parent hash should be valid.",
|
||||
|
||||
@@ -270,9 +270,9 @@ mod custom2 {
|
||||
// Inherent call is accepted for being dispatched
|
||||
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
|
||||
match call {
|
||||
Call::allowed_unsigned { .. } |
|
||||
Call::optional_inherent { .. } |
|
||||
Call::inherent { .. } => Ok(()),
|
||||
Call::allowed_unsigned { .. }
|
||||
| Call::optional_inherent { .. }
|
||||
| Call::inherent { .. } => Ok(()),
|
||||
_ => Err(UnknownTransaction::NoUnsignedValidator.into()),
|
||||
}
|
||||
}
|
||||
@@ -607,8 +607,8 @@ fn balance_transfer_dispatch_works() {
|
||||
.assimilate_storage(&mut t)
|
||||
.unwrap();
|
||||
let xt = UncheckedXt::new_signed(call_transfer(2, 69), 1, 1.into(), tx_ext(0, 0));
|
||||
let weight = xt.get_dispatch_info().total_weight() +
|
||||
<Runtime as pezframe_system::Config>::BlockWeights::get()
|
||||
let weight = xt.get_dispatch_info().total_weight()
|
||||
+ <Runtime as pezframe_system::Config>::BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.base_extrinsic;
|
||||
let fee: Balance =
|
||||
@@ -786,8 +786,8 @@ fn block_weight_limit_enforced() {
|
||||
// + extension weight
|
||||
// + extrinsic len
|
||||
Weight::from_parts(
|
||||
(transfer_weight.ref_time() + extension_weight.ref_time() + 5) *
|
||||
(nonce + 1),
|
||||
(transfer_weight.ref_time() + extension_weight.ref_time() + 5)
|
||||
* (nonce + 1),
|
||||
(nonce + 1) * encoded_len
|
||||
) + base_block_weight,
|
||||
);
|
||||
@@ -828,8 +828,8 @@ fn block_weight_and_size_is_stored_per_tx() {
|
||||
let mut t = new_test_ext(2);
|
||||
t.execute_with(|| {
|
||||
// Block execution weight + on_initialize weight from custom module
|
||||
let base_block_weight = Weight::from_parts(175, 0) +
|
||||
<Runtime as pezframe_system::Config>::BlockWeights::get().base_block;
|
||||
let base_block_weight = Weight::from_parts(175, 0)
|
||||
+ <Runtime as pezframe_system::Config>::BlockWeights::get().base_block;
|
||||
|
||||
Executive::initialize_block(&Header::new_from_number(1));
|
||||
|
||||
@@ -843,9 +843,9 @@ fn block_weight_and_size_is_stored_per_tx() {
|
||||
assert!(Executive::apply_extrinsic(x1.clone()).unwrap().is_ok());
|
||||
assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok());
|
||||
|
||||
let extrinsic_weight = transfer_weight +
|
||||
extension_weight +
|
||||
<Runtime as pezframe_system::Config>::BlockWeights::get()
|
||||
let extrinsic_weight = transfer_weight
|
||||
+ extension_weight
|
||||
+ <Runtime as pezframe_system::Config>::BlockWeights::get()
|
||||
.get(DispatchClass::Normal)
|
||||
.base_extrinsic;
|
||||
// Check we account for all extrinsic weight and their len.
|
||||
|
||||
@@ -531,8 +531,8 @@ pub mod pezpallet {
|
||||
let unchecked_eras_to_check = {
|
||||
// get the last available `bonding_duration` eras up to current era in reverse
|
||||
// order.
|
||||
let total_check_range = (current_era.saturating_sub(bonding_duration)..=
|
||||
current_era)
|
||||
let total_check_range = (current_era.saturating_sub(bonding_duration)
|
||||
..=current_era)
|
||||
.rev()
|
||||
.collect::<Vec<_>>();
|
||||
debug_assert!(
|
||||
@@ -608,7 +608,7 @@ pub mod pezpallet {
|
||||
);
|
||||
|
||||
match checked.try_extend(unchecked_eras_to_check.clone().into_iter()) {
|
||||
Ok(_) =>
|
||||
Ok(_) => {
|
||||
if stashes.is_empty() {
|
||||
Self::deposit_event(Event::<T>::BatchFinished { size: 0 });
|
||||
} else {
|
||||
@@ -616,7 +616,8 @@ pub mod pezpallet {
|
||||
Self::deposit_event(Event::<T>::BatchChecked {
|
||||
eras: unchecked_eras_to_check,
|
||||
});
|
||||
},
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
// don't put the head back in -- there is an internal error in the
|
||||
// pezpallet.
|
||||
|
||||
@@ -209,8 +209,8 @@ impl ExtBuilder {
|
||||
(VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA)
|
||||
.map(|v| {
|
||||
// for the sake of sanity, let's register this taker as an actual validator.
|
||||
let others = (NOMINATOR_PREFIX..
|
||||
(NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA))
|
||||
let others = (NOMINATOR_PREFIX
|
||||
..(NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA))
|
||||
.map(|n| IndividualExposure { who: n, value: 0 as Balance })
|
||||
.collect::<Vec<_>>();
|
||||
(v, Exposure { total: 0, own: 0, others })
|
||||
|
||||
@@ -213,8 +213,8 @@ where
|
||||
|
||||
// Check that the session id for the membership proof is within the
|
||||
// bounds of the set id reported in the equivocation.
|
||||
if session_index > set_id_session_index ||
|
||||
previous_set_id_session_index
|
||||
if session_index > set_id_session_index
|
||||
|| previous_set_id_session_index
|
||||
.map(|previous_index| session_index <= previous_index)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
|
||||
@@ -708,14 +708,16 @@ pub mod pezpallet {
|
||||
|
||||
let item = (reg_index, Judgement::FeePaid(registrar.fee));
|
||||
match id.judgements.binary_search_by_key(®_index, |x| x.0) {
|
||||
Ok(i) =>
|
||||
Ok(i) => {
|
||||
if id.judgements[i].1.is_sticky() {
|
||||
return Err(Error::<T>::StickyJudgement.into());
|
||||
} else {
|
||||
id.judgements[i] = item
|
||||
},
|
||||
Err(i) =>
|
||||
id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?,
|
||||
}
|
||||
},
|
||||
Err(i) => {
|
||||
id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?
|
||||
},
|
||||
}
|
||||
|
||||
T::Currency::reserve(&sender, registrar.fee)?;
|
||||
|
||||
@@ -274,42 +274,50 @@ pub mod v2 {
|
||||
// At first, migrate any authorities.
|
||||
None => Self::authority_step(None),
|
||||
// Migrate any remaining authorities.
|
||||
Some(MigrationState::Authority(maybe_last_authority)) =>
|
||||
Self::authority_step(Some(maybe_last_authority)),
|
||||
Some(MigrationState::Authority(maybe_last_authority)) => {
|
||||
Self::authority_step(Some(maybe_last_authority))
|
||||
},
|
||||
// After the last authority was migrated, start migrating usernames from
|
||||
// the former `AccountOfUsername` into `UsernameInfoOf`.
|
||||
Some(MigrationState::FinishedAuthorities) => Self::username_step(None),
|
||||
// Keep migrating usernames.
|
||||
Some(MigrationState::Username(maybe_last_username)) =>
|
||||
Self::username_step(Some(maybe_last_username)),
|
||||
Some(MigrationState::Username(maybe_last_username)) => {
|
||||
Self::username_step(Some(maybe_last_username))
|
||||
},
|
||||
// After the last username was migrated, start migrating all identities in
|
||||
// `IdentityOf`, which currently hold the primary username of the owner account
|
||||
// as well as any associated identity. Accounts which set a username but not an
|
||||
// identity also have a zero deposit identity stored, which will be removed.
|
||||
Some(MigrationState::FinishedUsernames) => Self::identity_step(None),
|
||||
// Keep migrating identities.
|
||||
Some(MigrationState::Identity(last_key)) =>
|
||||
Self::identity_step(Some(last_key.clone())),
|
||||
Some(MigrationState::Identity(last_key)) => {
|
||||
Self::identity_step(Some(last_key.clone()))
|
||||
},
|
||||
// After the last identity was migrated, start migrating usernames pending
|
||||
// approval from `PendingUsernames`.
|
||||
Some(MigrationState::FinishedIdentities) => Self::pending_username_step(None),
|
||||
// Keep migrating pending usernames.
|
||||
Some(MigrationState::PendingUsername(last_key)) =>
|
||||
Self::pending_username_step(Some(last_key.clone())),
|
||||
Some(MigrationState::PendingUsername(last_key)) => {
|
||||
Self::pending_username_step(Some(last_key.clone()))
|
||||
},
|
||||
// After the last pending username was migrated, start clearing the storage
|
||||
// previously associated with authorities in `UsernameAuthority`.
|
||||
Some(MigrationState::FinishedPendingUsernames) =>
|
||||
Self::cleanup_authority_step(None),
|
||||
Some(MigrationState::FinishedPendingUsernames) => {
|
||||
Self::cleanup_authority_step(None)
|
||||
},
|
||||
// Keep clearing the obsolete authority storage.
|
||||
Some(MigrationState::CleanupAuthorities(maybe_last_username)) =>
|
||||
Self::cleanup_authority_step(Some(maybe_last_username)),
|
||||
Some(MigrationState::CleanupAuthorities(maybe_last_username)) => {
|
||||
Self::cleanup_authority_step(Some(maybe_last_username))
|
||||
},
|
||||
// After the last obsolete authority was cleared from storage, start clearing
|
||||
// the storage previously associated with usernames in `AccountOfUsername`.
|
||||
Some(MigrationState::FinishedCleanupAuthorities) =>
|
||||
Self::cleanup_username_step(None),
|
||||
Some(MigrationState::FinishedCleanupAuthorities) => {
|
||||
Self::cleanup_username_step(None)
|
||||
},
|
||||
// Keep clearing the obsolete username storage.
|
||||
Some(MigrationState::CleanupUsernames(maybe_last_username)) =>
|
||||
Self::cleanup_username_step(Some(maybe_last_username)),
|
||||
Some(MigrationState::CleanupUsernames(maybe_last_username)) => {
|
||||
Self::cleanup_username_step(Some(maybe_last_username))
|
||||
},
|
||||
// After the last obsolete username was cleared from storage, the migration is
|
||||
// done.
|
||||
Some(MigrationState::Finished) => {
|
||||
@@ -428,16 +436,19 @@ pub mod v2 {
|
||||
) -> Weight {
|
||||
match step {
|
||||
MigrationState::Authority(_) => T::WeightInfo::migration_v2_authority_step(),
|
||||
MigrationState::FinishedAuthorities | MigrationState::Username(_) =>
|
||||
T::WeightInfo::migration_v2_username_step(),
|
||||
MigrationState::FinishedUsernames | MigrationState::Identity(_) =>
|
||||
T::WeightInfo::migration_v2_identity_step(),
|
||||
MigrationState::FinishedIdentities | MigrationState::PendingUsername(_) =>
|
||||
T::WeightInfo::migration_v2_pending_username_step(),
|
||||
MigrationState::FinishedPendingUsernames |
|
||||
MigrationState::CleanupAuthorities(_) => T::WeightInfo::migration_v2_cleanup_authority_step(),
|
||||
MigrationState::FinishedCleanupAuthorities |
|
||||
MigrationState::CleanupUsernames(_) => T::WeightInfo::migration_v2_cleanup_username_step(),
|
||||
MigrationState::FinishedAuthorities | MigrationState::Username(_) => {
|
||||
T::WeightInfo::migration_v2_username_step()
|
||||
},
|
||||
MigrationState::FinishedUsernames | MigrationState::Identity(_) => {
|
||||
T::WeightInfo::migration_v2_identity_step()
|
||||
},
|
||||
MigrationState::FinishedIdentities | MigrationState::PendingUsername(_) => {
|
||||
T::WeightInfo::migration_v2_pending_username_step()
|
||||
},
|
||||
MigrationState::FinishedPendingUsernames
|
||||
| MigrationState::CleanupAuthorities(_) => T::WeightInfo::migration_v2_cleanup_authority_step(),
|
||||
MigrationState::FinishedCleanupAuthorities
|
||||
| MigrationState::CleanupUsernames(_) => T::WeightInfo::migration_v2_cleanup_username_step(),
|
||||
MigrationState::Finished => Weight::zero(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,8 +185,8 @@ fn infoof_twenty() -> IdentityInfo<MaxAdditionalFields> {
|
||||
|
||||
fn id_deposit(id: &IdentityInfo<MaxAdditionalFields>) -> u64 {
|
||||
let base_deposit: u64 = <<Test as Config>::BasicDeposit as Get<u64>>::get();
|
||||
let byte_deposit: u64 = <<Test as Config>::ByteDeposit as Get<u64>>::get() *
|
||||
TryInto::<u64>::try_into(id.encoded_size()).unwrap();
|
||||
let byte_deposit: u64 = <<Test as Config>::ByteDeposit as Get<u64>>::get()
|
||||
* TryInto::<u64>::try_into(id.encoded_size()).unwrap();
|
||||
base_deposit + byte_deposit
|
||||
}
|
||||
|
||||
@@ -202,11 +202,11 @@ fn identity_fields_repr_works() {
|
||||
assert_eq!(IdentityField::Image as u64, 1 << 6);
|
||||
assert_eq!(IdentityField::Twitter as u64, 1 << 7);
|
||||
|
||||
let fields = IdentityField::Legal |
|
||||
IdentityField::Web |
|
||||
IdentityField::Riot |
|
||||
IdentityField::PgpFingerprint |
|
||||
IdentityField::Twitter;
|
||||
let fields = IdentityField::Legal
|
||||
| IdentityField::Web
|
||||
| IdentityField::Riot
|
||||
| IdentityField::PgpFingerprint
|
||||
| IdentityField::Twitter;
|
||||
|
||||
assert!(!fields.contains(IdentityField::Display));
|
||||
assert!(fields.contains(IdentityField::Legal));
|
||||
|
||||
@@ -293,8 +293,9 @@ impl<
|
||||
> Registration<Balance, MaxJudgements, IdentityInfo>
|
||||
{
|
||||
pub(crate) fn total_deposit(&self) -> Balance {
|
||||
self.deposit +
|
||||
self.judgements
|
||||
self.deposit
|
||||
+ self
|
||||
.judgements
|
||||
.iter()
|
||||
.map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() })
|
||||
.fold(Zero::zero(), |a, i| a + i)
|
||||
|
||||
@@ -532,8 +532,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
fn is_online_aux(authority_index: AuthIndex, authority: &ValidatorId<T>) -> bool {
|
||||
let current_session = T::ValidatorSet::session_index();
|
||||
|
||||
ReceivedHeartbeats::<T>::contains_key(current_session, authority_index) ||
|
||||
AuthoredBlocks::<T>::get(current_session, authority) != 0
|
||||
ReceivedHeartbeats::<T>::contains_key(current_session, authority_index)
|
||||
|| AuthoredBlocks::<T>::get(current_session, authority) != 0
|
||||
}
|
||||
|
||||
/// Returns `true` if a heartbeat has been received for the authority at `authority_index` in
|
||||
@@ -583,8 +583,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
// haven't sent an heartbeat yet we'll send one unconditionally. the idea is to prevent
|
||||
// all nodes from sending the heartbeats at the same block and causing a temporary (but
|
||||
// deterministic) spike in transactions.
|
||||
progress >= START_HEARTBEAT_FINAL_PERIOD ||
|
||||
progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress)
|
||||
progress >= START_HEARTBEAT_FINAL_PERIOD
|
||||
|| progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress)
|
||||
} else {
|
||||
// otherwise we fallback to using the block number calculated at the beginning
|
||||
// of the session that should roughly correspond to the middle of the session
|
||||
@@ -695,8 +695,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
// we will re-send it.
|
||||
match status {
|
||||
// we are still waiting for inclusion.
|
||||
Ok(Some(status)) if status.is_recent(session_index, now) =>
|
||||
Err(OffchainErr::WaitingForInclusion(status.sent_at)),
|
||||
Ok(Some(status)) if status.is_recent(session_index, now) => {
|
||||
Err(OffchainErr::WaitingForInclusion(status.sent_at))
|
||||
},
|
||||
// attempt to set new status
|
||||
_ => Ok(HeartbeatStatus { session_index, sent_at: now }),
|
||||
}
|
||||
|
||||
@@ -125,8 +125,9 @@ fn heartbeat(
|
||||
signature: signature.clone(),
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) =>
|
||||
"invalid validators len",
|
||||
TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => {
|
||||
"invalid validators len"
|
||||
},
|
||||
e @ _ => <&'static str>::from(e),
|
||||
})?;
|
||||
ImOnline::heartbeat(RuntimeOrigin::none(), heartbeat, signature)
|
||||
@@ -226,8 +227,9 @@ fn should_generate_heartbeats() {
|
||||
// check stuff about the transaction.
|
||||
let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap();
|
||||
let heartbeat = match ex.function {
|
||||
crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) =>
|
||||
heartbeat,
|
||||
crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => {
|
||||
heartbeat
|
||||
},
|
||||
e => panic!("Unexpected call: {:?}", e),
|
||||
};
|
||||
|
||||
@@ -340,8 +342,9 @@ fn should_not_send_a_report_if_already_online() {
|
||||
// check stuff about the transaction.
|
||||
let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap();
|
||||
let heartbeat = match ex.function {
|
||||
crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) =>
|
||||
heartbeat,
|
||||
crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => {
|
||||
heartbeat
|
||||
},
|
||||
e => panic!("Unexpected call: {:?}", e),
|
||||
};
|
||||
|
||||
|
||||
@@ -405,9 +405,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
leaves: Vec<LeafOf<T, I>>,
|
||||
proof: LeafProof<HashOf<T, I>>,
|
||||
) -> Result<(), Error> {
|
||||
if proof.leaf_count > NumberOfLeaves::<T, I>::get() ||
|
||||
proof.leaf_count == 0 ||
|
||||
proof.items.len().saturating_add(leaves.len()) as u64 > proof.leaf_count
|
||||
if proof.leaf_count > NumberOfLeaves::<T, I>::get()
|
||||
|| proof.leaf_count == 0
|
||||
|| proof.items.len().saturating_add(leaves.len()) as u64 > proof.leaf_count
|
||||
{
|
||||
return Err(
|
||||
Error::Verify.log_debug("The proof has incorrect number of leaves or proof items.")
|
||||
|
||||
@@ -989,9 +989,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
if let (Some(service_weight), Some(on_idle)) =
|
||||
(T::ServiceWeight::get(), T::IdleMaxServiceWeight::get())
|
||||
{
|
||||
if !(service_weight.all_gt(on_idle) ||
|
||||
on_idle.all_gt(service_weight) ||
|
||||
service_weight == on_idle)
|
||||
if !(service_weight.all_gt(on_idle)
|
||||
|| on_idle.all_gt(service_weight)
|
||||
|| service_weight == on_idle)
|
||||
{
|
||||
return Err("One of `ServiceWeight` or `IdleMaxServiceWeight` needs to be `all_gt` or both need to be equal.".into());
|
||||
}
|
||||
@@ -1096,8 +1096,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
page.peek_index(index.into() as usize).ok_or(Error::<T>::NoMessage)?;
|
||||
let payload_len = payload.len() as u64;
|
||||
ensure!(
|
||||
page_index < book_state.begin ||
|
||||
(page_index == book_state.begin && pos < page.first.into() as usize),
|
||||
page_index < book_state.begin
|
||||
|| (page_index == book_state.begin && pos < page.first.into() as usize),
|
||||
Error::<T>::Queued
|
||||
);
|
||||
ensure!(!is_processed, Error::<T>::AlreadyProcessed);
|
||||
@@ -1114,8 +1114,9 @@ impl<T: Config> Pezpallet<T> {
|
||||
// additional overweight event being deposited.
|
||||
) {
|
||||
Overweight | InsufficientWeight => Err(Error::<T>::InsufficientWeight),
|
||||
StackLimitReached | Unprocessable { permanent: false } =>
|
||||
Err(Error::<T>::TemporarilyUnprocessable),
|
||||
StackLimitReached | Unprocessable { permanent: false } => {
|
||||
Err(Error::<T>::TemporarilyUnprocessable)
|
||||
},
|
||||
Unprocessable { permanent: true } | Processed => {
|
||||
page.note_processed_at_pos(pos);
|
||||
book_state.message_count.saturating_dec();
|
||||
@@ -1657,7 +1658,7 @@ impl<T: Config> Pezpallet<T> {
|
||||
let (progressed, n) =
|
||||
Self::service_queue(next.clone(), &mut weight, overweight_limit);
|
||||
next = match n {
|
||||
Some(n) =>
|
||||
Some(n) => {
|
||||
if !progressed {
|
||||
if last_no_progress == Some(n.clone()) {
|
||||
break;
|
||||
@@ -1669,7 +1670,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
} else {
|
||||
last_no_progress = None;
|
||||
n
|
||||
},
|
||||
}
|
||||
},
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
@@ -1780,8 +1782,9 @@ impl<T: Config> ServiceQueues for Pezpallet<T> {
|
||||
Error::<T>::InsufficientWeight => ExecuteOverweightError::InsufficientWeight,
|
||||
Error::<T>::AlreadyProcessed => ExecuteOverweightError::AlreadyProcessed,
|
||||
Error::<T>::QueuePaused => ExecuteOverweightError::QueuePaused,
|
||||
Error::<T>::NoPage | Error::<T>::NoMessage | Error::<T>::Queued =>
|
||||
ExecuteOverweightError::NotFound,
|
||||
Error::<T>::NoPage | Error::<T>::NoMessage | Error::<T>::Queued => {
|
||||
ExecuteOverweightError::NotFound
|
||||
},
|
||||
Error::<T>::RecursiveDisallowed => ExecuteOverweightError::RecursiveDisallowed,
|
||||
_ => ExecuteOverweightError::Other,
|
||||
})
|
||||
|
||||
@@ -876,8 +876,8 @@ fn page_try_append_message_basic_works() {
|
||||
msgs += 1;
|
||||
}
|
||||
}
|
||||
let expected_msgs = (<Test as Config>::HeapSize::get()) /
|
||||
(ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u32 + 4);
|
||||
let expected_msgs = (<Test as Config>::HeapSize::get())
|
||||
/ (ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u32 + 4);
|
||||
assert_eq!(expected_msgs, msgs, "Wrong number of messages");
|
||||
assert_eq!(page.remaining, msgs);
|
||||
assert_eq!(page.remaining_size, msgs * 4);
|
||||
@@ -1441,8 +1441,8 @@ fn ready_ring_knit_and_unknit_works() {
|
||||
#[test]
|
||||
fn enqueue_message_works() {
|
||||
use MessageOrigin::*;
|
||||
let max_msg_per_page = <Test as Config>::HeapSize::get() as u64 /
|
||||
(ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u64 + 1);
|
||||
let max_msg_per_page = <Test as Config>::HeapSize::get() as u64
|
||||
/ (ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u64 + 1);
|
||||
|
||||
build_and_execute::<Test>(|| {
|
||||
// Enqueue messages which should fill three pages.
|
||||
@@ -1471,8 +1471,8 @@ fn enqueue_message_works() {
|
||||
#[test]
|
||||
fn enqueue_messages_works() {
|
||||
use MessageOrigin::*;
|
||||
let max_msg_per_page = <Test as Config>::HeapSize::get() as u64 /
|
||||
(ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u64 + 1);
|
||||
let max_msg_per_page = <Test as Config>::HeapSize::get() as u64
|
||||
/ (ItemHeader::<<Test as Config>::Size>::max_encoded_len() as u64 + 1);
|
||||
|
||||
build_and_execute::<Test>(|| {
|
||||
// Enqueue messages which should fill three pages.
|
||||
|
||||
@@ -272,16 +272,19 @@ pub fn set_status<T: Config<I>, I: 'static>(
|
||||
.expect("no bounty");
|
||||
|
||||
let new_status = match bounty.3 {
|
||||
BountyStatus::FundingAttempted { curator, .. } =>
|
||||
BountyStatus::FundingAttempted { payment_status: new_payment_status, curator },
|
||||
BountyStatus::RefundAttempted { curator, .. } =>
|
||||
BountyStatus::RefundAttempted { payment_status: new_payment_status, curator },
|
||||
BountyStatus::PayoutAttempted { curator, beneficiary, .. } =>
|
||||
BountyStatus::FundingAttempted { curator, .. } => {
|
||||
BountyStatus::FundingAttempted { payment_status: new_payment_status, curator }
|
||||
},
|
||||
BountyStatus::RefundAttempted { curator, .. } => {
|
||||
BountyStatus::RefundAttempted { payment_status: new_payment_status, curator }
|
||||
},
|
||||
BountyStatus::PayoutAttempted { curator, beneficiary, .. } => {
|
||||
BountyStatus::PayoutAttempted {
|
||||
payment_status: new_payment_status,
|
||||
curator,
|
||||
beneficiary,
|
||||
},
|
||||
}
|
||||
},
|
||||
_ => return Err(BenchmarkError::Stop("unexpected bounty status")),
|
||||
};
|
||||
|
||||
|
||||
@@ -663,8 +663,8 @@ pub mod pezpallet {
|
||||
Error::<T, I>::InvalidValue
|
||||
);
|
||||
ensure!(
|
||||
ChildBountiesPerParent::<T, I>::get(parent_bounty_id) <
|
||||
T::MaxActiveChildBountyCount::get() as u32,
|
||||
ChildBountiesPerParent::<T, I>::get(parent_bounty_id)
|
||||
< T::MaxActiveChildBountyCount::get() as u32,
|
||||
Error::<T, I>::TooManyChildBounties,
|
||||
);
|
||||
|
||||
@@ -898,8 +898,8 @@ pub mod pezpallet {
|
||||
// curator can unassign the child-/bounty curator.
|
||||
ensure!(
|
||||
maybe_sender.map_or(true, |sender| {
|
||||
sender == *curator ||
|
||||
parent_curator
|
||||
sender == *curator
|
||||
|| parent_curator
|
||||
.map_or(false, |parent_curator| sender == parent_curator)
|
||||
}),
|
||||
BadOrigin
|
||||
@@ -1070,8 +1070,9 @@ pub mod pezpallet {
|
||||
Self::get_bounty_details(parent_bounty_id, child_bounty_id)?;
|
||||
|
||||
let maybe_curator = match status {
|
||||
BountyStatus::Funded { curator } | BountyStatus::Active { curator, .. } =>
|
||||
Some(curator),
|
||||
BountyStatus::Funded { curator } | BountyStatus::Active { curator, .. } => {
|
||||
Some(curator)
|
||||
},
|
||||
BountyStatus::CuratorUnassigned => None,
|
||||
_ => return Err(Error::<T, I>::UnexpectedStatus.into()),
|
||||
};
|
||||
@@ -1174,13 +1175,14 @@ pub mod pezpallet {
|
||||
|
||||
let new_status = match new_payment_status {
|
||||
PaymentState::Succeeded => match (child_bounty_id, parent_curator) {
|
||||
(Some(_), Some(parent_curator)) if curator == parent_curator =>
|
||||
BountyStatus::Active { curator },
|
||||
(Some(_), Some(parent_curator)) if curator == parent_curator => {
|
||||
BountyStatus::Active { curator }
|
||||
},
|
||||
_ => BountyStatus::Funded { curator },
|
||||
},
|
||||
PaymentState::Pending |
|
||||
PaymentState::Failed |
|
||||
PaymentState::Attempted { .. } => BountyStatus::FundingAttempted {
|
||||
PaymentState::Pending
|
||||
| PaymentState::Failed
|
||||
| PaymentState::Attempted { .. } => BountyStatus::FundingAttempted {
|
||||
payment_status: new_payment_status,
|
||||
curator,
|
||||
},
|
||||
@@ -1220,9 +1222,9 @@ pub mod pezpallet {
|
||||
Self::remove_bounty(parent_bounty_id, child_bounty_id, metadata);
|
||||
return Ok(Pays::No.into());
|
||||
},
|
||||
PaymentState::Pending |
|
||||
PaymentState::Failed |
|
||||
PaymentState::Attempted { .. } => BountyStatus::RefundAttempted {
|
||||
PaymentState::Pending
|
||||
| PaymentState::Failed
|
||||
| PaymentState::Attempted { .. } => BountyStatus::RefundAttempted {
|
||||
payment_status: new_payment_status,
|
||||
curator: curator.clone(),
|
||||
},
|
||||
@@ -1256,9 +1258,9 @@ pub mod pezpallet {
|
||||
Self::remove_bounty(parent_bounty_id, child_bounty_id, metadata);
|
||||
return Ok(Pays::No.into());
|
||||
},
|
||||
PaymentState::Pending |
|
||||
PaymentState::Failed |
|
||||
PaymentState::Attempted { .. } => BountyStatus::PayoutAttempted {
|
||||
PaymentState::Pending
|
||||
| PaymentState::Failed
|
||||
| PaymentState::Attempted { .. } => BountyStatus::PayoutAttempted {
|
||||
curator: curator.clone(),
|
||||
beneficiary: beneficiary.clone(),
|
||||
payment_status: new_payment_status.clone(),
|
||||
@@ -1629,8 +1631,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
});
|
||||
Ok(PaymentState::Succeeded)
|
||||
},
|
||||
PaymentStatus::InProgress | PaymentStatus::Unknown =>
|
||||
return Err(Error::<T, I>::FundingInconclusive.into()),
|
||||
PaymentStatus::InProgress | PaymentStatus::Unknown => {
|
||||
return Err(Error::<T, I>::FundingInconclusive.into())
|
||||
},
|
||||
PaymentStatus::Failure => {
|
||||
Self::deposit_event(Event::<T, I>::PaymentFailed {
|
||||
index: parent_bounty_id,
|
||||
@@ -1697,7 +1700,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
},
|
||||
PaymentStatus::InProgress | PaymentStatus::Unknown =>
|
||||
// nothing new to report
|
||||
Err(Error::<T, I>::RefundInconclusive.into()),
|
||||
{
|
||||
Err(Error::<T, I>::RefundInconclusive.into())
|
||||
},
|
||||
PaymentStatus::Failure => {
|
||||
// assume payment has failed, allow user to retry
|
||||
Self::deposit_event(Event::<T, I>::PaymentFailed {
|
||||
@@ -1727,8 +1732,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
|
||||
let source = match child_bounty_id {
|
||||
None => Self::bounty_account(parent_bounty_id, asset_kind.clone())?,
|
||||
Some(child_bounty_id) =>
|
||||
Self::child_bounty_account(parent_bounty_id, child_bounty_id, asset_kind.clone())?,
|
||||
Some(child_bounty_id) => {
|
||||
Self::child_bounty_account(parent_bounty_id, child_bounty_id, asset_kind.clone())?
|
||||
},
|
||||
};
|
||||
|
||||
let id = <T as Config<I>>::Paymaster::pay(&source, &beneficiary, asset_kind, payout)
|
||||
@@ -1771,7 +1777,9 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
},
|
||||
PaymentStatus::InProgress | PaymentStatus::Unknown =>
|
||||
// nothing new to report
|
||||
Err(Error::<T, I>::PayoutInconclusive.into()),
|
||||
{
|
||||
Err(Error::<T, I>::PayoutInconclusive.into())
|
||||
},
|
||||
PaymentStatus::Failure => {
|
||||
// assume payment has failed, allow user to retry
|
||||
Self::deposit_event(Event::<T, I>::PaymentFailed {
|
||||
|
||||
@@ -99,8 +99,8 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
|
||||
let mut deposit = Zero::zero();
|
||||
// disabled DepositRequired setting only affects the CollectionOwner namespace
|
||||
if collection_config.is_setting_enabled(CollectionSetting::DepositRequired) ||
|
||||
namespace != AttributeNamespace::CollectionOwner
|
||||
if collection_config.is_setting_enabled(CollectionSetting::DepositRequired)
|
||||
|| namespace != AttributeNamespace::CollectionOwner
|
||||
{
|
||||
deposit = T::DepositPerByte::get()
|
||||
.saturating_mul(((key.len() + value.len()) as u32).into())
|
||||
@@ -461,19 +461,22 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
) -> Result<bool, DispatchError> {
|
||||
let mut result = false;
|
||||
match namespace {
|
||||
AttributeNamespace::CollectionOwner =>
|
||||
result = Self::has_role(&collection, &origin, CollectionRole::Admin),
|
||||
AttributeNamespace::ItemOwner =>
|
||||
AttributeNamespace::CollectionOwner => {
|
||||
result = Self::has_role(&collection, &origin, CollectionRole::Admin)
|
||||
},
|
||||
AttributeNamespace::ItemOwner => {
|
||||
if let Some(item) = maybe_item {
|
||||
let item_details =
|
||||
Item::<T, I>::get(&collection, &item).ok_or(Error::<T, I>::UnknownItem)?;
|
||||
result = origin == &item_details.owner
|
||||
},
|
||||
AttributeNamespace::Account(account_id) =>
|
||||
}
|
||||
},
|
||||
AttributeNamespace::Account(account_id) => {
|
||||
if let Some(item) = maybe_item {
|
||||
let approvals = ItemAttributesApprovalsOf::<T, I>::get(&collection, &item);
|
||||
result = account_id == origin && approvals.contains(&origin)
|
||||
},
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
};
|
||||
Ok(result)
|
||||
|
||||
@@ -253,8 +253,8 @@ impl<T: Config<I>, I: 'static> Pezpallet<T, I> {
|
||||
let collection_config = Self::get_collection_config(&collection)?;
|
||||
|
||||
ensure!(
|
||||
maybe_check_origin.is_none() ||
|
||||
collection_config.is_setting_enabled(CollectionSetting::UnlockedMetadata),
|
||||
maybe_check_origin.is_none()
|
||||
|| collection_config.is_setting_enabled(CollectionSetting::UnlockedMetadata),
|
||||
Error::<T, I>::LockedCollectionMetadata
|
||||
);
|
||||
|
||||
|
||||
@@ -128,9 +128,11 @@ impl<T: Config<I>, I: 'static> Inspect<<T as SystemConfig>::AccountId> for Pezpa
|
||||
ItemConfigOf::<T, I>::get(collection, item),
|
||||
) {
|
||||
(Some(cc), Some(ic))
|
||||
if cc.is_setting_enabled(CollectionSetting::TransferableItems) &&
|
||||
ic.is_setting_enabled(ItemSetting::Transferable) =>
|
||||
true,
|
||||
if cc.is_setting_enabled(CollectionSetting::TransferableItems)
|
||||
&& ic.is_setting_enabled(ItemSetting::Transferable) =>
|
||||
{
|
||||
true
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1443,8 +1443,9 @@ pub mod pezpallet {
|
||||
) -> DispatchResult {
|
||||
let origin = ensure_signed(origin)?;
|
||||
let depositor = match namespace {
|
||||
AttributeNamespace::CollectionOwner =>
|
||||
Self::collection_owner(collection).ok_or(Error::<T, I>::UnknownCollection)?,
|
||||
AttributeNamespace::CollectionOwner => {
|
||||
Self::collection_owner(collection).ok_or(Error::<T, I>::UnknownCollection)?
|
||||
},
|
||||
_ => origin.clone(),
|
||||
};
|
||||
Self::do_set_attribute(origin, collection, maybe_item, namespace, key, value, depositor)
|
||||
|
||||
@@ -3114,9 +3114,9 @@ fn collection_locking_should_work() {
|
||||
|
||||
let stored_config = CollectionConfigOf::<Test>::get(collection_id).unwrap();
|
||||
let full_lock_config = collection_config_from_disabled_settings(
|
||||
CollectionSetting::TransferableItems |
|
||||
CollectionSetting::UnlockedMetadata |
|
||||
CollectionSetting::UnlockedAttributes,
|
||||
CollectionSetting::TransferableItems
|
||||
| CollectionSetting::UnlockedMetadata
|
||||
| CollectionSetting::UnlockedAttributes,
|
||||
);
|
||||
assert_eq!(stored_config, full_lock_config);
|
||||
});
|
||||
|
||||
@@ -1071,10 +1071,10 @@ pub mod pezpallet {
|
||||
let expiry = now.saturating_add(T::BasePeriod::get().saturating_mul(duration.into()));
|
||||
let mut count = 0;
|
||||
|
||||
while count < max_bids &&
|
||||
!queue.is_empty() &&
|
||||
!remaining.is_zero() &&
|
||||
weight.check_accrue(T::WeightInfo::process_bid())
|
||||
while count < max_bids
|
||||
&& !queue.is_empty()
|
||||
&& !remaining.is_zero()
|
||||
&& weight.check_accrue(T::WeightInfo::process_bid())
|
||||
{
|
||||
let bid = match queue.pop() {
|
||||
Some(b) => b,
|
||||
|
||||
@@ -718,9 +718,9 @@ fn multiple_thaws_works_in_alternative_thaw_order() {
|
||||
fn enlargement_to_target_works() {
|
||||
new_test_ext().execute_with(|| {
|
||||
System::run_to_block::<AllPalletsWithSystem>(2);
|
||||
let w = <() as WeightInfo>::process_queues() +
|
||||
<() as WeightInfo>::process_queue() +
|
||||
(<() as WeightInfo>::process_bid() * 2);
|
||||
let w = <() as WeightInfo>::process_queues()
|
||||
+ <() as WeightInfo>::process_queue()
|
||||
+ (<() as WeightInfo>::process_bid() * 2);
|
||||
super::mock::MaxIntakeWeight::set(w);
|
||||
assert_ok!(Nis::place_bid(signed(1), 40, 1));
|
||||
assert_ok!(Nis::place_bid(signed(1), 40, 2));
|
||||
|
||||
@@ -349,8 +349,8 @@ mod benchmarks {
|
||||
|
||||
// commission of 50% deducted here.
|
||||
assert!(
|
||||
T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) >=
|
||||
scenario.dest_weight / 2u32.into()
|
||||
T::StakeAdapter::active_stake(Pool::from(scenario.origin1))
|
||||
>= scenario.dest_weight / 2u32.into()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -989,8 +989,8 @@ mod benchmarks {
|
||||
assert_eq!(PoolMembers::<T>::get(&depositor).unwrap().total_balance(), deposit_amount);
|
||||
// verify delegated balance.
|
||||
assert!(
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) ==
|
||||
Some(deposit_amount),
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone()))
|
||||
== Some(deposit_amount),
|
||||
);
|
||||
|
||||
// ugly type conversion between balances of pezpallet staking and pools (which really are
|
||||
@@ -1013,8 +1013,8 @@ mod benchmarks {
|
||||
);
|
||||
// verify delegated balance are not yet slashed.
|
||||
assert!(
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) ==
|
||||
Some(deposit_amount),
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone()))
|
||||
== Some(deposit_amount),
|
||||
);
|
||||
|
||||
// Fill member's sub pools for the worst case.
|
||||
@@ -1049,8 +1049,8 @@ mod benchmarks {
|
||||
deposit_amount / 2u32.into()
|
||||
);
|
||||
assert!(
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) ==
|
||||
Some(deposit_amount / 2u32.into()),
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone()))
|
||||
== Some(deposit_amount / 2u32.into()),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1168,8 +1168,8 @@ mod benchmarks {
|
||||
}
|
||||
// verify balances once more.
|
||||
assert!(
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) ==
|
||||
Some(deposit_amount),
|
||||
T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone()))
|
||||
== Some(deposit_amount),
|
||||
);
|
||||
assert_eq!(PoolMembers::<T>::get(&depositor).unwrap().total_balance(), deposit_amount);
|
||||
}
|
||||
|
||||
@@ -267,8 +267,8 @@ fn main() {
|
||||
}
|
||||
|
||||
// execute sanity checks at a fixed interval, possibly on every block.
|
||||
if iteration %
|
||||
(std::env::var("SANITY_CHECK_INTERVAL")
|
||||
if iteration
|
||||
% (std::env::var("SANITY_CHECK_INTERVAL")
|
||||
.ok()
|
||||
.and_then(|x| x.parse::<u64>().ok()))
|
||||
.unwrap_or(1) == 0
|
||||
|
||||
@@ -644,9 +644,10 @@ impl<T: Config> PoolMember<T> {
|
||||
) -> Result<(), Error<T>> {
|
||||
if let Some(new_points) = self.points.checked_sub(&points_dissolved) {
|
||||
match self.unbonding_eras.get_mut(&unbonding_era) {
|
||||
Some(already_unbonding_points) =>
|
||||
Some(already_unbonding_points) => {
|
||||
*already_unbonding_points =
|
||||
already_unbonding_points.saturating_add(points_issued),
|
||||
already_unbonding_points.saturating_add(points_issued)
|
||||
},
|
||||
None => self
|
||||
.unbonding_eras
|
||||
.try_insert(unbonding_era, points_issued)
|
||||
@@ -1138,8 +1139,8 @@ impl<T: Config> BondedPool<T> {
|
||||
}
|
||||
|
||||
fn can_nominate(&self, who: &T::AccountId) -> bool {
|
||||
self.is_root(who) ||
|
||||
self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who)
|
||||
self.is_root(who)
|
||||
|| self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who)
|
||||
}
|
||||
|
||||
fn can_kick(&self, who: &T::AccountId) -> bool {
|
||||
@@ -1246,9 +1247,9 @@ impl<T: Config> BondedPool<T> {
|
||||
|
||||
// any unbond must comply with the balance condition:
|
||||
ensure!(
|
||||
is_full_unbond ||
|
||||
balance_after_unbond >=
|
||||
if is_depositor {
|
||||
is_full_unbond
|
||||
|| balance_after_unbond
|
||||
>= if is_depositor {
|
||||
Pezpallet::<T>::depositor_min_bond()
|
||||
} else {
|
||||
MinJoinBond::<T>::get()
|
||||
@@ -2876,8 +2877,8 @@ pub mod pezpallet {
|
||||
.ok_or(Error::<T>::PoolMemberNotFound)?
|
||||
.active_points();
|
||||
|
||||
if bonded_pool.points_to_balance(depositor_points) >=
|
||||
T::StakeAdapter::minimum_nominator_bond()
|
||||
if bonded_pool.points_to_balance(depositor_points)
|
||||
>= T::StakeAdapter::minimum_nominator_bond()
|
||||
{
|
||||
ensure!(bonded_pool.can_nominate(&who), Error::<T>::NotNominator);
|
||||
}
|
||||
@@ -3246,8 +3247,8 @@ pub mod pezpallet {
|
||||
// ensure pool exists.
|
||||
let bonded_pool = BondedPool::<T>::get(pool_id).ok_or(Error::<T>::PoolNotFound)?;
|
||||
ensure!(
|
||||
T::StakeAdapter::pool_strategy(Pool::from(bonded_pool.bonded_account())) ==
|
||||
adapter::StakeStrategyType::Transfer,
|
||||
T::StakeAdapter::pool_strategy(Pool::from(bonded_pool.bonded_account()))
|
||||
== adapter::StakeStrategyType::Transfer,
|
||||
Error::<T>::AlreadyMigrated
|
||||
);
|
||||
|
||||
@@ -3620,10 +3621,12 @@ impl<T: Config> Pezpallet<T> {
|
||||
)?;
|
||||
|
||||
let (points_issued, bonded) = match extra {
|
||||
BondExtra::FreeBalance(amount) =>
|
||||
(bonded_pool.try_bond_funds(&member_account, amount, BondType::Extra)?, amount),
|
||||
BondExtra::Rewards =>
|
||||
(bonded_pool.try_bond_funds(&member_account, claimed, BondType::Extra)?, claimed),
|
||||
BondExtra::FreeBalance(amount) => {
|
||||
(bonded_pool.try_bond_funds(&member_account, amount, BondType::Extra)?, amount)
|
||||
},
|
||||
BondExtra::Rewards => {
|
||||
(bonded_pool.try_bond_funds(&member_account, claimed, BondType::Extra)?, claimed)
|
||||
},
|
||||
};
|
||||
|
||||
bonded_pool.ok_to_be_open()?;
|
||||
@@ -3776,8 +3779,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
) -> Result<BalanceOf<T>, DispatchError> {
|
||||
// only executed in tests: ensure the member account is correct.
|
||||
debug_assert!(
|
||||
PoolMembers::<T>::get(member_account.clone().get()).expect("member must exist") ==
|
||||
pool_member
|
||||
PoolMembers::<T>::get(member_account.clone().get()).expect("member must exist")
|
||||
== pool_member
|
||||
);
|
||||
|
||||
let pool_account = Pezpallet::<T>::generate_bonded_account(pool_member.pool_id);
|
||||
@@ -3879,8 +3882,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
|
||||
for id in reward_pools {
|
||||
let account = Self::generate_reward_account(id);
|
||||
if T::Currency::reducible_balance(&account, Preservation::Expendable, Fortitude::Polite) <
|
||||
T::Currency::minimum_balance()
|
||||
if T::Currency::reducible_balance(&account, Preservation::Expendable, Fortitude::Polite)
|
||||
< T::Currency::minimum_balance()
|
||||
{
|
||||
log!(
|
||||
warn,
|
||||
@@ -3925,8 +3928,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
RewardPools::<T>::iter_keys().try_for_each(|id| -> Result<(), TryRuntimeError> {
|
||||
// the sum of the pending rewards must be less than the leftover balance. Since the
|
||||
// reward math rounds down, we might accumulate some dust here.
|
||||
let pending_rewards_lt_leftover_bal = RewardPool::<T>::current_balance(id) >=
|
||||
pools_members_pending_rewards.get(&id).copied().unwrap_or_default();
|
||||
let pending_rewards_lt_leftover_bal = RewardPool::<T>::current_balance(id)
|
||||
>= pools_members_pending_rewards.get(&id).copied().unwrap_or_default();
|
||||
|
||||
// If this happens, this is most likely due to an old bug and not a recent code change.
|
||||
// We warn about this in try-runtime checks but do not panic.
|
||||
@@ -3958,8 +3961,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
|
||||
let depositor = PoolMembers::<T>::get(&bonded_pool.roles.depositor).unwrap();
|
||||
let depositor_has_enough_stake = bonded_pool
|
||||
.is_destroying_and_only_depositor(depositor.active_points()) ||
|
||||
depositor.active_points() >= MinCreateBond::<T>::get();
|
||||
.is_destroying_and_only_depositor(depositor.active_points())
|
||||
|| depositor.active_points() >= MinCreateBond::<T>::get();
|
||||
if !depositor_has_enough_stake {
|
||||
log!(
|
||||
warn,
|
||||
@@ -4162,8 +4165,8 @@ impl<T: Config> Pezpallet<T> {
|
||||
let pool_account = Self::generate_bonded_account(pool_id);
|
||||
|
||||
// true if pool is still not migrated to `DelegateStake`.
|
||||
T::StakeAdapter::pool_strategy(Pool::from(pool_account)) !=
|
||||
adapter::StakeStrategyType::Delegate
|
||||
T::StakeAdapter::pool_strategy(Pool::from(pool_account))
|
||||
!= adapter::StakeStrategyType::Delegate
|
||||
}
|
||||
|
||||
/// Checks whether member delegation needs to be migrated to
|
||||
|
||||
@@ -134,8 +134,8 @@ pub mod unversioned {
|
||||
let pool_acc = Pezpallet::<T>::generate_bonded_account(id);
|
||||
|
||||
// only migrate if the pool is in Transfer Strategy.
|
||||
if T::StakeAdapter::pool_strategy(Pool::from(pool_acc)) ==
|
||||
adapter::StakeStrategyType::Transfer
|
||||
if T::StakeAdapter::pool_strategy(Pool::from(pool_acc))
|
||||
== adapter::StakeStrategyType::Transfer
|
||||
{
|
||||
let _ = Pezpallet::<T>::migrate_to_delegate_stake(id).map_err(|err| {
|
||||
log!(
|
||||
@@ -198,8 +198,8 @@ pub mod unversioned {
|
||||
BondedPools::<T>::iter_keys().take(MaxPools::get() as usize).enumerate()
|
||||
{
|
||||
let pool_account = Pezpallet::<T>::generate_bonded_account(id);
|
||||
if T::StakeAdapter::pool_strategy(Pool::from(pool_account.clone())) ==
|
||||
adapter::StakeStrategyType::Transfer
|
||||
if T::StakeAdapter::pool_strategy(Pool::from(pool_account.clone()))
|
||||
== adapter::StakeStrategyType::Transfer
|
||||
{
|
||||
log!(error, "Pool {} failed to migrate", id,);
|
||||
return Err(TryRuntimeError::Other("Pool failed to migrate"));
|
||||
@@ -518,8 +518,8 @@ pub mod v5 {
|
||||
"There are undecodable BondedPools in storage. This migration will not fix that."
|
||||
);
|
||||
ensure!(
|
||||
SubPoolsStorage::<T>::iter_keys().count() ==
|
||||
SubPoolsStorage::<T>::iter_values().count(),
|
||||
SubPoolsStorage::<T>::iter_keys().count()
|
||||
== SubPoolsStorage::<T>::iter_values().count(),
|
||||
"There are undecodable SubPools in storage. This migration will not fix that."
|
||||
);
|
||||
ensure!(
|
||||
@@ -552,10 +552,10 @@ pub mod v5 {
|
||||
// `total_commission_claimed` field.
|
||||
ensure!(
|
||||
RewardPools::<T>::iter().all(|(_, reward_pool)| reward_pool
|
||||
.total_commission_pending >=
|
||||
Zero::zero() && reward_pool
|
||||
.total_commission_claimed >=
|
||||
Zero::zero()),
|
||||
.total_commission_pending
|
||||
>= Zero::zero() && reward_pool
|
||||
.total_commission_claimed
|
||||
>= Zero::zero()),
|
||||
"a commission value has been incorrectly set"
|
||||
);
|
||||
ensure!(
|
||||
@@ -573,8 +573,8 @@ pub mod v5 {
|
||||
"There are undecodable BondedPools in storage."
|
||||
);
|
||||
ensure!(
|
||||
SubPoolsStorage::<T>::iter_keys().count() ==
|
||||
SubPoolsStorage::<T>::iter_values().count(),
|
||||
SubPoolsStorage::<T>::iter_keys().count()
|
||||
== SubPoolsStorage::<T>::iter_values().count(),
|
||||
"There are undecodable SubPools in storage."
|
||||
);
|
||||
ensure!(
|
||||
|
||||
@@ -171,8 +171,8 @@ impl pezsp_staking::StakingInterface for StakingMock {
|
||||
DelegateMock::on_withdraw(who, withdraw_amount);
|
||||
|
||||
UnbondingBalanceMap::set(&unbonding_map);
|
||||
Ok(UnbondingBalanceMap::get().get(&who).unwrap().is_empty() &&
|
||||
BondedBalanceMap::get().get(&who).unwrap().is_zero())
|
||||
Ok(UnbondingBalanceMap::get().get(&who).unwrap().is_empty()
|
||||
&& BondedBalanceMap::get().get(&who).unwrap().is_zero())
|
||||
}
|
||||
|
||||
fn bond(stash: &Self::AccountId, value: Self::Balance, _: &Self::AccountId) -> DispatchResult {
|
||||
|
||||
@@ -190,7 +190,13 @@ impl pezpallet_nomination_pools::adapter::StakeStrategy for MockAdapter {
|
||||
bond_type: BondType,
|
||||
) -> DispatchResult {
|
||||
if LegacyAdapter::get() {
|
||||
return TransferStake::pledge_bond(who, pool_account, reward_account, amount, bond_type);
|
||||
return TransferStake::pledge_bond(
|
||||
who,
|
||||
pool_account,
|
||||
reward_account,
|
||||
amount,
|
||||
bond_type,
|
||||
);
|
||||
}
|
||||
DelegateStake::pledge_bond(who, pool_account, reward_account, amount, bond_type)
|
||||
}
|
||||
|
||||
@@ -318,8 +318,8 @@ impl<T: Config> TransactionExtension<T::RuntimeCall> for RestrictOrigin<T> {
|
||||
Usages::<T>::insert(&entity, &usage);
|
||||
|
||||
let allowed_one_time_excess = || {
|
||||
usage_without_new_xt == 0u32.into() &&
|
||||
T::OperationAllowedOneTimeExcess::contains(&entity, call)
|
||||
usage_without_new_xt == 0u32.into()
|
||||
&& T::OperationAllowedOneTimeExcess::contains(&entity, call)
|
||||
};
|
||||
if usage.used <= allowance.max || allowed_one_time_excess() {
|
||||
Ok((ValidTransaction::default(), Val::Charge { fee, entity }, origin))
|
||||
@@ -350,7 +350,7 @@ impl<T: Config> TransactionExtension<T::RuntimeCall> for RestrictOrigin<T> {
|
||||
_result: &DispatchResult,
|
||||
) -> Result<Weight, TransactionValidityError> {
|
||||
match pre {
|
||||
Pre::Charge { fee, entity } =>
|
||||
Pre::Charge { fee, entity } => {
|
||||
if post_info.pays_fee == Pays::No {
|
||||
Usages::<T>::mutate_exists(entity, |maybe_usage| {
|
||||
if let Some(usage) = maybe_usage {
|
||||
@@ -364,7 +364,8 @@ impl<T: Config> TransactionExtension<T::RuntimeCall> for RestrictOrigin<T> {
|
||||
Ok(Weight::zero())
|
||||
} else {
|
||||
Ok(Weight::zero())
|
||||
},
|
||||
}
|
||||
},
|
||||
Pre::NoCharge { refund } => Ok(refund),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,10 +141,12 @@ impl RestrictedEntity<OriginCaller, u64> for RuntimeRestrictedEntity {
|
||||
|
||||
fn restricted_entity(caller: &OriginCaller) -> Option<RuntimeRestrictedEntity> {
|
||||
match caller {
|
||||
OriginCaller::system(pezframe_system::Origin::<Test>::Signed(RESTRICTED_ORIGIN_1)) =>
|
||||
Some(RuntimeRestrictedEntity::A),
|
||||
OriginCaller::system(pezframe_system::Origin::<Test>::Signed(RESTRICTED_ORIGIN_2)) =>
|
||||
Some(RuntimeRestrictedEntity::B),
|
||||
OriginCaller::system(pezframe_system::Origin::<Test>::Signed(RESTRICTED_ORIGIN_1)) => {
|
||||
Some(RuntimeRestrictedEntity::A)
|
||||
},
|
||||
OriginCaller::system(pezframe_system::Origin::<Test>::Signed(RESTRICTED_ORIGIN_2)) => {
|
||||
Some(RuntimeRestrictedEntity::B)
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +113,9 @@ mod custom_origin {
|
||||
}
|
||||
|
||||
match key {
|
||||
RuntimeParametersKey::SomEWeirdSPElLInGS(_) |
|
||||
RuntimeParametersKey::Nis(_) |
|
||||
RuntimeParametersKey::Pallet1(_) => ensure_root(origin.clone()),
|
||||
RuntimeParametersKey::SomEWeirdSPElLInGS(_)
|
||||
| RuntimeParametersKey::Nis(_)
|
||||
| RuntimeParametersKey::Pallet1(_) => ensure_root(origin.clone()),
|
||||
RuntimeParametersKey::Pallet2(_) => ensure_signed(origin.clone()).map(|_| ()),
|
||||
}
|
||||
.map_err(|_| origin)
|
||||
|
||||
@@ -118,17 +118,21 @@ impl<T: Config + Send + Sync> TransactionExtension<<T as pezframe_system::Config
|
||||
// Extension is passthrough
|
||||
None => Weight::zero(),
|
||||
// Alias with existing account
|
||||
Some(AsPersonInfo::AsPersonalAliasWithAccount(_)) =>
|
||||
T::WeightInfo::as_person_alias_with_account(),
|
||||
Some(AsPersonInfo::AsPersonalAliasWithAccount(_)) => {
|
||||
T::WeightInfo::as_person_alias_with_account()
|
||||
},
|
||||
// Alias with proof
|
||||
Some(AsPersonInfo::AsPersonalAliasWithProof(_, _, _)) =>
|
||||
T::WeightInfo::as_person_alias_with_proof(),
|
||||
Some(AsPersonInfo::AsPersonalAliasWithProof(_, _, _)) => {
|
||||
T::WeightInfo::as_person_alias_with_proof()
|
||||
},
|
||||
// Personal Identity with proof
|
||||
Some(AsPersonInfo::AsPersonalIdentityWithProof(_, _)) =>
|
||||
T::WeightInfo::as_person_identity_with_proof(),
|
||||
Some(AsPersonInfo::AsPersonalIdentityWithProof(_, _)) => {
|
||||
T::WeightInfo::as_person_identity_with_proof()
|
||||
},
|
||||
// Personal Identity with existing account
|
||||
Some(AsPersonInfo::AsPersonalIdentityWithAccount(_)) =>
|
||||
T::WeightInfo::as_person_identity_with_account(),
|
||||
Some(AsPersonInfo::AsPersonalIdentityWithAccount(_)) => {
|
||||
T::WeightInfo::as_person_identity_with_account()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,8 +303,9 @@ impl<T: Config + Send + Sync> TransactionExtension<<T as pezframe_system::Config
|
||||
_len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
match val {
|
||||
Val::UsingAccount(who, nonce) =>
|
||||
CheckNonce::<T>::prepare_nonce_for_account(&who, nonce)?,
|
||||
Val::UsingAccount(who, nonce) => {
|
||||
CheckNonce::<T>::prepare_nonce_for_account(&who, nonce)?
|
||||
},
|
||||
Val::NotUsing | Val::UsingProof => (),
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user