cargo +nightly fmt (#3540)

* cargo +nightly fmt

* add cargo-fmt check to ci

* update ci

* fmt

* fmt

* skip macro

* ignore bridges
This commit is contained in:
Shawn Tabrizi
2021-08-02 12:47:33 +02:00
committed by GitHub
parent 30e3012270
commit ff5d56fb76
350 changed files with 20617 additions and 21266 deletions
@@ -18,11 +18,11 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub use sp_std::{result, ops::Add, convert::TryInto};
pub use sp_runtime::traits::CheckedSub;
pub use parity_scale_codec::{Encode, Decode};
pub use paste;
pub use enumn::N;
pub use parity_scale_codec::{Decode, Encode};
pub use paste;
pub use sp_runtime::traits::CheckedSub;
pub use sp_std::{convert::TryInto, ops::Add, result};
/// This macro generates a `SlotRange` enum of arbitrary length for use in the Slot Auction
/// mechanism on Polkadot.
File diff suppressed because it is too large Load Diff
+300 -120
View File
@@ -16,24 +16,31 @@
//! Pallet to process claims from Ethereum addresses.
use sp_std::{prelude::*, fmt::Debug};
use sp_io::{hashing::keccak_256, crypto::secp256k1_ecdsa_recover};
use frame_support::{ensure, traits::{Currency, Get, VestingSchedule, IsSubType}, weights::Weight};
use parity_scale_codec::{Encode, Decode};
use frame_support::{
ensure,
traits::{Currency, Get, IsSubType, VestingSchedule},
weights::Weight,
};
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::ValidityError;
#[cfg(feature = "std")]
use serde::{self, Serialize, Deserialize, Serializer, Deserializer};
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
#[cfg(feature = "std")]
use sp_runtime::traits::Zero;
use sp_runtime::{
traits::{CheckedSub, SignedExtension, DispatchInfoOf}, RuntimeDebug,
traits::{CheckedSub, DispatchInfoOf, SignedExtension},
transaction_validity::{
TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
},
RuntimeDebug,
};
use primitives::v1::ValidityError;
pub use pallet::*;
use sp_std::{fmt::Debug, prelude::*};
type CurrencyOf<T> = <<T as Config>::VestingSchedule as VestingSchedule<<T as frame_system::Config>::AccountId>>::Currency;
type CurrencyOf<T> = <<T as Config>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId,
>>::Currency;
type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
pub trait WeightInfo {
@@ -46,11 +53,21 @@ pub trait WeightInfo {
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn claim() -> Weight { 0 }
fn mint_claim() -> Weight { 0 }
fn claim_attest() -> Weight { 0 }
fn attest() -> Weight { 0 }
fn move_claim() -> Weight { 0 }
fn claim() -> Weight {
0
}
fn mint_claim() -> Weight {
0
}
fn claim_attest() -> Weight {
0
}
fn attest() -> Weight {
0
}
fn move_claim() -> Weight {
0
}
}
/// The kind of statement an account needs to make for a claim to be valid.
@@ -93,7 +110,10 @@ pub struct EthereumAddress([u8; 20]);
#[cfg(feature = "std")]
impl Serialize for EthereumAddress {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]);
serializer.serialize_str(&format!("0x{}", hex))
}
@@ -101,12 +121,17 @@ impl Serialize for EthereumAddress {
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for EthereumAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let base_string = String::deserialize(deserializer)?;
let offset = if base_string.starts_with("0x") { 2 } else { 0 };
let s = &base_string[offset..];
if s.len() != 40 {
Err(serde::de::Error::custom("Bad length of Ethereum address (should be 42 including '0x')"))?;
Err(serde::de::Error::custom(
"Bad length of Ethereum address (should be 42 including '0x')",
))?;
}
let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s)
.map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?;
@@ -133,9 +158,9 @@ impl sp_std::fmt::Debug for EcdsaSignature {
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -146,7 +171,7 @@ pub mod pallet {
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment=Self::BlockNumber>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment = Self::BlockNumber>;
#[pallet::constant]
type Prefix: Get<&'static [u8]>;
type MoveClaimOrigin: EnsureOrigin<Self::Origin>;
@@ -192,11 +217,8 @@ pub mod pallet {
/// The block number is when the vesting should start.
#[pallet::storage]
#[pallet::getter(fn vesting)]
pub(super) type Vesting<T: Config> = StorageMap<
_,
Identity, EthereumAddress,
(BalanceOf<T>, BalanceOf<T>, T::BlockNumber),
>;
pub(super) type Vesting<T: Config> =
StorageMap<_, Identity, EthereumAddress, (BalanceOf<T>, BalanceOf<T>, T::BlockNumber)>;
/// The statement kind that must be signed, if any.
#[pallet::storage]
@@ -208,17 +230,15 @@ pub mod pallet {
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub claims: Vec<(EthereumAddress, BalanceOf<T>, Option<T::AccountId>, Option<StatementKind>)>,
pub claims:
Vec<(EthereumAddress, BalanceOf<T>, Option<T::AccountId>, Option<StatementKind>)>,
pub vesting: Vec<(EthereumAddress, (BalanceOf<T>, BalanceOf<T>, T::BlockNumber))>,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
claims: Default::default(),
vesting: Default::default(),
}
GenesisConfig { claims: Default::default(), vesting: Default::default() }
}
}
@@ -226,23 +246,32 @@ pub mod pallet {
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
// build `Claims`
self.claims.iter().map(|(a, b, _, _)| (a.clone(), b.clone())).for_each(|(a, b)| {
Claims::<T>::insert(a, b);
});
self.claims
.iter()
.map(|(a, b, _, _)| (a.clone(), b.clone()))
.for_each(|(a, b)| {
Claims::<T>::insert(a, b);
});
// build `Total`
Total::<T>::put(
self.claims.iter().fold(Zero::zero(), |acc: BalanceOf<T>, &(_, b, _, _)| acc + b),
self.claims
.iter()
.fold(Zero::zero(), |acc: BalanceOf<T>, &(_, b, _, _)| acc + b),
);
// build `Vesting`
self.vesting.iter().for_each(|(k, v)| { Vesting::<T>::insert(k, v); });
self.vesting.iter().for_each(|(k, v)| {
Vesting::<T>::insert(k, v);
});
// build `Signing`
self.claims.iter()
self.claims
.iter()
.filter_map(|(a, _, _, s)| Some((a.clone(), s.clone()?)))
.for_each(|(a, s)| {
Signing::<T>::insert(a, s);
});
// build `Preclaims`
self.claims.iter()
self.claims
.iter()
.filter_map(|(a, _, i, _)| Some((i.clone()?, a.clone())))
.for_each(|(i, a)| {
Preclaims::<T>::insert(i, a);
@@ -283,7 +312,7 @@ pub mod pallet {
pub fn claim(
origin: OriginFor<T>,
dest: T::AccountId,
ethereum_signature: EcdsaSignature
ethereum_signature: EcdsaSignature,
) -> DispatchResult {
ensure_none(origin)?;
@@ -422,9 +451,13 @@ pub mod pallet {
Claims::<T>::take(&old).map(|c| Claims::<T>::insert(&new, c));
Vesting::<T>::take(&old).map(|c| Vesting::<T>::insert(&new, c));
Signing::<T>::take(&old).map(|c| Signing::<T>::insert(&new, c));
maybe_preclaim.map(|preclaim| Preclaims::<T>::mutate(&preclaim, |maybe_o|
if maybe_o.as_ref().map_or(false, |o| o == &old) { *maybe_o = Some(new) }
));
maybe_preclaim.map(|preclaim| {
Preclaims::<T>::mutate(&preclaim, |maybe_o| {
if maybe_o.as_ref().map_or(false, |o| o == &old) {
*maybe_o = Some(new)
}
})
});
Ok(Pays::No.into())
}
}
@@ -443,19 +476,23 @@ pub mod pallet {
Call::claim(account, ethereum_signature) => {
let data = account.using_encoded(to_ascii_hex);
(Self::eth_recover(&ethereum_signature, &data, &[][..]), None)
}
},
// <weight>
// The weight of this logic is included in the `claim_attest` dispatchable.
// </weight>
Call::claim_attest(account, ethereum_signature, statement) => {
let data = account.using_encoded(to_ascii_hex);
(Self::eth_recover(&ethereum_signature, &data, &statement), Some(statement.as_slice()))
}
(
Self::eth_recover(&ethereum_signature, &data, &statement),
Some(statement.as_slice()),
)
},
_ => return Err(InvalidTransaction::Call.into()),
};
let signer = maybe_signer
.ok_or(InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()))?;
let signer = maybe_signer.ok_or(InvalidTransaction::Custom(
ValidityError::InvalidEthereumSignature.into(),
))?;
let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into());
ensure!(<Claims<T>>::contains_key(&signer), e);
@@ -511,13 +548,13 @@ impl<T: Config> Pallet<T> {
fn eth_recover(s: &EcdsaSignature, what: &[u8], extra: &[u8]) -> Option<EthereumAddress> {
let msg = keccak_256(&Self::ethereum_signable_message(what, extra));
let mut res = EthereumAddress::default();
res.0.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
res.0
.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
Some(res)
}
fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> sp_runtime::DispatchResult {
let balance_due = <Claims<T>>::get(&signer)
.ok_or(Error::<T>::SignerHasNoClaim)?;
let balance_due = <Claims<T>>::get(&signer).ok_or(Error::<T>::SignerHasNoClaim)?;
let new_total = Self::total().checked_sub(&balance_due).ok_or(Error::<T>::PotUnderflow)?;
@@ -552,11 +589,13 @@ impl<T: Config> Pallet<T> {
/// Validate `attest` calls prior to execution. Needed to avoid a DoS attack since they are
/// otherwise free to place on chain.
#[derive(Encode, Decode, Clone, Eq, PartialEq)]
pub struct PrevalidateAttests<T: Config + Send + Sync>(sp_std::marker::PhantomData<T>) where
pub struct PrevalidateAttests<T: Config + Send + Sync>(sp_std::marker::PhantomData<T>)
where
<T as frame_system::Config>::Call: IsSubType<Call<T>>;
impl<T: Config + Send + Sync> Debug for PrevalidateAttests<T> where
<T as frame_system::Config>::Call: IsSubType<Call<T>>
impl<T: Config + Send + Sync> Debug for PrevalidateAttests<T>
where
<T as frame_system::Config>::Call: IsSubType<Call<T>>,
{
#[cfg(feature = "std")]
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
@@ -569,8 +608,9 @@ impl<T: Config + Send + Sync> Debug for PrevalidateAttests<T> where
}
}
impl<T: Config + Send + Sync> PrevalidateAttests<T> where
<T as frame_system::Config>::Call: IsSubType<Call<T>>
impl<T: Config + Send + Sync> PrevalidateAttests<T>
where
<T as frame_system::Config>::Call: IsSubType<Call<T>>,
{
/// Create new `SignedExtension` to check runtime version.
pub fn new() -> Self {
@@ -578,8 +618,9 @@ impl<T: Config + Send + Sync> PrevalidateAttests<T> where
}
}
impl<T: Config + Send + Sync> SignedExtension for PrevalidateAttests<T> where
<T as frame_system::Config>::Call: IsSubType<Call<T>>
impl<T: Config + Send + Sync> SignedExtension for PrevalidateAttests<T>
where
<T as frame_system::Config>::Call: IsSubType<Call<T>>,
{
type AccountId = T::AccountId;
type Call = <T as frame_system::Config>::Call;
@@ -627,8 +668,15 @@ mod secp_utils {
res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
res
}
pub fn sig<T: Config>(secret: &libsecp256k1::SecretKey, what: &[u8], extra: &[u8]) -> EcdsaSignature {
let msg = keccak_256(&<super::Pallet<T>>::ethereum_signable_message(&to_ascii_hex(what)[..], extra));
pub fn sig<T: Config>(
secret: &libsecp256k1::SecretKey,
what: &[u8],
extra: &[u8],
) -> EcdsaSignature {
let msg = keccak_256(&<super::Pallet<T>>::ethereum_signable_message(
&to_ascii_hex(what)[..],
extra,
));
let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);
let mut r = [0u8; 65];
r[0..64].copy_from_slice(&sig.serialize()[..]);
@@ -639,27 +687,29 @@ mod secp_utils {
#[cfg(test)]
mod tests {
use hex_literal::hex;
use super::*;
use hex_literal::hex;
use secp_utils::*;
use sp_core::H256;
use parity_scale_codec::Encode;
use sp_core::H256;
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup, Identity},
transaction_validity::TransactionLongevity,
testing::Header,
};
use frame_support::{
assert_ok, assert_err, assert_noop, parameter_types,
ord_parameter_types, weights::{Pays, GetDispatchInfo}, traits::{ExistenceRequirement, GenesisBuild},
dispatch::DispatchError::BadOrigin,
};
use pallet_balances;
use crate::claims;
use claims::Call as ClaimsCall;
use frame_support::{
assert_err, assert_noop, assert_ok,
dispatch::DispatchError::BadOrigin,
ord_parameter_types, parameter_types,
traits::{ExistenceRequirement, GenesisBuild},
weights::{GetDispatchInfo, Pays},
};
use pallet_balances;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, Identity, IdentityLookup},
transaction_validity::TransactionLongevity,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -734,7 +784,7 @@ mod tests {
type WeightInfo = ();
}
parameter_types!{
parameter_types! {
pub Prefix: &'static [u8] = b"Pay RUSTs to the TEST account:";
}
ord_parameter_types! {
@@ -770,8 +820,10 @@ mod tests {
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
// We use default for brevity, but you can configure as desired if needed.
pallet_balances::GenesisConfig::<Test>::default().assimilate_storage(&mut t).unwrap();
claims::GenesisConfig::<Test>{
pallet_balances::GenesisConfig::<Test>::default()
.assimilate_storage(&mut t)
.unwrap();
claims::GenesisConfig::<Test> {
claims: vec![
(eth(&alice()), 100, None, None),
(eth(&dave()), 200, None, Some(StatementKind::Regular)),
@@ -779,7 +831,9 @@ mod tests {
(eth(&frank()), 400, Some(43), None),
],
vesting: vec![(eth(&alice()), (50, 10, 1))],
}.assimilate_storage(&mut t).unwrap();
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
@@ -813,7 +867,11 @@ mod tests {
fn claiming_works() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&alice(), &42u64.encode(), &[][..])
));
assert_eq!(Balances::free_balance(&42), 100);
assert_eq!(Vesting::vesting_balance(&42), Some(50));
assert_eq!(Claims::total(), total_claims() - 100);
@@ -824,10 +882,20 @@ mod tests {
fn basic_claim_moving_works() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_noop!(Claims::move_claim(Origin::signed(1), eth(&alice()), eth(&bob()), None), BadOrigin);
assert_noop!(
Claims::move_claim(Origin::signed(1), eth(&alice()), eth(&bob()), None),
BadOrigin
);
assert_ok!(Claims::move_claim(Origin::signed(6), eth(&alice()), eth(&bob()), None));
assert_noop!(Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])), Error::<Test>::SignerHasNoClaim);
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&bob(), &42u64.encode(), &[][..])));
assert_noop!(
Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])),
Error::<Test>::SignerHasNoClaim
);
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&bob(), &42u64.encode(), &[][..])
));
assert_eq!(Balances::free_balance(&42), 100);
assert_eq!(Vesting::vesting_balance(&42), Some(50));
assert_eq!(Claims::total(), total_claims() - 100);
@@ -839,7 +907,12 @@ mod tests {
new_test_ext().execute_with(|| {
assert_ok!(Claims::move_claim(Origin::signed(6), eth(&dave()), eth(&bob()), None));
let s = sig::<Test>(&bob(), &42u64.encode(), StatementKind::Regular.to_text());
assert_ok!(Claims::claim_attest(Origin::none(), 42, s, StatementKind::Regular.to_text().to_vec()));
assert_ok!(Claims::claim_attest(
Origin::none(),
42,
s,
StatementKind::Regular.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&42), 200);
});
}
@@ -856,7 +929,11 @@ mod tests {
#[test]
fn claiming_does_not_bypass_signing() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&alice(), &42u64.encode(), &[][..])
));
assert_noop!(
Claims::claim(Origin::none(), 42, sig::<Test>(&dave(), &42u64.encode(), &[][..])),
Error::<Test>::InvalidStatement,
@@ -865,7 +942,11 @@ mod tests {
Claims::claim(Origin::none(), 42, sig::<Test>(&eve(), &42u64.encode(), &[][..])),
Error::<Test>::InvalidStatement,
);
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&frank(), &42u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&frank(), &42u64.encode(), &[][..])
));
});
}
@@ -874,21 +955,41 @@ mod tests {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
let s = sig::<Test>(&dave(), &42u64.encode(), StatementKind::Saft.to_text());
let r = Claims::claim_attest(Origin::none(), 42, s.clone(), StatementKind::Saft.to_text().to_vec());
let r = Claims::claim_attest(
Origin::none(),
42,
s.clone(),
StatementKind::Saft.to_text().to_vec(),
);
assert_noop!(r, Error::<Test>::InvalidStatement);
let r = Claims::claim_attest(Origin::none(), 42, s, StatementKind::Regular.to_text().to_vec());
let r = Claims::claim_attest(
Origin::none(),
42,
s,
StatementKind::Regular.to_text().to_vec(),
);
assert_noop!(r, Error::<Test>::SignerHasNoClaim);
// ^^^ we use ecdsa_recover, so an invalid signature just results in a random signer id
// being recovered, which realistically will never have a claim.
let s = sig::<Test>(&dave(), &42u64.encode(), StatementKind::Regular.to_text());
assert_ok!(Claims::claim_attest(Origin::none(), 42, s, StatementKind::Regular.to_text().to_vec()));
assert_ok!(Claims::claim_attest(
Origin::none(),
42,
s,
StatementKind::Regular.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&42), 200);
assert_eq!(Claims::total(), total_claims() - 200);
let s = sig::<Test>(&dave(), &42u64.encode(), StatementKind::Regular.to_text());
let r = Claims::claim_attest(Origin::none(), 42, s, StatementKind::Regular.to_text().to_vec());
let r = Claims::claim_attest(
Origin::none(),
42,
s,
StatementKind::Regular.to_text().to_vec(),
);
assert_noop!(r, Error::<Test>::SignerHasNoClaim);
});
}
@@ -897,8 +998,14 @@ mod tests {
fn attesting_works() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_noop!(Claims::attest(Origin::signed(69), StatementKind::Saft.to_text().to_vec()), Error::<Test>::SenderHasNoClaim);
assert_noop!(Claims::attest(Origin::signed(42), StatementKind::Regular.to_text().to_vec()), Error::<Test>::InvalidStatement);
assert_noop!(
Claims::attest(Origin::signed(69), StatementKind::Saft.to_text().to_vec()),
Error::<Test>::SenderHasNoClaim
);
assert_noop!(
Claims::attest(Origin::signed(42), StatementKind::Regular.to_text().to_vec()),
Error::<Test>::InvalidStatement
);
assert_ok!(Claims::attest(Origin::signed(42), StatementKind::Saft.to_text().to_vec()));
assert_eq!(Balances::free_balance(&42), 300);
assert_eq!(Claims::total(), total_claims() - 300);
@@ -910,7 +1017,11 @@ mod tests {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
// Alice's claim is 100
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&alice(), &42u64.encode(), &[][..])
));
assert_eq!(Balances::free_balance(&42), 100);
// Eve's claim is 300 through Account 42
assert_ok!(Claims::attest(Origin::signed(42), StatementKind::Saft.to_text().to_vec()));
@@ -970,7 +1081,11 @@ mod tests {
);
assert_ok!(Claims::mint_claim(Origin::root(), eth(&bob()), 200, None, None));
assert_eq!(Claims::total(), total_claims() + 200);
assert_ok!(Claims::claim(Origin::none(), 69, sig::<Test>(&bob(), &69u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
69,
sig::<Test>(&bob(), &69u64.encode(), &[][..])
));
assert_eq!(Balances::free_balance(&69), 200);
assert_eq!(Vesting::vesting_balance(&69), None);
assert_eq!(Claims::total(), total_claims());
@@ -989,14 +1104,29 @@ mod tests {
Claims::claim(Origin::none(), 69, sig::<Test>(&bob(), &69u64.encode(), &[][..])),
Error::<Test>::SignerHasNoClaim,
);
assert_ok!(Claims::mint_claim(Origin::root(), eth(&bob()), 200, Some((50, 10, 1)), None));
assert_ok!(Claims::claim(Origin::none(), 69, sig::<Test>(&bob(), &69u64.encode(), &[][..])));
assert_ok!(Claims::mint_claim(
Origin::root(),
eth(&bob()),
200,
Some((50, 10, 1)),
None
));
assert_ok!(Claims::claim(
Origin::none(),
69,
sig::<Test>(&bob(), &69u64.encode(), &[][..])
));
assert_eq!(Balances::free_balance(&69), 200);
assert_eq!(Vesting::vesting_balance(&69), Some(50));
// Make sure we can not transfer the vested balance.
assert_err!(
<Balances as Currency<_>>::transfer(&69, &80, 180, ExistenceRequirement::AllowDeath),
<Balances as Currency<_>>::transfer(
&69,
&80,
180,
ExistenceRequirement::AllowDeath
),
pallet_balances::Error::<Test, _>::LiquidityRestrictions,
);
});
@@ -1006,29 +1136,43 @@ mod tests {
fn add_claim_with_statement_works() {
new_test_ext().execute_with(|| {
assert_noop!(
Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, None, Some(StatementKind::Regular)),
Claims::mint_claim(
Origin::signed(42),
eth(&bob()),
200,
None,
Some(StatementKind::Regular)
),
sp_runtime::traits::BadOrigin,
);
assert_eq!(Balances::free_balance(42), 0);
let signature = sig::<Test>(&bob(), &69u64.encode(), StatementKind::Regular.to_text());
assert_noop!(
Claims::claim_attest(
Origin::none(), 69, signature.clone(), StatementKind::Regular.to_text().to_vec()
Origin::none(),
69,
signature.clone(),
StatementKind::Regular.to_text().to_vec()
),
Error::<Test>::SignerHasNoClaim
);
assert_ok!(Claims::mint_claim(Origin::root(), eth(&bob()), 200, None, Some(StatementKind::Regular)));
assert_ok!(Claims::mint_claim(
Origin::root(),
eth(&bob()),
200,
None,
Some(StatementKind::Regular)
));
assert_noop!(
Claims::claim_attest(
Origin::none(), 69, signature.clone(), vec![],
),
Claims::claim_attest(Origin::none(), 69, signature.clone(), vec![],),
Error::<Test>::SignerHasNoClaim
);
assert_ok!(
Claims::claim_attest(
Origin::none(), 69, signature.clone(), StatementKind::Regular.to_text().to_vec()
)
);
assert_ok!(Claims::claim_attest(
Origin::none(),
69,
signature.clone(),
StatementKind::Regular.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&69), 200);
});
}
@@ -1038,7 +1182,11 @@ mod tests {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_err!(
Claims::claim(Origin::signed(42), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])),
Claims::claim(
Origin::signed(42),
42,
sig::<Test>(&alice(), &42u64.encode(), &[][..])
),
sp_runtime::traits::BadOrigin,
);
});
@@ -1048,7 +1196,11 @@ mod tests {
fn double_claiming_doesnt_work() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(42), 0);
assert_ok!(Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])));
assert_ok!(Claims::claim(
Origin::none(),
42,
sig::<Test>(&alice(), &42u64.encode(), &[][..])
));
assert_noop!(
Claims::claim(Origin::none(), 42, sig::<Test>(&alice(), &42u64.encode(), &[][..])),
Error::<Test>::SignerHasNoClaim
@@ -1060,10 +1212,21 @@ mod tests {
fn claiming_while_vested_doesnt_work() {
new_test_ext().execute_with(|| {
// A user is already vested
assert_ok!(<Test as Config>::VestingSchedule::add_vesting_schedule(&69, total_claims(), 100, 10));
assert_ok!(<Test as Config>::VestingSchedule::add_vesting_schedule(
&69,
total_claims(),
100,
10
));
CurrencyOf::<Test>::make_free_balance_be(&69, total_claims());
assert_eq!(Balances::free_balance(69), total_claims());
assert_ok!(Claims::mint_claim(Origin::root(), eth(&bob()), 200, Some((50, 10, 1)), None));
assert_ok!(Claims::mint_claim(
Origin::root(),
eth(&bob()),
200,
Some((50, 10, 1)),
None
));
// New total
assert_eq!(Claims::total(), total_claims() + 200);
@@ -1116,7 +1279,10 @@ mod tests {
new_test_ext().execute_with(|| {
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &ClaimsCall::claim(1, sig::<Test>(&alice(), &1u64.encode(), &[][..]))),
<Pallet<Test>>::validate_unsigned(
source,
&ClaimsCall::claim(1, sig::<Test>(&alice(), &1u64.encode(), &[][..]))
),
Ok(ValidTransaction {
priority: 100,
requires: vec![],
@@ -1126,11 +1292,17 @@ mod tests {
})
);
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &ClaimsCall::claim(0, EcdsaSignature([0; 65]))),
<Pallet<Test>>::validate_unsigned(
source,
&ClaimsCall::claim(0, EcdsaSignature([0; 65]))
),
InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(),
);
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &ClaimsCall::claim(1, sig::<Test>(&bob(), &1u64.encode(), &[][..]))),
<Pallet<Test>>::validate_unsigned(
source,
&ClaimsCall::claim(1, sig::<Test>(&bob(), &1u64.encode(), &[][..]))
),
InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(),
);
let s = sig::<Test>(&dave(), &1u64.encode(), StatementKind::Regular.to_text());
@@ -1148,8 +1320,11 @@ mod tests {
assert_eq!(
<Pallet<Test>>::validate_unsigned(
source,
&ClaimsCall::claim_attest(1, EcdsaSignature([0; 65]),
StatementKind::Regular.to_text().to_vec())
&ClaimsCall::claim_attest(
1,
EcdsaSignature([0; 65]),
StatementKind::Regular.to_text().to_vec()
)
),
InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(),
);
@@ -1181,12 +1356,11 @@ mod tests {
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking {
use super::*;
use secp_utils::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, account};
use sp_runtime::DispatchResult;
use sp_runtime::traits::ValidateUnsigned;
use crate::claims::Call;
use frame_benchmarking::{account, benchmarks};
use frame_system::RawOrigin;
use secp_utils::*;
use sp_runtime::{traits::ValidateUnsigned, DispatchResult};
const SEED: u32 = 0;
@@ -1197,7 +1371,13 @@ mod benchmarking {
let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&input.encode())).unwrap();
let eth_address = eth(&secret_key);
let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into()));
super::Pallet::<T>::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, None)?;
super::Pallet::<T>::mint_claim(
RawOrigin::Root.into(),
eth_address,
VALUE.into(),
vesting,
None,
)?;
Ok(())
}
@@ -1210,7 +1390,7 @@ mod benchmarking {
eth_address,
VALUE.into(),
vesting,
Some(Default::default())
Some(Default::default()),
)?;
Ok(())
}
+341 -162
View File
@@ -49,33 +49,35 @@
//! the parachain remains active. Users can withdraw their funds once the slot is completed and funds are
//! returned to the crowdloan account.
use crate::{
slot_range::SlotRange,
traits::{Auctioneer, Registrar},
};
use frame_support::{
ensure, Identity, PalletId,
storage::{child, ChildTriePrefixIterator},
traits::{
Currency, ReservableCurrency, Get, ExistenceRequirement::AllowDeath
},
ensure,
pallet_prelude::Weight,
storage::{child, ChildTriePrefixIterator},
traits::{Currency, ExistenceRequirement::AllowDeath, Get, ReservableCurrency},
Identity, PalletId,
};
use sp_runtime::{
RuntimeDebug, MultiSignature, MultiSigner,
traits::{
AccountIdConversion, Hash, Saturating, Zero, One, CheckedAdd, Verify, IdentifyAccount,
},
};
use crate::traits::{Registrar, Auctioneer};
use crate::slot_range::SlotRange;
use parity_scale_codec::{Encode, Decode};
use sp_std::vec::Vec;
use primitives::v1::Id as ParaId;
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::Id as ParaId;
use sp_runtime::{
traits::{
AccountIdConversion, CheckedAdd, Hash, IdentifyAccount, One, Saturating, Verify, Zero,
},
MultiSignature, MultiSigner, RuntimeDebug,
};
use sp_std::vec::Vec;
type CurrencyOf<T> = <<T as Config>::Auctioneer as Auctioneer>::Currency;
type LeasePeriodOf<T> = <<T as Config>::Auctioneer as Auctioneer>::LeasePeriod;
type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
#[allow(dead_code)]
type NegativeImbalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
type NegativeImbalanceOf<T> =
<CurrencyOf<T> as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
type TrieIndex = u32;
@@ -83,25 +85,43 @@ pub trait WeightInfo {
fn create() -> Weight;
fn contribute() -> Weight;
fn withdraw() -> Weight;
fn refund(k: u32, ) -> Weight;
fn refund(k: u32) -> Weight;
fn dissolve() -> Weight;
fn edit() -> Weight;
fn add_memo() -> Weight;
fn on_initialize(n: u32, ) -> Weight;
fn on_initialize(n: u32) -> Weight;
fn poke() -> Weight;
}
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn create() -> Weight { 0 }
fn contribute() -> Weight { 0 }
fn withdraw() -> Weight { 0 }
fn refund(_k: u32, ) -> Weight { 0 }
fn dissolve() -> Weight { 0 }
fn edit() -> Weight { 0 }
fn add_memo() -> Weight { 0 }
fn on_initialize(_n: u32, ) -> Weight { 0 }
fn poke() -> Weight { 0 }
fn create() -> Weight {
0
}
fn contribute() -> Weight {
0
}
fn withdraw() -> Weight {
0
}
fn refund(_k: u32) -> Weight {
0
}
fn dissolve() -> Weight {
0
}
fn edit() -> Weight {
0
}
fn add_memo() -> Weight {
0
}
fn on_initialize(_n: u32) -> Weight {
0
}
fn poke() -> Weight {
0
}
}
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
@@ -148,9 +168,9 @@ pub struct FundInfo<AccountId, Balance, BlockNumber, LeasePeriod> {
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::{pallet_prelude::*, ensure_signed, ensure_root};
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -178,13 +198,13 @@ pub mod pallet {
/// The parachain registrar type. We just use this to ensure that only the manager of a para is able to
/// start a crowdloan for its slot.
type Registrar: Registrar<AccountId=Self::AccountId>;
type Registrar: Registrar<AccountId = Self::AccountId>;
/// The type representing the auctioning system.
type Auctioneer: Auctioneer<
AccountId=Self::AccountId,
BlockNumber=Self::BlockNumber,
LeasePeriod=Self::BlockNumber,
AccountId = Self::AccountId,
BlockNumber = Self::BlockNumber,
LeasePeriod = Self::BlockNumber,
>;
/// The maximum length for the memo attached to a crowdloan contribution.
@@ -199,7 +219,8 @@ pub mod pallet {
#[pallet::getter(fn funds)]
pub(super) type Funds<T: Config> = StorageMap<
_,
Twox64Concat, ParaId,
Twox64Concat,
ParaId,
FundInfo<T::AccountId, BalanceOf<T>, T::BlockNumber, LeasePeriodOf<T>>,
>;
@@ -305,7 +326,9 @@ pub mod pallet {
}
let new_raise = NewRaise::<T>::take();
let new_raise_len = new_raise.len() as u32;
for (fund, para_id) in new_raise.into_iter().filter_map(|i| Self::funds(i).map(|f| (f, i))) {
for (fund, para_id) in
new_raise.into_iter().filter_map(|i| Self::funds(i).map(|f| (f, i)))
{
// Care needs to be taken by the crowdloan creator that this function will succeed given
// the crowdloaning configuration. We do some checks ahead of time in crowdloan `create`.
let result = T::Auctioneer::place_bid(
@@ -349,9 +372,13 @@ pub mod pallet {
.ok_or(Error::<T>::FirstPeriodTooFarInFuture)?;
ensure!(last_period <= last_period_limit, Error::<T>::LastPeriodTooFarInFuture);
ensure!(end > <frame_system::Pallet<T>>::block_number(), Error::<T>::CannotEndInPast);
let last_possible_win_date = (first_period.saturating_add(One::one())).saturating_mul(T::Auctioneer::lease_period());
let last_possible_win_date = (first_period.saturating_add(One::one()))
.saturating_mul(T::Auctioneer::lease_period());
ensure!(end <= last_possible_win_date, Error::<T>::EndTooFarInFuture);
ensure!(first_period >= T::Auctioneer::lease_period_index(), Error::<T>::FirstPeriodInPast);
ensure!(
first_period >= T::Auctioneer::lease_period_index(),
Error::<T>::FirstPeriodInPast
);
// There should not be an existing fund.
ensure!(!Funds::<T>::contains_key(index), Error::<T>::FundNotEnded);
@@ -367,18 +394,21 @@ pub mod pallet {
CurrencyOf::<T>::reserve(&depositor, deposit)?;
Funds::<T>::insert(index, FundInfo {
depositor,
verifier,
deposit,
raised: Zero::zero(),
end,
cap,
last_contribution: LastContribution::Never,
first_period,
last_period,
trie_index,
});
Funds::<T>::insert(
index,
FundInfo {
depositor,
verifier,
deposit,
raised: Zero::zero(),
end,
cap,
last_contribution: LastContribution::Never,
first_period,
last_period,
trie_index,
},
);
NextTrieIndex::<T>::put(new_trie_index);
// Add a lock to the para so that the configuration cannot be changed.
@@ -401,7 +431,7 @@ pub mod pallet {
ensure!(value >= T::MinContribution::get(), Error::<T>::ContributionTooSmall);
let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
fund.raised = fund.raised.checked_add(&value).ok_or(Error::<T>::Overflow)?;
fund.raised = fund.raised.checked_add(&value).ok_or(Error::<T>::Overflow)?;
ensure!(fund.raised <= fund.cap, Error::<T>::CapExceeded);
// Make sure crowdloan has not ended
@@ -414,7 +444,10 @@ pub mod pallet {
// Make sure crowdloan has not already won.
let fund_account = Self::fund_account_id(index);
ensure!(!T::Auctioneer::has_won_an_auction(index, &fund_account), Error::<T>::BidOrLeaseActive);
ensure!(
!T::Auctioneer::has_won_an_auction(index, &fund_account),
Error::<T>::BidOrLeaseActive
);
// We disallow any crowdloan contributions during the VRF Period, so that people do not sneak their
// contributions into the auction when it would not impact the outcome.
@@ -425,7 +458,9 @@ pub mod pallet {
if let Some(ref verifier) = fund.verifier {
let signature = signature.ok_or(Error::<T>::InvalidSignature)?;
let payload = (index, &who, old_balance, value);
let valid = payload.using_encoded(|encoded| signature.verify(encoded, &verifier.clone().into_account()));
let valid = payload.using_encoded(|encoded| {
signature.verify(encoded, &verifier.clone().into_account())
});
ensure!(valid, Error::<T>::InvalidSignature);
}
@@ -439,11 +474,11 @@ pub mod pallet {
// In ending period; must ensure that we are in NewRaise.
LastContribution::Ending(n) if n == now => {
// do nothing - already in NewRaise
}
},
_ => {
NewRaise::<T>::append(index);
fund.last_contribution = LastContribution::Ending(now);
}
},
}
} else {
let endings_count = Self::endings_count();
@@ -452,13 +487,13 @@ pub mod pallet {
// Not in ending period and no auctions have ended ending since our
// previous bid which was also not in an ending period.
// `NewRaise` will contain our ID still: Do nothing.
}
},
_ => {
// Not in ending period; but an auction has been ending since our previous
// bid, or we never had one to begin with. Add bid.
NewRaise::<T>::append(index);
fund.last_contribution = LastContribution::PreEnding(endings_count);
}
},
}
}
@@ -538,7 +573,7 @@ pub mod pallet {
if refund_count >= T::RemoveKeysLimit::get() {
// Not everyone was able to be refunded this time around.
all_refunded = false;
break;
break
}
CurrencyOf::<T>::transfer(&fund_account, &who, balance, AllowDeath)?;
Self::contribution_kill(fund.trie_index, &who);
@@ -602,18 +637,21 @@ pub mod pallet {
let fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
Funds::<T>::insert(index, FundInfo {
depositor: fund.depositor,
verifier,
deposit: fund.deposit,
raised: fund.raised,
end,
cap,
last_contribution: fund.last_contribution,
first_period,
last_period,
trie_index: fund.trie_index,
});
Funds::<T>::insert(
index,
FundInfo {
depositor: fund.depositor,
verifier,
deposit: fund.deposit,
raised: fund.raised,
end,
cap,
last_contribution: fund.last_contribution,
first_period,
last_period,
trie_index: fund.trie_index,
},
);
Self::deposit_event(Event::<T>::Edited(index));
Ok(())
@@ -669,15 +707,19 @@ impl<T: Config> Pallet<T> {
child::ChildInfo::new_default(T::Hashing::hash(&buf[..]).as_ref())
}
pub fn contribution_put(index: TrieIndex, who: &T::AccountId, balance: &BalanceOf<T>, memo: &[u8]) {
pub fn contribution_put(
index: TrieIndex,
who: &T::AccountId,
balance: &BalanceOf<T>,
memo: &[u8],
) {
who.using_encoded(|b| child::put(&Self::id_from_index(index), b, &(balance, memo)));
}
pub fn contribution_get(index: TrieIndex, who: &T::AccountId) -> (BalanceOf<T>, Vec<u8>) {
who.using_encoded(|b| child::get_or_default::<(BalanceOf<T>, Vec<u8>)>(
&Self::id_from_index(index),
b,
))
who.using_encoded(|b| {
child::get_or_default::<(BalanceOf<T>, Vec<u8>)>(&Self::id_from_index(index), b)
})
}
pub fn contribution_kill(index: TrieIndex, who: &T::AccountId) {
@@ -689,9 +731,12 @@ impl<T: Config> Pallet<T> {
}
pub fn contribution_iterator(
index: TrieIndex
index: TrieIndex,
) -> ChildTriePrefixIterator<(T::AccountId, (BalanceOf<T>, Vec<u8>))> {
ChildTriePrefixIterator::<_>::with_prefix_over_key::<Identity>(&Self::id_from_index(index), &[])
ChildTriePrefixIterator::<_>::with_prefix_over_key::<Identity>(
&Self::id_from_index(index),
&[],
)
}
/// This function checks all conditions which would qualify a crowdloan has ended.
@@ -701,40 +746,39 @@ impl<T: Config> Pallet<T> {
fn ensure_crowdloan_ended(
now: T::BlockNumber,
fund_account: &T::AccountId,
fund: &FundInfo<T::AccountId, BalanceOf<T>, T::BlockNumber, LeasePeriodOf<T>>
fund: &FundInfo<T::AccountId, BalanceOf<T>, T::BlockNumber, LeasePeriodOf<T>>,
) -> sp_runtime::DispatchResult {
// `fund.end` can represent the end of a failed crowdloan or the beginning of retirement
// If the current lease period is past the first period they are trying to bid for, then
// it is already too late to win the bid.
let current_lease_period = T::Auctioneer::lease_period_index();
ensure!(now >= fund.end || current_lease_period > fund.first_period, Error::<T>::FundNotEnded);
// free balance must greater than or equal amount raised, otherwise funds are being used
// and a bid or lease must be active.
ensure!(CurrencyOf::<T>::free_balance(&fund_account) >= fund.raised, Error::<T>::BidOrLeaseActive);
// `fund.end` can represent the end of a failed crowdloan or the beginning of retirement
// If the current lease period is past the first period they are trying to bid for, then
// it is already too late to win the bid.
let current_lease_period = T::Auctioneer::lease_period_index();
ensure!(
now >= fund.end || current_lease_period > fund.first_period,
Error::<T>::FundNotEnded
);
// free balance must greater than or equal amount raised, otherwise funds are being used
// and a bid or lease must be active.
ensure!(
CurrencyOf::<T>::free_balance(&fund_account) >= fund.raised,
Error::<T>::BidOrLeaseActive
);
Ok(())
Ok(())
}
}
impl<T: Config> crate::traits::OnSwap for Pallet<T> {
fn on_swap(one: ParaId, other: ParaId) {
Funds::<T>::mutate(one, |x|
Funds::<T>::mutate(other, |y|
sp_std::mem::swap(x, y)
)
)
Funds::<T>::mutate(one, |x| Funds::<T>::mutate(other, |y| sp_std::mem::swap(x, y)))
}
}
#[cfg(any(feature = "runtime-benchmarks", test))]
mod crypto {
use sp_core::ed25519;
use sp_io::crypto::{ed25519_sign, ed25519_generate};
use sp_std::{
vec::Vec,
convert::TryFrom,
};
use sp_runtime::{MultiSigner, MultiSignature};
use sp_io::crypto::{ed25519_generate, ed25519_sign};
use sp_runtime::{MultiSignature, MultiSigner};
use sp_std::{convert::TryFrom, vec::Vec};
pub fn create_ed25519_pubkey(seed: Vec<u8>) -> MultiSigner {
ed25519_generate(0.into(), Some(seed)).into()
@@ -751,24 +795,26 @@ mod crypto {
mod tests {
use super::*;
use std::{cell::RefCell, sync::Arc, collections::BTreeMap};
use frame_support::{
assert_ok, assert_noop, parameter_types,
traits::{OnInitialize, OnFinalize},
assert_noop, assert_ok, parameter_types,
traits::{OnFinalize, OnInitialize},
};
use sp_core::H256;
use primitives::v1::Id as ParaId;
use sp_core::H256;
use std::{cell::RefCell, collections::BTreeMap, sync::Arc};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use sp_runtime::{
testing::Header, traits::{BlakeTwo256, IdentityLookup}, DispatchResult,
};
use crate::{
mock::TestRegistrar,
traits::{OnSwap, AuctionStatus},
crowdloan,
mock::TestRegistrar,
traits::{AuctionStatus, OnSwap},
};
use sp_keystore::{testing::KeyStore, KeystoreExt};
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
DispatchResult,
};
use sp_keystore::{KeystoreExt, testing::KeyStore};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -840,7 +886,7 @@ mod tests {
para: ParaId,
first_period: u64,
last_period: u64,
amount: u64
amount: u64,
}
thread_local! {
static AUCTION: RefCell<Option<(u64, u64)>> = RefCell::new(None);
@@ -875,7 +921,8 @@ mod tests {
let account_id = Crowdloan::fund_account_id(para);
if winner {
let free_balance = Balances::free_balance(&account_id);
Balances::reserve(&account_id, free_balance).expect("should be able to reserve free balance");
Balances::reserve(&account_id, free_balance)
.expect("should be able to reserve free balance");
} else {
let reserved_balance = Balances::reserved_balance(&account_id);
Balances::unreserve(&account_id, reserved_balance);
@@ -915,10 +962,10 @@ mod tests {
let after_end = after_early_end - ending_period;
// Optional VRF delay
if after_end < vrf_delay() {
return AuctionStatus::VrfDelay(after_end);
return AuctionStatus::VrfDelay(after_end)
} else {
// VRF delay is done, so we just end the auction
return AuctionStatus::NotStarted;
return AuctionStatus::NotStarted
}
}
}
@@ -928,10 +975,19 @@ mod tests {
para: ParaId,
first_period: u64,
last_period: u64,
amount: u64
amount: u64,
) -> DispatchResult {
let height = System::block_number();
BIDS_PLACED.with(|p| p.borrow_mut().push(BidPlaced { height, bidder, para, first_period, last_period, amount }));
BIDS_PLACED.with(|p| {
p.borrow_mut().push(BidPlaced {
height,
bidder,
para,
first_period,
last_period,
amount,
})
});
Ok(())
}
@@ -974,9 +1030,11 @@ mod tests {
// our desired mockup.
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test>{
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 1000), (2, 2000), (3, 3000), (4, 4000)],
}.assimilate_storage(&mut t).unwrap();
}
.assimilate_storage(&mut t)
.unwrap();
let keystore = KeyStore::new();
let mut t: sp_io::TestExternalities = t.into();
t.register_extension(KeystoreExt(Arc::new(keystore)));
@@ -986,9 +1044,16 @@ mod tests {
fn new_para() -> ParaId {
for i in 0.. {
let para: ParaId = i.into();
if TestRegistrar::<Test>::is_registered(para) { continue }
assert_ok!(TestRegistrar::<Test>::register(1, para, Default::default(), Default::default()));
return para;
if TestRegistrar::<Test>::is_registered(para) {
continue
}
assert_ok!(TestRegistrar::<Test>::register(
1,
para,
Default::default(),
Default::default()
));
return para
}
unreachable!()
}
@@ -1023,7 +1088,14 @@ mod tests {
assert_eq!(bids(), vec![]);
assert_ok!(TestAuctioneer::place_bid(1, 2.into(), 0, 3, 6));
let b = BidPlaced { height: 0, bidder: 1, para: 2.into(), first_period: 0, last_period: 3, amount: 6 };
let b = BidPlaced {
height: 0,
bidder: 1,
para: 2.into(),
first_period: 0,
last_period: 3,
amount: 6,
};
assert_eq!(bids(), vec![b]);
assert_eq!(TestAuctioneer::auction_status(4), AuctionStatus::<u64>::StartingPeriod);
assert_eq!(TestAuctioneer::auction_status(5), AuctionStatus::<u64>::EndingPeriod(0, 0));
@@ -1069,7 +1141,15 @@ mod tests {
let pubkey = crypto::create_ed25519_pubkey(b"//verifier".to_vec());
let para = new_para();
// Now try to create a crowdloan campaign
assert_ok!(Crowdloan::create(Origin::signed(1), para, 1000, 1, 4, 9, Some(pubkey.clone())));
assert_ok!(Crowdloan::create(
Origin::signed(1),
para,
1000,
1,
4,
9,
Some(pubkey.clone())
));
// This is what the initial `fund_info` should look like
let fund_info = FundInfo {
depositor: 1,
@@ -1110,13 +1190,24 @@ mod tests {
assert_noop!(Crowdloan::create(Origin::signed(1), para, 1000, 1, 9, 9, None), e);
// Cannot create a crowdloan without some deposit funds
assert_ok!(TestRegistrar::<Test>::register(1337, ParaId::from(1234), Default::default(), Default::default()));
assert_ok!(TestRegistrar::<Test>::register(
1337,
ParaId::from(1234),
Default::default(),
Default::default()
));
let e = BalancesError::<Test, _>::InsufficientBalance;
assert_noop!(Crowdloan::create(Origin::signed(1337), ParaId::from(1234), 1000, 1, 3, 9, None), e);
assert_noop!(
Crowdloan::create(Origin::signed(1337), ParaId::from(1234), 1000, 1, 3, 9, None),
e
);
// Cannot create a crowdloan with nonsense end date
// This crowdloan would end in lease period 2, but is bidding for some slot that starts in lease period 1.
assert_noop!(Crowdloan::create(Origin::signed(1), para, 1000, 1, 4, 41, None), Error::<Test>::EndTooFarInFuture);
assert_noop!(
Crowdloan::create(Origin::signed(1), para, 1000, 1, 4, 41, None),
Error::<Test>::EndTooFarInFuture
);
});
}
@@ -1156,30 +1247,59 @@ mod tests {
let para = new_para();
let pubkey = crypto::create_ed25519_pubkey(b"//verifier".to_vec());
// Set up a crowdloan
assert_ok!(Crowdloan::create(Origin::signed(1), para, 1000, 1, 4, 9, Some(pubkey.clone())));
assert_ok!(Crowdloan::create(
Origin::signed(1),
para,
1000,
1,
4,
9,
Some(pubkey.clone())
));
// No contributions yet
assert_eq!(Crowdloan::contribution_get(u32::from(para), &1).0, 0);
// Missing signature
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 49, None), Error::<Test>::InvalidSignature);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 49, None),
Error::<Test>::InvalidSignature
);
let payload = (0u32, 1u64, 0u64, 49u64);
let valid_signature = crypto::create_ed25519_signature(&payload.encode(), pubkey.clone());
let valid_signature =
crypto::create_ed25519_signature(&payload.encode(), pubkey.clone());
let invalid_signature = MultiSignature::default();
// Invalid signature
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 49, Some(invalid_signature)), Error::<Test>::InvalidSignature);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 49, Some(invalid_signature)),
Error::<Test>::InvalidSignature
);
// Valid signature wrong parameter
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 50, Some(valid_signature.clone())), Error::<Test>::InvalidSignature);
assert_noop!(Crowdloan::contribute(Origin::signed(2), para, 49, Some(valid_signature.clone())), Error::<Test>::InvalidSignature);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 50, Some(valid_signature.clone())),
Error::<Test>::InvalidSignature
);
assert_noop!(
Crowdloan::contribute(Origin::signed(2), para, 49, Some(valid_signature.clone())),
Error::<Test>::InvalidSignature
);
// Valid signature
assert_ok!(Crowdloan::contribute(Origin::signed(1), para, 49, Some(valid_signature.clone())));
assert_ok!(Crowdloan::contribute(
Origin::signed(1),
para,
49,
Some(valid_signature.clone())
));
// Reuse valid signature
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 49, Some(valid_signature)), Error::<Test>::InvalidSignature);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 49, Some(valid_signature)),
Error::<Test>::InvalidSignature
);
let payload_2 = (0u32, 1u64, 49u64, 10u64);
let valid_signature_2 = crypto::create_ed25519_signature(&payload_2.encode(), pubkey);
@@ -1202,22 +1322,34 @@ mod tests {
let para = new_para();
// Cannot contribute to non-existing fund
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 49, None), Error::<Test>::InvalidParaId);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 49, None),
Error::<Test>::InvalidParaId
);
// Cannot contribute below minimum contribution
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 9, None), Error::<Test>::ContributionTooSmall);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 9, None),
Error::<Test>::ContributionTooSmall
);
// Set up a crowdloan
assert_ok!(Crowdloan::create(Origin::signed(1), para, 1000, 1, 4, 9, None));
assert_ok!(Crowdloan::contribute(Origin::signed(1), para, 101, None));
// Cannot contribute past the limit
assert_noop!(Crowdloan::contribute(Origin::signed(2), para, 900, None), Error::<Test>::CapExceeded);
assert_noop!(
Crowdloan::contribute(Origin::signed(2), para, 900, None),
Error::<Test>::CapExceeded
);
// Move past end date
run_to_block(10);
// Cannot contribute to ended fund
assert_noop!(Crowdloan::contribute(Origin::signed(1), para, 49, None), Error::<Test>::ContributionPeriodOver);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para, 49, None),
Error::<Test>::ContributionPeriodOver
);
// If a crowdloan has already won, it should not allow contributions.
let para_2 = new_para();
@@ -1225,7 +1357,10 @@ mod tests {
// Emulate a win by leasing out and putting a deposit. Slots pallet would normally do this.
let crowdloan_account = Crowdloan::fund_account_id(para_2);
set_winner(para_2, crowdloan_account, true);
assert_noop!(Crowdloan::contribute(Origin::signed(1), para_2, 49, None), Error::<Test>::BidOrLeaseActive);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para_2, 49, None),
Error::<Test>::BidOrLeaseActive
);
// Move past lease period 1, should not be allowed to have further contributions with a crowdloan
// that has starting period 1.
@@ -1233,7 +1368,10 @@ mod tests {
assert_ok!(Crowdloan::create(Origin::signed(1), para_3, 1000, 1, 4, 40, None));
run_to_block(40);
assert_eq!(TestAuctioneer::lease_period_index(), 2);
assert_noop!(Crowdloan::contribute(Origin::signed(1), para_3, 49, None), Error::<Test>::ContributionPeriodOver);
assert_noop!(
Crowdloan::contribute(Origin::signed(1), para_3, 49, None),
Error::<Test>::ContributionPeriodOver
);
});
}
@@ -1249,7 +1387,15 @@ mod tests {
assert_ok!(TestAuctioneer::new_auction(5, 0));
// Set up a crowdloan
assert_ok!(Crowdloan::create(Origin::signed(1), para, 1000, first_period, last_period, 20, None));
assert_ok!(Crowdloan::create(
Origin::signed(1),
para,
1000,
first_period,
last_period,
20,
None
));
run_to_block(8);
// Can def contribute when auction is running.
@@ -1259,7 +1405,10 @@ mod tests {
run_to_block(10);
// Can't contribute when auction is in the VRF delay period.
assert!(TestAuctioneer::auction_status(System::block_number()).is_vrf());
assert_noop!(Crowdloan::contribute(Origin::signed(2), para, 250, None), Error::<Test>::VrfDelayInProgress);
assert_noop!(
Crowdloan::contribute(Origin::signed(2), para, 250, None),
Error::<Test>::VrfDelayInProgress
);
run_to_block(15);
// Its fine to contribute when no auction is running.
@@ -1278,7 +1427,15 @@ mod tests {
assert_ok!(TestAuctioneer::new_auction(5, 0));
// Set up a crowdloan
assert_ok!(Crowdloan::create(Origin::signed(1), para, 1000, first_period, last_period, 9, None));
assert_ok!(Crowdloan::create(
Origin::signed(1),
para,
1000,
first_period,
last_period,
9,
None
));
let bidder = Crowdloan::fund_account_id(para);
// Fund crowdloan
@@ -1292,11 +1449,14 @@ mod tests {
assert_ok!(Crowdloan::contribute(Origin::signed(2), para, 250, None));
run_to_block(10);
assert_eq!(bids(), vec![
BidPlaced { height: 5, amount: 250, bidder, para, first_period, last_period },
BidPlaced { height: 6, amount: 450, bidder, para, first_period, last_period },
BidPlaced { height: 9, amount: 700, bidder, para, first_period, last_period },
]);
assert_eq!(
bids(),
vec![
BidPlaced { height: 5, amount: 250, bidder, para, first_period, last_period },
BidPlaced { height: 6, amount: 450, bidder, para, first_period, last_period },
BidPlaced { height: 9, amount: 700, bidder, para, first_period, last_period },
]
);
// Endings count incremented
assert_eq!(Crowdloan::endings_count(), 1);
@@ -1405,9 +1565,14 @@ mod tests {
// Set up a crowdloan ending on 9
assert_ok!(Crowdloan::create(Origin::signed(1), para, 100000, 1, 1, 9, None));
// Make more contributions than our limit
for i in 1 ..= RemoveKeysLimit::get() * 2 {
for i in 1..=RemoveKeysLimit::get() * 2 {
Balances::make_free_balance_be(&i.into(), (1000 * i).into());
assert_ok!(Crowdloan::contribute(Origin::signed(i.into()), para, (i * 100).into(), None));
assert_ok!(Crowdloan::contribute(
Origin::signed(i.into()),
para,
(i * 100).into(),
None
));
}
assert_eq!(Balances::free_balance(account_id), 21000);
@@ -1427,7 +1592,7 @@ mod tests {
// Funds are returned
assert_eq!(Balances::free_balance(account_id), 0);
// 1 deposit for the crowdloan which hasn't dissolved yet.
for i in 1 ..= RemoveKeysLimit::get() * 2 {
for i in 1..=RemoveKeysLimit::get() * 2 {
assert_eq!(Balances::free_balance(&i.into()), i as u64 * 1000);
}
});
@@ -1469,16 +1634,25 @@ mod tests {
assert_ok!(Crowdloan::contribute(Origin::signed(3), para, 50, None));
// Can't dissolve before it ends
assert_noop!(Crowdloan::dissolve(Origin::signed(1), para), Error::<Test>::NotReadyToDissolve);
assert_noop!(
Crowdloan::dissolve(Origin::signed(1), para),
Error::<Test>::NotReadyToDissolve
);
run_to_block(10);
set_winner(para, 1, true);
// Can't dissolve when it won.
assert_noop!(Crowdloan::dissolve(Origin::signed(1), para), Error::<Test>::NotReadyToDissolve);
assert_noop!(
Crowdloan::dissolve(Origin::signed(1), para),
Error::<Test>::NotReadyToDissolve
);
set_winner(para, 1, false);
// Can't dissolve while it still has user funds
assert_noop!(Crowdloan::dissolve(Origin::signed(1), para), Error::<Test>::NotReadyToDissolve);
assert_noop!(
Crowdloan::dissolve(Origin::signed(1), para),
Error::<Test>::NotReadyToDissolve
);
// All funds are refunded
assert_ok!(Crowdloan::refund(Origin::signed(2), para));
@@ -1508,7 +1682,10 @@ mod tests {
assert_ok!(Balances::reserve(&account_id, 150));
run_to_block(19);
assert_noop!(Crowdloan::withdraw(Origin::signed(2), 2, para), Error::<Test>::BidOrLeaseActive);
assert_noop!(
Crowdloan::withdraw(Origin::signed(2), 2, para),
Error::<Test>::BidOrLeaseActive
);
run_to_block(20);
// simulate the unreserving of para's funds, now that the lease expired. this actually
@@ -1566,7 +1743,6 @@ mod tests {
Crowdloan::create(Origin::signed(1), para_1, 1000, 1, 1, 9, None),
Error::<Test>::FundNotEnded,
);
});
}
@@ -1648,16 +1824,13 @@ mod tests {
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking {
use super::{*, Pallet as Crowdloan};
use super::{Pallet as Crowdloan, *};
use frame_support::{assert_ok, traits::OnInitialize};
use frame_system::RawOrigin;
use frame_support::{
assert_ok,
traits::OnInitialize,
};
use sp_runtime::traits::{Bounded, CheckedSub};
use sp_std::prelude::*;
use frame_benchmarking::{benchmarks, whitelisted_caller, account, impl_benchmark_test_suite};
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
fn assert_last_event<T: Config>(generic_event: <T as Config>::Event) {
let events = frame_system::Pallet::<T>::events();
@@ -1671,7 +1844,8 @@ mod benchmarking {
let cap = BalanceOf::<T>::max_value();
let lease_period_index = T::Auctioneer::lease_period_index();
let first_period = lease_period_index;
let last_period = lease_period_index + ((SlotRange::LEASE_PERIODS_PER_SLOT as u32) - 1).into();
let last_period =
lease_period_index + ((SlotRange::LEASE_PERIODS_PER_SLOT as u32) - 1).into();
let para_id = id.into();
let caller = account("fund_creator", id, 0);
@@ -1706,7 +1880,12 @@ mod benchmarking {
let payload = (index, &who, BalanceOf::<T>::default(), value);
let sig = crypto::create_ed25519_signature(&payload.encode(), pubkey);
assert_ok!(Crowdloan::<T>::contribute(RawOrigin::Signed(who.clone()).into(), index, value, Some(sig)));
assert_ok!(Crowdloan::<T>::contribute(
RawOrigin::Signed(who.clone()).into(),
index,
value,
Some(sig)
));
}
benchmarks! {
+1 -1
View File
@@ -16,12 +16,12 @@
//! Code for elections.
use super::{BlockExecutionWeight, BlockLength, BlockWeights};
use frame_support::{
parameter_types,
weights::{DispatchClass, Weight},
};
use sp_runtime::Perbill;
use super::{BlockExecutionWeight, BlockLength, BlockWeights};
parameter_types! {
/// A limit for off-chain phragmen unsigned solution submission.
+17 -10
View File
@@ -16,8 +16,8 @@
//! Auxiliary `struct`/`enum`s for polkadot runtime.
use frame_support::traits::{OnUnbalanced, Imbalance, Currency};
use crate::NegativeImbalance;
use frame_support::traits::{Currency, Imbalance, OnUnbalanced};
/// Logic for the author to get a portion of fees.
pub struct ToAuthor<R>(sp_std::marker::PhantomData<R>);
@@ -31,8 +31,14 @@ where
fn on_nonzero_unbalanced(amount: NegativeImbalance<R>) {
let numeric_amount = amount.peek();
let author = <pallet_authorship::Pallet<R>>::author();
<pallet_balances::Pallet<R>>::resolve_creating(&<pallet_authorship::Pallet<R>>::author(), amount);
<frame_system::Pallet<R>>::deposit_event(pallet_balances::Event::Deposit(author, numeric_amount));
<pallet_balances::Pallet<R>>::resolve_creating(
&<pallet_authorship::Pallet<R>>::author(),
amount,
);
<frame_system::Pallet<R>>::deposit_event(pallet_balances::Event::Deposit(
author,
numeric_amount,
));
}
}
@@ -45,7 +51,7 @@ where
<R as frame_system::Config>::AccountId: Into<primitives::v1::AccountId>,
<R as frame_system::Config>::Event: From<pallet_balances::Event<R>>,
{
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance<R>>) {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance<R>>) {
if let Some(fees) = fees_then_tips.next() {
// for fees, 80% to treasury, 20% to author
let mut split = fees.ration(80, 20);
@@ -60,20 +66,18 @@ where
}
}
#[cfg(test)]
mod tests {
use super::*;
use frame_support::{parameter_types, traits::FindAuthor, weights::DispatchClass, PalletId};
use frame_system::limits;
use frame_support::{parameter_types, PalletId, weights::DispatchClass};
use frame_support::traits::FindAuthor;
use primitives::v1::AccountId;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
Perbill,
};
use primitives::v1::AccountId;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -169,7 +173,8 @@ mod tests {
pub struct OneAuthor;
impl FindAuthor<AccountId> for OneAuthor {
fn find_author<'a, I>(_: I) -> Option<AccountId>
where I: 'a,
where
I: 'a,
{
Some(Default::default())
}
@@ -184,7 +189,9 @@ mod tests {
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
// We use default for brevity, but you can configure as desired if needed.
pallet_balances::GenesisConfig::<Test>::default().assimilate_storage(&mut t).unwrap();
pallet_balances::GenesisConfig::<Test>::default()
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
+219 -155
View File
@@ -16,33 +16,28 @@
//! Mocking utilities for testing with real pallets.
use sp_std::sync::Arc;
use sp_io::TestExternalities;
use sp_core::{H256, crypto::KeyTypeId};
use sp_runtime::{
traits::{
BlakeTwo256, IdentityLookup, One,
},
use crate::{
auctions, crowdloan, paras_registrar,
slot_range::SlotRange,
slots,
traits::{AuctionStatus, Auctioneer, Registrar as RegistrarT},
};
use sp_keystore::{KeystoreExt, testing::KeyStore};
use primitives::v1::{BlockNumber, Header, Id as ParaId, ValidationCode, HeadData, LOWEST_PUBLIC_ID};
use frame_support::{
parameter_types, assert_ok, assert_noop, PalletId,
traits::{Currency, OnInitialize, OnFinalize, KeyOwnerProofSystem, GenesisBuild},
};
use frame_system::EnsureRoot;
use runtime_parachains::{
ParaLifecycle, Origin as ParaOrigin,
paras, configuration, shared,
assert_noop, assert_ok, parameter_types,
traits::{Currency, GenesisBuild, KeyOwnerProofSystem, OnFinalize, OnInitialize},
PalletId,
};
use frame_support_test::TestRandomness;
use crate::{
auctions, crowdloan, slots, paras_registrar,
slot_range::SlotRange,
traits::{
Registrar as RegistrarT, Auctioneer, AuctionStatus,
},
use frame_system::EnsureRoot;
use primitives::v1::{
BlockNumber, HeadData, Header, Id as ParaId, ValidationCode, LOWEST_PUBLIC_ID,
};
use runtime_parachains::{configuration, paras, shared, Origin as ParaOrigin, ParaLifecycle};
use sp_core::{crypto::KeyTypeId, H256};
use sp_io::TestExternalities;
use sp_keystore::{testing::KeyStore, KeystoreExt};
use sp_runtime::traits::{BlakeTwo256, IdentityLookup, One};
use sp_std::sync::Arc;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -75,8 +70,7 @@ frame_support::construct_runtime!(
}
);
use crate::crowdloan::Error as CrowdloanError;
use crate::auctions::Error as AuctionsError;
use crate::{auctions::Error as AuctionsError, crowdloan::Error as CrowdloanError};
parameter_types! {
pub const BlockHashCount: u32 = 250;
@@ -121,8 +115,10 @@ impl pallet_babe::Config for Test {
type ExpectedBlockTime = ExpectedBlockTime;
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
type KeyOwnerProofSystem = ();
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof;
type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
@@ -159,9 +155,9 @@ impl pallet_balances::Config for Test {
type ReserveIdentifier = [u8; 8];
}
impl configuration::Config for Test { }
impl configuration::Config for Test {}
impl shared::Config for Test { }
impl shared::Config for Test {}
impl paras::Config for Test {
type Origin = Origin;
@@ -236,14 +232,15 @@ pub fn new_test_ext() -> TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisBuild::<Test>::assimilate_storage(
&configuration::GenesisConfig {
config: configuration::HostConfiguration {
max_code_size: 2 * 1024 * 1024, // 2 MB
max_head_data_size: 1 * 1024 * 1024, // 1 MB
..Default::default()
}
config: configuration::HostConfiguration {
max_code_size: 2 * 1024 * 1024, // 2 MB
max_head_data_size: 1 * 1024 * 1024, // 1 MB
..Default::default()
},
&mut t
).unwrap();
},
&mut t,
)
.unwrap();
let keystore = KeyStore::new();
let mut ext: sp_io::TestExternalities = t.into();
ext.register_extension(KeystoreExt(Arc::new(keystore)));
@@ -255,9 +252,7 @@ const BLOCKS_PER_SESSION: u32 = 10;
fn maybe_new_session(n: u32) {
if n % BLOCKS_PER_SESSION == 0 {
shared::Pallet::<Test>::set_session_index(
shared::Pallet::<Test>::session_index() + 1
);
shared::Pallet::<Test>::set_session_index(shared::Pallet::<Test>::session_index() + 1);
Paras::test_on_new_session();
}
}
@@ -343,10 +338,10 @@ fn basic_end_to_end_works() {
assert_ok!(Crowdloan::create(
Origin::signed(2),
ParaId::from(para_2),
1_000, // Cap
1_000, // Cap
lease_period_index_start + 2, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End
200, // Block End
None,
));
let crowdloan_account = Crowdloan::fund_account_id(ParaId::from(para_2));
@@ -361,10 +356,10 @@ fn basic_end_to_end_works() {
assert_ok!(Auctions::bid(
Origin::signed(10),
ParaId::from(para_1),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
910, // Amount
910, // Amount
));
// User 2 will be a contribute to crowdloan for parachain 2
@@ -378,10 +373,7 @@ fn basic_end_to_end_works() {
crowdloan::Event::<Test>::HandleBidResult(ParaId::from(para_2), Ok(())).into(),
);
run_to_block(110);
assert_eq!(
last_event(),
auctions::Event::<Test>::AuctionClosed(1).into(),
);
assert_eq!(last_event(), auctions::Event::<Test>::AuctionClosed(1).into(),);
// Paras should have won slots
assert_eq!(
@@ -392,19 +384,33 @@ fn basic_end_to_end_works() {
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(para_2)),
// -- 1 --- 2 --- 3 --- 4 --- 5 ---------------- 6 --------------------------- 7 ----------------
vec![None, None, None, None, None, Some((crowdloan_account, 920)), Some((crowdloan_account, 920))],
vec![
None,
None,
None,
None,
None,
Some((crowdloan_account, 920)),
Some((crowdloan_account, 920))
],
);
// Should not be able to contribute to a winning crowdloan
Balances::make_free_balance_be(&3, 1_000_000_000);
assert_noop!(Crowdloan::contribute(Origin::signed(3), ParaId::from(2001), 10, None), CrowdloanError::<Test>::BidOrLeaseActive);
assert_noop!(
Crowdloan::contribute(Origin::signed(3), ParaId::from(2001), 10, None),
CrowdloanError::<Test>::BidOrLeaseActive
);
// New leases will start on block 400
let lease_start_block = 400;
run_to_block(lease_start_block);
// First slot, Para 1 should be transitioning to Parachain
assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::UpgradingParathread));
assert_eq!(
Paras::lifecycle(ParaId::from(para_1)),
Some(ParaLifecycle::UpgradingParathread)
);
assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));
// Two sessions later, it has upgraded
@@ -419,8 +425,14 @@ fn basic_end_to_end_works() {
// Third slot, Para 2 should be upgrading, and Para 1 is downgrading
run_to_block(lease_start_block + 200);
assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::DowngradingParachain));
assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::UpgradingParathread));
assert_eq!(
Paras::lifecycle(ParaId::from(para_1)),
Some(ParaLifecycle::DowngradingParachain)
);
assert_eq!(
Paras::lifecycle(ParaId::from(para_2)),
Some(ParaLifecycle::UpgradingParathread)
);
// Two sessions later, they have transitioned
run_to_block(lease_start_block + 220);
@@ -435,7 +447,10 @@ fn basic_end_to_end_works() {
// Fifth slot, Para 2 is downgrading
run_to_block(lease_start_block + 400);
assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::DowngradingParachain));
assert_eq!(
Paras::lifecycle(ParaId::from(para_2)),
Some(ParaLifecycle::DowngradingParachain)
);
// Two sessions later, Para 2 is downgraded
run_to_block(lease_start_block + 420);
@@ -463,12 +478,10 @@ fn basic_errors_fail() {
validation_code.clone(),
));
assert_ok!(Registrar::reserve(Origin::signed(2)));
assert_noop!(Registrar::register(
Origin::signed(2),
para_id,
genesis_head,
validation_code,
), paras_registrar::Error::<Test>::NotOwner);
assert_noop!(
Registrar::register(Origin::signed(2), para_id, genesis_head, validation_code,),
paras_registrar::Error::<Test>::NotOwner
);
// Start an auction
let duration = 99u32;
@@ -476,15 +489,18 @@ fn basic_errors_fail() {
assert_ok!(Auctions::new_auction(Origin::root(), duration, lease_period_index_start));
// Cannot create a crowdloan if you do not own the para
assert_noop!(Crowdloan::create(
Origin::signed(2),
para_id,
1_000, // Cap
lease_period_index_start + 2, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End
None,
), crowdloan::Error::<Test>::InvalidOrigin);
assert_noop!(
Crowdloan::create(
Origin::signed(2),
para_id,
1_000, // Cap
lease_period_index_start + 2, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End
None,
),
crowdloan::Error::<Test>::InvalidOrigin
);
});
}
@@ -497,7 +513,7 @@ fn competing_slots() {
let para_id = LOWEST_PUBLIC_ID;
// Create n paras and owners
for n in 1 ..= max_bids {
for n in 1..=max_bids {
Balances::make_free_balance_be(&n, 1_000_000_000);
let genesis_head = Registrar::worst_head_data();
let validation_code = Registrar::worst_validation_code();
@@ -518,22 +534,22 @@ fn competing_slots() {
// Paras should be onboarded
run_to_block(20); // session 2
for n in 1 ..= max_bids {
for n in 1..=max_bids {
// Increment block number
run_to_block(System::block_number() + 10);
Balances::make_free_balance_be(&(n * 10), n * 1_000);
let (start, end) = match n {
1 => (0, 0),
2 => (0, 1),
3 => (0, 2),
4 => (0, 3),
5 => (1, 1),
6 => (1, 2),
7 => (1, 3),
8 => (2, 2),
9 => (2, 3),
1 => (0, 0),
2 => (0, 1),
3 => (0, 2),
4 => (0, 3),
5 => (1, 1),
6 => (1, 2),
7 => (1, 3),
8 => (2, 2),
9 => (2, 3),
10 => (3, 3),
_ => panic!("test not meant for this"),
};
@@ -542,10 +558,10 @@ fn competing_slots() {
assert_ok!(Auctions::bid(
Origin::signed(n * 10),
para_id + n - 1,
1, // Auction Index
1, // Auction Index
lease_period_index_start + start, // First Slot
lease_period_index_start + end, // Last slot
n * 900, // Amount
lease_period_index_start + end, // Last slot
n * 900, // Amount
));
}
@@ -582,7 +598,7 @@ fn competing_bids() {
let start_para = LOWEST_PUBLIC_ID - 1;
// Create 3 paras and owners
for n in 1 ..= 3 {
for n in 1..=3 {
Balances::make_free_balance_be(&n, 1_000_000_000);
let genesis_head = Registrar::worst_head_data();
let validation_code = Registrar::worst_validation_code();
@@ -604,20 +620,20 @@ fn competing_bids() {
let lease_period_index_start = 4u32;
assert_ok!(Auctions::new_auction(Origin::root(), duration, lease_period_index_start));
for n in 1 ..= 3 {
for n in 1..=3 {
// Create a crowdloan for each para
assert_ok!(Crowdloan::create(
Origin::signed(n),
ParaId::from(start_para + n),
100_000, // Cap
100_000, // Cap
lease_period_index_start + 2, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End,
200, // Block End,
None,
));
}
for n in 1 ..= 9 {
for n in 1..=9 {
// Increment block number
run_to_block(starting_block + n * 10);
@@ -630,10 +646,10 @@ fn competing_bids() {
assert_ok!(Auctions::bid(
Origin::signed(n * 10),
ParaId::from(para),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
n * 900, // Amount
n * 900, // Amount
));
} else {
// User 20 will be a contribute to crowdloan for parachain 2
@@ -654,7 +670,15 @@ fn competing_bids() {
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(2000)),
// -- 1 --- 2 --- 3 --- 4 --- 5 ------------- 6 ------------------------ 7 -------------
vec![None, None, None, None, None, Some((crowdloan_2, 1812)), Some((crowdloan_2, 1812))],
vec![
None,
None,
None,
None,
None,
Some((crowdloan_2, 1812)),
Some((crowdloan_2, 1812))
],
);
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(2002)),
@@ -669,7 +693,7 @@ fn basic_swap_works() {
// This test will test a swap between a parachain and parathread works successfully.
new_test_ext().execute_with(|| {
assert!(System::block_number().is_one()); // So events are emitted
// User 1 and 2 will own paras
// User 1 and 2 will own paras
Balances::make_free_balance_be(&1, 1_000_000_000);
Balances::make_free_balance_be(&2, 1_000_000_000);
// First register 2 parathreads with different data
@@ -706,17 +730,17 @@ fn basic_swap_works() {
assert_ok!(Crowdloan::create(
Origin::signed(1),
ParaId::from(2000),
1_000_000, // Cap
1_000_000, // Cap
lease_period_index_start + 0, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End
200, // Block End
None,
));
let crowdloan_account = Crowdloan::fund_account_id(ParaId::from(2000));
// Bunch of contributions
let mut total = 0;
for i in 10 .. 20 {
for i in 10..20 {
Balances::make_free_balance_be(&i, 1_000_000_000);
assert_ok!(Crowdloan::contribute(Origin::signed(i), ParaId::from(2000), 900 - i, None));
total += 900 - i;
@@ -750,8 +774,16 @@ fn basic_swap_works() {
assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Parathread));
// Initiate a swap
assert_ok!(Registrar::swap(para_origin(2000).into(), ParaId::from(2000), ParaId::from(2001)));
assert_ok!(Registrar::swap(para_origin(2001).into(), ParaId::from(2001), ParaId::from(2000)));
assert_ok!(Registrar::swap(
para_origin(2000).into(),
ParaId::from(2000),
ParaId::from(2001)
));
assert_ok!(Registrar::swap(
para_origin(2001).into(),
ParaId::from(2001),
ParaId::from(2000)
));
assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::DowngradingParachain));
assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::UpgradingParathread));
@@ -774,15 +806,21 @@ fn basic_swap_works() {
assert!(!Slots::lease(ParaId::from(2001)).is_empty());
// Cant dissolve
assert_noop!(Crowdloan::dissolve(Origin::signed(1), ParaId::from(2000)), CrowdloanError::<Test>::InvalidParaId);
assert_noop!(Crowdloan::dissolve(Origin::signed(2), ParaId::from(2001)), CrowdloanError::<Test>::NotReadyToDissolve);
assert_noop!(
Crowdloan::dissolve(Origin::signed(1), ParaId::from(2000)),
CrowdloanError::<Test>::InvalidParaId
);
assert_noop!(
Crowdloan::dissolve(Origin::signed(2), ParaId::from(2001)),
CrowdloanError::<Test>::NotReadyToDissolve
);
// Go way in the future when the para is offboarded
run_to_block(lease_start_block + 1000);
// Withdraw of contributions works
assert_eq!(Balances::free_balance(&crowdloan_account), total);
for i in 10 .. 20 {
for i in 10..20 {
assert_ok!(Crowdloan::withdraw(Origin::signed(i), i, ParaId::from(2001)));
}
assert_eq!(Balances::free_balance(&crowdloan_account), 0);
@@ -802,7 +840,7 @@ fn basic_swap_works() {
fn crowdloan_ending_period_bid() {
new_test_ext().execute_with(|| {
assert!(System::block_number().is_one()); // So events are emitted
// User 1 and 2 will own paras
// User 1 and 2 will own paras
Balances::make_free_balance_be(&1, 1_000_000_000);
Balances::make_free_balance_be(&2, 1_000_000_000);
// First register 2 parathreads
@@ -839,17 +877,17 @@ fn crowdloan_ending_period_bid() {
assert_ok!(Crowdloan::create(
Origin::signed(1),
ParaId::from(2000),
1_000_000, // Cap
1_000_000, // Cap
lease_period_index_start + 0, // First Slot
lease_period_index_start + 3, // Last Slot
200, // Block End
200, // Block End
None,
));
let crowdloan_account = Crowdloan::fund_account_id(ParaId::from(2000));
// Bunch of contributions
let mut total = 0;
for i in 10 .. 20 {
for i in 10..20 {
Balances::make_free_balance_be(&i, 1_000_000_000);
assert_ok!(Crowdloan::contribute(Origin::signed(i), ParaId::from(2000), 900 - i, None));
total += 900 - i;
@@ -862,10 +900,10 @@ fn crowdloan_ending_period_bid() {
assert_ok!(Auctions::bid(
Origin::signed(2),
ParaId::from(2001),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
900, // Amount
));
// Go to beginning of ending period
@@ -874,7 +912,8 @@ fn crowdloan_ending_period_bid() {
assert_eq!(Auctions::auction_status(100), AuctionStatus::<u32>::EndingPeriod(0, 0));
let mut winning = [None; SlotRange::SLOT_RANGE_COUNT];
winning[SlotRange::ZeroOne as u8 as usize] = Some((2, ParaId::from(2001), 900));
winning[SlotRange::ZeroThree as u8 as usize] = Some((crowdloan_account, ParaId::from(2000), total));
winning[SlotRange::ZeroThree as u8 as usize] =
Some((crowdloan_account, ParaId::from(2000), total));
assert_eq!(Auctions::winning(0), Some(winning));
@@ -887,7 +926,8 @@ fn crowdloan_ending_period_bid() {
run_to_block(102);
let mut winning = [None; SlotRange::SLOT_RANGE_COUNT];
winning[SlotRange::ZeroOne as u8 as usize] = Some((2, ParaId::from(2001), 900));
winning[SlotRange::ZeroThree as u8 as usize] = Some((crowdloan_account, ParaId::from(2000), total + 900));
winning[SlotRange::ZeroThree as u8 as usize] =
Some((crowdloan_account, ParaId::from(2000), total + 900));
assert_eq!(Auctions::winning(2), Some(winning));
})
}
@@ -904,14 +944,17 @@ fn auction_bid_requires_registered_para() {
// Can't bid with non-registered paras
Balances::make_free_balance_be(&1, 1_000_000_000);
assert_noop!(Auctions::bid(
Origin::signed(1),
ParaId::from(2000),
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
), AuctionsError::<Test>::ParaNotRegistered);
assert_noop!(
Auctions::bid(
Origin::signed(1),
ParaId::from(2000),
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
),
AuctionsError::<Test>::ParaNotRegistered
);
// Now we register the para
assert_ok!(Registrar::reserve(Origin::signed(1)));
@@ -923,14 +966,17 @@ fn auction_bid_requires_registered_para() {
));
// Still can't bid until it is fully onboarded
assert_noop!(Auctions::bid(
Origin::signed(1),
ParaId::from(2000),
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
), AuctionsError::<Test>::ParaNotRegistered);
assert_noop!(
Auctions::bid(
Origin::signed(1),
ParaId::from(2000),
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
),
AuctionsError::<Test>::ParaNotRegistered
);
// Onboarded on Session 2
run_to_session(2);
@@ -940,10 +986,10 @@ fn auction_bid_requires_registered_para() {
assert_ok!(Auctions::bid(
Origin::signed(1),
ParaId::from(2000),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last slot
900, // Amount
900, // Amount
));
});
}
@@ -986,29 +1032,29 @@ fn gap_bids_work() {
assert_ok!(Auctions::bid(
Origin::signed(10),
ParaId::from(2000),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 0, // First Slot
lease_period_index_start + 0, // Last slot
100, // Amount
100, // Amount
));
// Slot 4 for 400 from 10
assert_ok!(Auctions::bid(
Origin::signed(10),
ParaId::from(2000),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 3, // First Slot
lease_period_index_start + 3, // Last slot
400, // Amount
400, // Amount
));
// A bid for another para is counted separately.
assert_ok!(Auctions::bid(
Origin::signed(10),
ParaId::from(2001),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 1, // First Slot
lease_period_index_start + 1, // Last slot
555, // Amount
555, // Amount
));
assert_eq!(Balances::reserved_balance(&10), 400 + 555);
@@ -1016,19 +1062,19 @@ fn gap_bids_work() {
assert_ok!(Auctions::bid(
Origin::signed(20),
ParaId::from(2000),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 1, // First Slot
lease_period_index_start + 1, // Last slot
800, // Amount
800, // Amount
));
// Slot 3 for 200 from 20
assert_ok!(Auctions::bid(
Origin::signed(20),
ParaId::from(2000),
1, // Auction Index
1, // Auction Index
lease_period_index_start + 2, // First Slot
lease_period_index_start + 2, // Last slot
200, // Amount
200, // Amount
));
// Finish the auction
@@ -1038,7 +1084,15 @@ fn gap_bids_work() {
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(2000)),
// -- 1 --- 2 --- 3 ---------- 4 -------------- 5 -------------- 6 -------------- 7 -------
vec![None, None, None, Some((10, 100)), Some((20, 800)), Some((20, 200)), Some((10, 400))],
vec![
None,
None,
None,
Some((10, 100)),
Some((20, 800)),
Some((20, 200)),
Some((10, 400))
],
);
// Appropriate amount is reserved (largest of the values)
assert_eq!(Balances::reserved_balance(&10), 400);
@@ -1125,17 +1179,17 @@ fn cant_bid_on_existing_lease_periods() {
assert_ok!(Crowdloan::create(
Origin::signed(1),
ParaId::from(2000),
1_000_000, // Cap
1_000_000, // Cap
lease_period_index_start + 0, // First Slot
lease_period_index_start + 1, // Last Slot
400, // Long block end
400, // Long block end
None,
));
let crowdloan_account = Crowdloan::fund_account_id(ParaId::from(2000));
// Bunch of contributions
let mut total = 0;
for i in 10 .. 20 {
for i in 10..20 {
Balances::make_free_balance_be(&i, 1_000_000_000);
assert_ok!(Crowdloan::contribute(Origin::signed(i), ParaId::from(2000), 900 - i, None));
total += 900 - i;
@@ -1150,7 +1204,13 @@ fn cant_bid_on_existing_lease_periods() {
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(2000)),
// -- 1 --- 2 --- 3 ------------- 4 ------------------------ 5 -------------
vec![None, None, None, Some((crowdloan_account, 8855)), Some((crowdloan_account, 8855))],
vec![
None,
None,
None,
Some((crowdloan_account, 8855)),
Some((crowdloan_account, 8855))
],
);
// Let's start another auction for the same range
@@ -1175,7 +1235,8 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start + 0,
lease_period_index_start + 1,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
assert_noop!(
@@ -1186,7 +1247,8 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start + 1,
lease_period_index_start + 2,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
assert_noop!(
@@ -1197,7 +1259,8 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start - 1,
lease_period_index_start + 0,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
assert_noop!(
@@ -1208,7 +1271,8 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start + 0,
lease_period_index_start + 0,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
assert_noop!(
@@ -1219,7 +1283,8 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start + 1,
lease_period_index_start + 1,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
assert_noop!(
@@ -1230,19 +1295,18 @@ fn cant_bid_on_existing_lease_periods() {
lease_period_index_start - 1,
lease_period_index_start + 5,
100,
), AuctionsError::<Test>::AlreadyLeasedOut,
),
AuctionsError::<Test>::AlreadyLeasedOut,
);
// Will work when not overlapping
assert_ok!(
Auctions::bid(
Origin::signed(crowdloan_account),
ParaId::from(2000),
2,
lease_period_index_start + 2,
lease_period_index_start + 3,
100,
)
);
assert_ok!(Auctions::bid(
Origin::signed(crowdloan_account),
ParaId::from(2000),
2,
lease_period_index_start + 2,
lease_period_index_start + 3,
100,
));
});
}
+56 -48
View File
@@ -18,47 +18,52 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod claims;
pub mod slots;
pub mod auctions;
pub mod claims;
pub mod crowdloan;
pub mod purchase;
pub mod elections;
pub mod impls;
pub mod paras_sudo_wrapper;
pub mod paras_registrar;
pub mod paras_sudo_wrapper;
pub mod purchase;
pub mod slot_range;
pub mod slots;
pub mod traits;
pub mod xcm_sender;
pub mod elections;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod integration_tests;
#[cfg(test)]
mod mock;
use primitives::v1::{AssignmentId, BlockNumber, ValidatorId};
use sp_runtime::{Perquintill, Perbill, FixedPointNumber};
use frame_system::limits;
use frame_support::{
parameter_types, traits::{Currency, OneSessionHandler},
weights::{Weight, constants::WEIGHT_PER_SECOND, DispatchClass},
pub use frame_support::weights::constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
};
use pallet_transaction_payment::{TargetedFeeAdjustment, Multiplier};
use frame_support::{
parameter_types,
traits::{Currency, OneSessionHandler},
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, Weight},
};
use frame_system::limits;
use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};
use primitives::v1::{AssignmentId, BlockNumber, ValidatorId};
use sp_runtime::{FixedPointNumber, Perbill, Perquintill};
use static_assertions::const_assert;
pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
pub use elections::{OffchainSolutionLengthLimit, OffchainSolutionWeightLimit};
pub use pallet_balances::Call as BalancesCall;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use elections::{OffchainSolutionLengthLimit, OffchainSolutionWeightLimit};
/// Implementations of some helper traits passed into runtime modules as associated types.
pub use impls::ToAuthor;
pub type NegativeImbalance<T> = <pallet_balances::Pallet<T> as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
pub type NegativeImbalance<T> = <pallet_balances::Pallet<T> as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
/// We assume that an on-initialize consumes 1% of the weight on average, hence a single extrinsic
/// will not be allowed to consume more than `AvailableBlockRatio - 1%`.
@@ -110,12 +115,8 @@ parameter_types! {
/// Parameterized slow adjusting fee updated based on
/// https://w3f-research.readthedocs.io/en/latest/polkadot/Token%20Economics.html#-2.-slow-adjusting-mechanism
pub type SlowAdjustingFeeUpdate<R> = TargetedFeeAdjustment<
R,
TargetBlockFullness,
AdjustmentVariable,
MinimumMultiplier
>;
pub type SlowAdjustingFeeUpdate<R> =
TargetedFeeAdjustment<R, TargetBlockFullness, AdjustmentVariable, MinimumMultiplier>;
/// The type used for currency conversion.
///
@@ -130,25 +131,26 @@ impl<T> sp_runtime::BoundToRuntimeAppPublic for ParachainSessionKeyPlaceholder<T
type Public = ValidatorId;
}
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId> for ParachainSessionKeyPlaceholder<T>
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId>
for ParachainSessionKeyPlaceholder<T>
{
type Key = ValidatorId;
fn on_genesis_session<'a, I: 'a>(_validators: I) where
fn on_genesis_session<'a, I: 'a>(_validators: I)
where
I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
T::AccountId: 'a
T::AccountId: 'a,
{
}
fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I) where
fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I)
where
I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
T::AccountId: 'a
T::AccountId: 'a,
{
}
fn on_disabled(_: usize) { }
fn on_disabled(_: usize) {}
}
/// A placeholder since there is currently no provided session key handler for parachain validator
@@ -158,25 +160,26 @@ impl<T> sp_runtime::BoundToRuntimeAppPublic for AssignmentSessionKeyPlaceholder<
type Public = AssignmentId;
}
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId> for AssignmentSessionKeyPlaceholder<T>
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId>
for AssignmentSessionKeyPlaceholder<T>
{
type Key = AssignmentId;
fn on_genesis_session<'a, I: 'a>(_validators: I) where
fn on_genesis_session<'a, I: 'a>(_validators: I)
where
I: Iterator<Item = (&'a T::AccountId, AssignmentId)>,
T::AccountId: 'a
T::AccountId: 'a,
{
}
fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I) where
fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I)
where
I: Iterator<Item = (&'a T::AccountId, AssignmentId)>,
T::AccountId: 'a
T::AccountId: 'a,
{
}
fn on_disabled(_: usize) { }
fn on_disabled(_: usize) {}
}
#[cfg(test)]
@@ -186,7 +189,7 @@ mod multiplier_tests {
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup, Convert, One},
traits::{BlakeTwo256, Convert, IdentityLookup, One},
Perbill,
};
@@ -238,9 +241,14 @@ mod multiplier_tests {
type OnSetCode = ();
}
fn run_with_system_weight<F>(w: Weight, mut assertions: F) where F: FnMut() -> () {
let mut t: sp_io::TestExternalities =
frame_system::GenesisConfig::default().build_storage::<Runtime>().unwrap().into();
fn run_with_system_weight<F>(w: Weight, mut assertions: F)
where
F: FnMut() -> (),
{
let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap()
.into();
t.execute_with(|| {
System::set_block_consumed_resources(w, 0);
assertions()
@@ -266,9 +274,9 @@ mod multiplier_tests {
// assume the multiplier is initially set to its minimum. We update it with values twice the
//target (target is 25%, thus 50%) and we see at which point it reaches 1.
let mut multiplier = MinimumMultiplier::get();
let block_weight = TargetBlockFullness::get()
* BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap()
* 2;
let block_weight = TargetBlockFullness::get() *
BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() *
2;
let mut blocks = 0;
while multiplier <= Multiplier::one() {
run_with_system_weight(block_weight, || {
+23 -13
View File
@@ -16,12 +16,12 @@
//! Mocking utilities for testing.
use std::{cell::RefCell, collections::HashMap};
use parity_scale_codec::{Encode, Decode};
use sp_runtime::traits::SaturatedConversion;
use frame_support::dispatch::{DispatchError, DispatchResult};
use primitives::v1::{HeadData, ValidationCode, Id as ParaId};
use crate::traits::Registrar;
use frame_support::dispatch::{DispatchError, DispatchResult};
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{HeadData, Id as ParaId, ValidationCode};
use sp_runtime::traits::SaturatedConversion;
use std::{cell::RefCell, collections::HashMap};
thread_local! {
static OPERATIONS: RefCell<Vec<(ParaId, u32, bool)>> = RefCell::new(Vec::new());
@@ -130,9 +130,13 @@ impl<T: frame_system::Config> Registrar for TestRegistrar<T> {
},
}
})?;
OPERATIONS.with(|x| x.borrow_mut().push(
(id, frame_system::Pallet::<T>::block_number().saturated_into(), true)
));
OPERATIONS.with(|x| {
x.borrow_mut().push((
id,
frame_system::Pallet::<T>::block_number().saturated_into(),
true,
))
});
Ok(())
}
fn make_parathread(id: ParaId) -> DispatchResult {
@@ -149,16 +153,21 @@ impl<T: frame_system::Config> Registrar for TestRegistrar<T> {
PARATHREADS.with(|x| {
let mut parathreads = x.borrow_mut();
match parathreads.binary_search(&id) {
Ok(_) => Err(DispatchError::Other("already parathread, so cannot `make_parathread`")),
Ok(_) =>
Err(DispatchError::Other("already parathread, so cannot `make_parathread`")),
Err(i) => {
parathreads.insert(i, id);
Ok(())
},
}
})?;
OPERATIONS.with(|x| x.borrow_mut().push(
(id, frame_system::Pallet::<T>::block_number().saturated_into(), false)
));
OPERATIONS.with(|x| {
x.borrow_mut().push((
id,
frame_system::Pallet::<T>::block_number().saturated_into(),
false,
))
});
Ok(())
}
@@ -179,7 +188,8 @@ impl<T: frame_system::Config> Registrar for TestRegistrar<T> {
impl<T: frame_system::Config> TestRegistrar<T> {
pub fn operations() -> Vec<(ParaId, T::BlockNumber, bool)> {
OPERATIONS.with(|x| x.borrow().iter().map(|(p, b, c)| (*p, (*b).into(), *c)).collect::<Vec<_>>())
OPERATIONS
.with(|x| x.borrow().iter().map(|(p, b, c)| (*p, (*b).into(), *c)).collect::<Vec<_>>())
}
#[allow(dead_code)]
+179 -166
View File
@@ -17,31 +17,28 @@
//! Pallet to handle parathread/parachain registration and related fund management.
//! In essence this is a simple wrapper around `paras`.
use sp_std::{prelude::*, result};
use frame_support::{
ensure,
dispatch::DispatchResult,
traits::{Get, Currency, ReservableCurrency},
ensure,
pallet_prelude::Weight,
traits::{Currency, Get, ReservableCurrency},
};
use frame_system::{self, ensure_root, ensure_signed};
use primitives::v1::{
Id as ParaId, ValidationCode, HeadData, LOWEST_PUBLIC_ID,
};
use primitives::v1::{HeadData, Id as ParaId, ValidationCode, LOWEST_PUBLIC_ID};
use runtime_parachains::{
paras::{
self,
ParaGenesisArgs,
},
configuration,
ensure_parachain,
configuration, ensure_parachain,
paras::{self, ParaGenesisArgs},
Origin, ParaLifecycle,
};
use sp_std::{prelude::*, result};
use crate::traits::{Registrar, OnSwap};
use parity_scale_codec::{Encode, Decode};
use sp_runtime::{RuntimeDebug, traits::{Saturating, CheckedSub}};
use crate::traits::{OnSwap, Registrar};
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
use sp_runtime::{
traits::{CheckedSub, Saturating},
RuntimeDebug,
};
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug)]
pub struct ParaInfo<Account, Balance> {
@@ -66,18 +63,28 @@ pub trait WeightInfo {
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn reserve() -> Weight { 0 }
fn register() -> Weight { 0 }
fn force_register() -> Weight { 0 }
fn deregister() -> Weight { 0 }
fn swap() -> Weight { 0 }
fn reserve() -> Weight {
0
}
fn register() -> Weight {
0
}
fn force_register() -> Weight {
0
}
fn deregister() -> Weight {
0
}
fn swap() -> Weight {
0
}
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -161,7 +168,8 @@ pub mod pallet {
/// The given account ID is responsible for registering the code and initial head data, but may only do
/// so if it isn't yet registered. (After that, it's up to governance to do so.)
#[pallet::storage]
pub type Paras<T: Config> = StorageMap<_, Twox64Concat, ParaId, ParaInfo<T::AccountId, BalanceOf<T>>>;
pub type Paras<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ParaInfo<T::AccountId, BalanceOf<T>>>;
/// The next free `ParaId`.
#[pallet::storage]
@@ -363,8 +371,12 @@ impl<T: Config> Registrar for Pallet<T> {
// Upgrade a registered parathread into a parachain.
fn make_parachain(id: ParaId) -> DispatchResult {
// Para backend should think this is a parathread...
ensure!(paras::Pallet::<T>::lifecycle(id) == Some(ParaLifecycle::Parathread), Error::<T>::NotParathread);
runtime_parachains::schedule_parathread_upgrade::<T>(id).map_err(|_| Error::<T>::CannotUpgrade)?;
ensure!(
paras::Pallet::<T>::lifecycle(id) == Some(ParaLifecycle::Parathread),
Error::<T>::NotParathread
);
runtime_parachains::schedule_parathread_upgrade::<T>(id)
.map_err(|_| Error::<T>::CannotUpgrade)?;
// Once a para has upgraded to a parachain, it can no longer be managed by the owner.
// Intentionally, the flag stays with the para even after downgrade.
Self::apply_lock(id);
@@ -374,8 +386,12 @@ impl<T: Config> Registrar for Pallet<T> {
// Downgrade a registered para into a parathread.
fn make_parathread(id: ParaId) -> DispatchResult {
// Para backend should think this is a parachain...
ensure!(paras::Pallet::<T>::lifecycle(id) == Some(ParaLifecycle::Parachain), Error::<T>::NotParachain);
runtime_parachains::schedule_parachain_downgrade::<T>(id).map_err(|_| Error::<T>::CannotDowngrade)?;
ensure!(
paras::Pallet::<T>::lifecycle(id) == Some(ParaLifecycle::Parachain),
Error::<T>::NotParachain
);
runtime_parachains::schedule_parachain_downgrade::<T>(id)
.map_err(|_| Error::<T>::CannotDowngrade)?;
Ok(())
}
@@ -397,9 +413,7 @@ impl<T: Config> Registrar for Pallet<T> {
#[cfg(any(feature = "runtime-benchmarks", test))]
fn execute_pending_transitions() {
use runtime_parachains::shared;
shared::Pallet::<T>::set_session_index(
shared::Pallet::<T>::scheduled_session()
);
shared::Pallet::<T>::set_session_index(shared::Pallet::<T>::scheduled_session());
paras::Pallet::<T>::test_on_new_session();
}
}
@@ -407,23 +421,28 @@ impl<T: Config> Registrar for Pallet<T> {
impl<T: Config> Pallet<T> {
/// Ensure the origin is one of Root, the `para` owner, or the `para` itself.
/// If the origin is the `para` owner, the `para` must be unlocked.
fn ensure_root_para_or_owner(origin: <T as frame_system::Config>::Origin, id: ParaId) -> DispatchResult {
ensure_signed(origin.clone()).map_err(|e| e.into())
.and_then(|who| -> DispatchResult {
let para_info = Paras::<T>::get(id).ok_or(Error::<T>::NotRegistered)?;
ensure!(!para_info.locked, Error::<T>::ParaLocked);
ensure!(para_info.manager == who, Error::<T>::NotOwner);
Ok(())
})
.or_else(|_| -> DispatchResult {
// Else check if para origin...
let caller_id = ensure_parachain(<T as Config>::Origin::from(origin.clone()))?;
ensure!(caller_id == id, Error::<T>::NotOwner);
Ok(())
}).or_else(|_| -> DispatchResult {
// Check if root...
ensure_root(origin.clone()).map_err(|e| e.into())
})
fn ensure_root_para_or_owner(
origin: <T as frame_system::Config>::Origin,
id: ParaId,
) -> DispatchResult {
ensure_signed(origin.clone())
.map_err(|e| e.into())
.and_then(|who| -> DispatchResult {
let para_info = Paras::<T>::get(id).ok_or(Error::<T>::NotRegistered)?;
ensure!(!para_info.locked, Error::<T>::ParaLocked);
ensure!(para_info.manager == who, Error::<T>::NotOwner);
Ok(())
})
.or_else(|_| -> DispatchResult {
// Else check if para origin...
let caller_id = ensure_parachain(<T as Config>::Origin::from(origin.clone()))?;
ensure!(caller_id == id, Error::<T>::NotOwner);
Ok(())
})
.or_else(|_| -> DispatchResult {
// Check if root...
ensure_root(origin.clone()).map_err(|e| e.into())
})
}
fn do_reserve(
@@ -436,11 +455,7 @@ impl<T: Config> Pallet<T> {
let deposit = deposit_override.unwrap_or_else(T::ParaDeposit::get);
<T as Config>::Currency::reserve(&who, deposit)?;
let info = ParaInfo {
manager: who.clone(),
deposit,
locked: false,
};
let info = ParaInfo { manager: who.clone(), deposit, locked: false };
Paras::<T>::insert(id, info);
Self::deposit_event(Event::<T>::Reserved(id, who));
@@ -466,11 +481,8 @@ impl<T: Config> Pallet<T> {
Default::default()
};
ensure!(paras::Pallet::<T>::lifecycle(id).is_none(), Error::<T>::AlreadyRegistered);
let (genesis, deposit) = Self::validate_onboarding_data(
genesis_head,
validation_code,
false
)?;
let (genesis, deposit) =
Self::validate_onboarding_data(genesis_head, validation_code, false)?;
let deposit = deposit_override.unwrap_or(deposit);
if let Some(additional) = deposit.checked_sub(&deposited) {
@@ -478,11 +490,7 @@ impl<T: Config> Pallet<T> {
} else if let Some(rebate) = deposited.checked_sub(&deposit) {
<T as Config>::Currency::unreserve(&who, rebate);
};
let info = ParaInfo {
manager: who.clone(),
deposit,
locked: false,
};
let info = ParaInfo { manager: who.clone(), deposit, locked: false };
Paras::<T>::insert(id, info);
// We check above that para has no lifecycle, so this should not fail.
@@ -497,9 +505,10 @@ impl<T: Config> Pallet<T> {
match paras::Pallet::<T>::lifecycle(id) {
// Para must be a parathread, or not exist at all.
Some(ParaLifecycle::Parathread) | None => {},
_ => return Err(Error::<T>::NotParathread.into())
_ => return Err(Error::<T>::NotParathread.into()),
}
runtime_parachains::schedule_para_cleanup::<T>(id).map_err(|_| Error::<T>::CannotDeregister)?;
runtime_parachains::schedule_para_cleanup::<T>(id)
.map_err(|_| Error::<T>::CannotDeregister)?;
if let Some(info) = Paras::<T>::take(&id) {
<T as Config>::Currency::unreserve(&info.manager, info.deposit);
@@ -520,45 +529,40 @@ impl<T: Config> Pallet<T> {
) -> Result<(ParaGenesisArgs, BalanceOf<T>), sp_runtime::DispatchError> {
let config = configuration::Pallet::<T>::config();
ensure!(validation_code.0.len() <= config.max_code_size as usize, Error::<T>::CodeTooLarge);
ensure!(genesis_head.0.len() <= config.max_head_data_size as usize, Error::<T>::HeadDataTooLarge);
ensure!(
genesis_head.0.len() <= config.max_head_data_size as usize,
Error::<T>::HeadDataTooLarge
);
let per_byte_fee = T::DataDepositPerByte::get();
let deposit = T::ParaDeposit::get()
.saturating_add(
per_byte_fee.saturating_mul((genesis_head.0.len() as u32).into())
).saturating_add(
per_byte_fee.saturating_mul((validation_code.0.len() as u32).into())
);
.saturating_add(per_byte_fee.saturating_mul((genesis_head.0.len() as u32).into()))
.saturating_add(per_byte_fee.saturating_mul((validation_code.0.len() as u32).into()));
Ok((ParaGenesisArgs {
genesis_head,
validation_code,
parachain,
}, deposit))
Ok((ParaGenesisArgs { genesis_head, validation_code, parachain }, deposit))
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_io::TestExternalities;
use sp_core::H256;
use sp_runtime::{
traits::{
BlakeTwo256, IdentityLookup,
}, Perbill,
};
use primitives::v1::{Balance, BlockNumber, Header};
use frame_system::limits;
use crate::{paras_registrar, traits::Registrar as RegistrarTrait};
use frame_support::{
traits::{OnInitialize, OnFinalize, GenesisBuild},
assert_ok, assert_noop, parameter_types,
assert_noop, assert_ok,
error::BadOrigin,
parameter_types,
traits::{GenesisBuild, OnFinalize, OnInitialize},
};
use runtime_parachains::{configuration, shared};
use frame_system::limits;
use pallet_balances::Error as BalancesError;
use crate::traits::Registrar as RegistrarTrait;
use crate::paras_registrar;
use primitives::v1::{Balance, BlockNumber, Header};
use runtime_parachains::{configuration, shared};
use sp_core::H256;
use sp_io::TestExternalities;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
Perbill,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -636,7 +640,7 @@ mod tests {
type Event = Event;
}
impl configuration::Config for Test { }
impl configuration::Config for Test {}
parameter_types! {
pub const ParaDeposit: Balance = 10;
@@ -661,17 +665,18 @@ mod tests {
GenesisBuild::<Test>::assimilate_storage(
&configuration::GenesisConfig {
config: configuration::HostConfiguration {
max_code_size: 2 * 1024 * 1024, // 2 MB
max_code_size: 2 * 1024 * 1024, // 2 MB
max_head_data_size: 1 * 1024 * 1024, // 1 MB
..Default::default()
}
},
},
&mut t
).unwrap();
&mut t,
)
.unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10_000_000), (2, 10_000_000)],
}.assimilate_storage(&mut t).unwrap();
pallet_balances::GenesisConfig::<Test> { balances: vec![(1, 10_000_000), (2, 10_000_000)] }
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
@@ -691,7 +696,7 @@ mod tests {
// Session change every 3 blocks.
if (b + 1) % BLOCKS_PER_SESSION == 0 {
shared::Pallet::<Test>::set_session_index(
shared::Pallet::<Test>::session_index() + 1
shared::Pallet::<Test>::session_index() + 1,
);
Parachains::test_on_new_session();
}
@@ -765,10 +770,7 @@ mod tests {
assert!(Parachains::is_parathread(para_id));
assert!(!Parachains::is_parachain(para_id));
// Deregister it
assert_ok!(Registrar::deregister(
Origin::root(),
para_id,
));
assert_ok!(Registrar::deregister(Origin::root(), para_id,));
run_to_session(8);
// It is nothing
assert!(!Parachains::is_parathread(para_id));
@@ -794,7 +796,8 @@ mod tests {
assert!(Parachains::is_parathread(para_id));
assert_eq!(
Balances::reserved_balance(&1),
<Test as Config>::ParaDeposit::get() + 64 * <Test as Config>::DataDepositPerByte::get()
<Test as Config>::ParaDeposit::get() +
64 * <Test as Config>::DataDepositPerByte::get()
);
});
}
@@ -804,22 +807,28 @@ mod tests {
new_test_ext().execute_with(|| {
let para_id = LOWEST_PUBLIC_ID;
assert_noop!(Registrar::register(
Origin::signed(1),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
), Error::<Test>::NotReserved);
assert_noop!(
Registrar::register(
Origin::signed(1),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
),
Error::<Test>::NotReserved
);
// Successfully register para
assert_ok!(Registrar::reserve(Origin::signed(1)));
assert_noop!(Registrar::register(
Origin::signed(2),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
), Error::<Test>::NotOwner);
assert_noop!(
Registrar::register(
Origin::signed(2),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
),
Error::<Test>::NotOwner
);
assert_ok!(Registrar::register(
Origin::signed(1),
@@ -833,32 +842,44 @@ mod tests {
assert_ok!(Registrar::deregister(Origin::root(), para_id));
// Can't do it again
assert_noop!(Registrar::register(
Origin::signed(1),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
), Error::<Test>::NotReserved);
assert_noop!(
Registrar::register(
Origin::signed(1),
para_id,
test_genesis_head(max_head_size() as usize),
test_validation_code(max_code_size() as usize),
),
Error::<Test>::NotReserved
);
// Head Size Check
assert_ok!(Registrar::reserve(Origin::signed(2)));
assert_noop!(Registrar::register(
Origin::signed(2),
para_id + 1,
test_genesis_head((max_head_size() + 1) as usize),
test_validation_code(max_code_size() as usize),
), Error::<Test>::HeadDataTooLarge);
assert_noop!(
Registrar::register(
Origin::signed(2),
para_id + 1,
test_genesis_head((max_head_size() + 1) as usize),
test_validation_code(max_code_size() as usize),
),
Error::<Test>::HeadDataTooLarge
);
// Code Size Check
assert_noop!(Registrar::register(
Origin::signed(2),
para_id + 1,
test_genesis_head(max_head_size() as usize),
test_validation_code((max_code_size() + 1) as usize),
), Error::<Test>::CodeTooLarge);
assert_noop!(
Registrar::register(
Origin::signed(2),
para_id + 1,
test_genesis_head(max_head_size() as usize),
test_validation_code((max_code_size() + 1) as usize),
),
Error::<Test>::CodeTooLarge
);
// Needs enough funds for deposit
assert_noop!(Registrar::reserve(Origin::signed(1337)), BalancesError::<Test, _>::InsufficientBalance);
assert_noop!(
Registrar::reserve(Origin::signed(1337)),
BalancesError::<Test, _>::InsufficientBalance
);
});
}
@@ -877,10 +898,7 @@ mod tests {
));
run_to_session(2);
assert!(Parachains::is_parathread(para_id));
assert_ok!(Registrar::deregister(
Origin::root(),
para_id,
));
assert_ok!(Registrar::deregister(Origin::root(), para_id,));
run_to_session(4);
assert!(paras::Pallet::<Test>::lifecycle(para_id).is_none());
assert_eq!(Balances::reserved_balance(&1), 0);
@@ -903,17 +921,14 @@ mod tests {
run_to_session(2);
assert!(Parachains::is_parathread(para_id));
// Owner check
assert_noop!(Registrar::deregister(
Origin::signed(2),
para_id,
), BadOrigin);
assert_noop!(Registrar::deregister(Origin::signed(2), para_id,), BadOrigin);
assert_ok!(Registrar::make_parachain(para_id));
run_to_session(4);
// Cant directly deregister parachain
assert_noop!(Registrar::deregister(
Origin::root(),
para_id,
), Error::<Test>::NotParathread);
assert_noop!(
Registrar::deregister(Origin::root(), para_id,),
Error::<Test>::NotParathread
);
});
}
@@ -951,22 +966,17 @@ mod tests {
assert!(Parachains::is_parathread(para_2));
// Both paras initiate a swap
assert_ok!(Registrar::swap(
para_origin(para_1),
para_1,
para_2,
));
assert_ok!(Registrar::swap(
para_origin(para_2),
para_2,
para_1,
));
assert_ok!(Registrar::swap(para_origin(para_1), para_1, para_2,));
assert_ok!(Registrar::swap(para_origin(para_2), para_2, para_1,));
run_to_session(6);
// Deregister a parathread that was originally a parachain
assert_eq!(Parachains::lifecycle(para_1), Some(ParaLifecycle::Parathread));
assert_ok!(Registrar::deregister(runtime_parachains::Origin::Parachain(para_1).into(), para_1));
assert_ok!(Registrar::deregister(
runtime_parachains::Origin::Parachain(para_1).into(),
para_1
));
run_to_block(21);
@@ -1010,14 +1020,14 @@ mod tests {
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking {
use super::{*, Pallet as Registrar};
use frame_system::RawOrigin;
use super::{Pallet as Registrar, *};
use crate::traits::Registrar as RegistrarT;
use frame_support::assert_ok;
use sp_runtime::traits::Bounded;
use crate::traits::{Registrar as RegistrarT};
use frame_system::RawOrigin;
use runtime_parachains::{paras, shared, Origin as ParaOrigin};
use sp_runtime::traits::Bounded;
use frame_benchmarking::{account, benchmarks, whitelisted_caller, impl_benchmark_test_suite};
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
fn assert_last_event<T: Config>(generic_event: <T as Config>::Event) {
let events = frame_system::Pallet::<T>::events();
@@ -1034,8 +1044,13 @@ mod benchmarking {
let caller: T::AccountId = whitelisted_caller();
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
assert_ok!(Registrar::<T>::reserve(RawOrigin::Signed(caller.clone()).into()));
assert_ok!(Registrar::<T>::register(RawOrigin::Signed(caller).into(), para, genesis_head, validation_code));
return para;
assert_ok!(Registrar::<T>::register(
RawOrigin::Signed(caller).into(),
para,
genesis_head,
validation_code
));
return para
}
fn para_origin(id: u32) -> ParaOrigin {
@@ -1044,9 +1059,7 @@ mod benchmarking {
// This function moves forward to the next scheduled session for parachain lifecycle upgrades.
fn next_scheduled_session<T: Config>() {
shared::Pallet::<T>::set_session_index(
shared::Pallet::<T>::scheduled_session()
);
shared::Pallet::<T>::set_session_index(shared::Pallet::<T>::scheduled_session());
paras::Pallet::<T>::test_on_new_session();
}
@@ -18,14 +18,14 @@
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use runtime_parachains::{
configuration, dmp, ump, hrmp,
ParaLifecycle,
paras::{self, ParaGenesisArgs},
};
use primitives::v1::Id as ParaId;
use parity_scale_codec::Encode;
pub use pallet::*;
use parity_scale_codec::Encode;
use primitives::v1::Id as ParaId;
use runtime_parachains::{
configuration, dmp, hrmp,
paras::{self, ParaGenesisArgs},
ump, ParaLifecycle,
};
#[frame_support::pallet]
pub mod pallet {
@@ -38,8 +38,9 @@ pub mod pallet {
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config:
configuration::Config + paras::Config + dmp::Config + ump::Config + hrmp::Config {}
configuration::Config + paras::Config + dmp::Config + ump::Config + hrmp::Config
{
}
#[pallet::error]
pub enum Error<T> {
@@ -84,13 +85,17 @@ pub mod pallet {
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn sudo_schedule_para_cleanup(origin: OriginFor<T>, id: ParaId) -> DispatchResult {
ensure_root(origin)?;
runtime_parachains::schedule_para_cleanup::<T>(id).map_err(|_| Error::<T>::CouldntCleanup)?;
runtime_parachains::schedule_para_cleanup::<T>(id)
.map_err(|_| Error::<T>::CouldntCleanup)?;
Ok(())
}
/// Upgrade a parathread to a parachain
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn sudo_schedule_parathread_upgrade(origin: OriginFor<T>, id: ParaId) -> DispatchResult {
pub fn sudo_schedule_parathread_upgrade(
origin: OriginFor<T>,
id: ParaId,
) -> DispatchResult {
ensure_root(origin)?;
// Para backend should think this is a parathread...
ensure!(
@@ -104,7 +109,10 @@ pub mod pallet {
/// Downgrade a parachain to a parathread
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn sudo_schedule_parachain_downgrade(origin: OriginFor<T>, id: ParaId) -> DispatchResult {
pub fn sudo_schedule_parachain_downgrade(
origin: OriginFor<T>,
id: ParaId,
) -> DispatchResult {
ensure_root(origin)?;
// Para backend should think this is a parachain...
ensure!(
@@ -129,11 +137,11 @@ pub mod pallet {
ensure_root(origin)?;
ensure!(<paras::Pallet<T>>::is_valid_para(id), Error::<T>::ParaDoesntExist);
let config = <configuration::Pallet<T>>::config();
<dmp::Pallet<T>>::queue_downward_message(&config, id, xcm.encode())
.map_err(|e| match e {
dmp::QueueDownwardMessageError::ExceedsMaxMessageSize =>
Error::<T>::ExceedsMaxMessageSize.into(),
})
<dmp::Pallet<T>>::queue_downward_message(&config, id, xcm.encode()).map_err(|e| match e
{
dmp::QueueDownwardMessageError::ExceedsMaxMessageSize =>
Error::<T>::ExceedsMaxMessageSize.into(),
})
}
/// Forcefully establish a channel from the sender to the recipient.
+255 -174
View File
@@ -16,19 +16,22 @@
//! Pallet to process purchase of DOTs.
use parity_scale_codec::{Encode, Decode};
use sp_runtime::{Permill, RuntimeDebug, DispatchResult, DispatchError, AnySignature};
use sp_runtime::traits::{Zero, CheckedAdd, Verify, Saturating};
use frame_support::pallet_prelude::*;
use frame_support::traits::{
EnsureOrigin, Currency, ExistenceRequirement, VestingSchedule, Get
use frame_support::{
pallet_prelude::*,
traits::{Currency, EnsureOrigin, ExistenceRequirement, Get, VestingSchedule},
};
use frame_system::pallet_prelude::*;
use sp_core::sr25519;
use sp_std::prelude::*;
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
use sp_core::sr25519;
use sp_runtime::{
traits::{CheckedAdd, Saturating, Verify, Zero},
AnySignature, DispatchError, DispatchResult, Permill, RuntimeDebug,
};
use sp_std::prelude::*;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
/// The kind of a statement an account needs to make for a claim to be valid.
#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug)]
@@ -99,7 +102,11 @@ pub mod pallet {
type Currency: Currency<Self::AccountId>;
/// Vesting Pallet
type VestingSchedule: VestingSchedule<Self::AccountId, Moment=Self::BlockNumber, Currency=Self::Currency>;
type VestingSchedule: VestingSchedule<
Self::AccountId,
Moment = Self::BlockNumber,
Currency = Self::Currency,
>;
/// The origin allowed to set account status.
type ValidityOrigin: EnsureOrigin<Self::Origin>;
@@ -166,12 +173,8 @@ pub mod pallet {
// A map of all participants in the DOT purchase process.
#[pallet::storage]
pub(super) type Accounts<T: Config> = StorageMap<
_,
Blake2_128Concat, T::AccountId,
AccountStatus<BalanceOf<T>>,
ValueQuery,
>;
pub(super) type Accounts<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, AccountStatus<BalanceOf<T>>, ValueQuery>;
// The account that will be used to payout participants of the DOT purchase process.
#[pallet::storage]
@@ -199,13 +202,16 @@ pub mod pallet {
pub fn create_account(
origin: OriginFor<T>,
who: T::AccountId,
signature: Vec<u8>
signature: Vec<u8>,
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
// Account is already being tracked by the pallet.
ensure!(!Accounts::<T>::contains_key(&who), Error::<T>::ExistingAccount);
// Account should not have a vesting schedule.
ensure!(T::VestingSchedule::vesting_balance(&who).is_none(), Error::<T>::VestingScheduleExists);
ensure!(
T::VestingSchedule::vesting_balance(&who).is_none(),
Error::<T>::VestingScheduleExists
);
// Verify the signature provided is valid for the statement.
Self::verify_signature(&who, &signature)?;
@@ -233,15 +239,21 @@ pub mod pallet {
pub fn update_validity_status(
origin: OriginFor<T>,
who: T::AccountId,
validity: AccountValidity
validity: AccountValidity,
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
ensure!(Accounts::<T>::contains_key(&who), Error::<T>::InvalidAccount);
Accounts::<T>::try_mutate(&who, |status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
ensure!(status.validity != AccountValidity::Completed, Error::<T>::AlreadyCompleted);
status.validity = validity;
Ok(())
})?;
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
ensure!(
status.validity != AccountValidity::Completed,
Error::<T>::AlreadyCompleted
);
status.validity = validity;
Ok(())
},
)?;
Self::deposit_event(Event::<T>::ValidityUpdated(who, validity));
Ok(())
}
@@ -261,16 +273,19 @@ pub mod pallet {
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
Accounts::<T>::try_mutate(&who, |status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
// Account has a valid status (not Invalid, Pending, or Completed)...
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
// Account has a valid status (not Invalid, Pending, or Completed)...
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
free_balance.checked_add(&locked_balance).ok_or(Error::<T>::Overflow)?;
status.free_balance = free_balance;
status.locked_balance = locked_balance;
status.vat = vat;
Ok(())
})?;
free_balance.checked_add(&locked_balance).ok_or(Error::<T>::Overflow)?;
status.free_balance = free_balance;
status.locked_balance = locked_balance;
status.vat = vat;
Ok(())
},
)?;
Self::deposit_event(Event::<T>::BalanceUpdated(who, free_balance, locked_balance));
Ok(())
}
@@ -287,44 +302,59 @@ pub mod pallet {
ensure!(payment_account == PaymentAccount::<T>::get(), DispatchError::BadOrigin);
// Account should not have a vesting schedule.
ensure!(T::VestingSchedule::vesting_balance(&who).is_none(), Error::<T>::VestingScheduleExists);
ensure!(
T::VestingSchedule::vesting_balance(&who).is_none(),
Error::<T>::VestingScheduleExists
);
Accounts::<T>::try_mutate(&who, |status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
// Account has a valid status (not Invalid, Pending, or Completed)...
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
// Account has a valid status (not Invalid, Pending, or Completed)...
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
// Transfer funds from the payment account into the purchasing user.
let total_balance = status.free_balance
.checked_add(&status.locked_balance)
.ok_or(Error::<T>::Overflow)?;
T::Currency::transfer(&payment_account, &who, total_balance, ExistenceRequirement::AllowDeath)?;
if !status.locked_balance.is_zero() {
let unlock_block = UnlockBlock::<T>::get();
// We allow some configurable portion of the purchased locked DOTs to be unlocked for basic usage.
let unlocked = (T::UnlockedProportion::get() * status.locked_balance).min(T::MaxUnlocked::get());
let locked = status.locked_balance.saturating_sub(unlocked);
// We checked that this account has no existing vesting schedule. So this function should
// never fail, however if it does, not much we can do about it at this point.
let _ = T::VestingSchedule::add_vesting_schedule(
// Apply vesting schedule to this user
// Transfer funds from the payment account into the purchasing user.
let total_balance = status
.free_balance
.checked_add(&status.locked_balance)
.ok_or(Error::<T>::Overflow)?;
T::Currency::transfer(
&payment_account,
&who,
// For this much amount
locked,
// Unlocking the full amount after one block
locked,
// When everything unlocks
unlock_block
);
}
total_balance,
ExistenceRequirement::AllowDeath,
)?;
// Setting the user account to `Completed` ends the purchase process for this user.
status.validity = AccountValidity::Completed;
Self::deposit_event(
Event::<T>::PaymentComplete(who.clone(), status.free_balance, status.locked_balance)
);
Ok(())
})?;
if !status.locked_balance.is_zero() {
let unlock_block = UnlockBlock::<T>::get();
// We allow some configurable portion of the purchased locked DOTs to be unlocked for basic usage.
let unlocked = (T::UnlockedProportion::get() * status.locked_balance)
.min(T::MaxUnlocked::get());
let locked = status.locked_balance.saturating_sub(unlocked);
// We checked that this account has no existing vesting schedule. So this function should
// never fail, however if it does, not much we can do about it at this point.
let _ = T::VestingSchedule::add_vesting_schedule(
// Apply vesting schedule to this user
&who,
// For this much amount
locked,
// Unlocking the full amount after one block
locked,
// When everything unlocks
unlock_block,
);
}
// Setting the user account to `Completed` ends the purchase process for this user.
status.validity = AccountValidity::Completed;
Self::deposit_event(Event::<T>::PaymentComplete(
who.clone(),
status.free_balance,
status.locked_balance,
));
Ok(())
},
)?;
Ok(())
}
@@ -348,7 +378,10 @@ pub mod pallet {
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_statement(origin: OriginFor<T>, statement: Vec<u8>) -> DispatchResult {
T::ConfigurationOrigin::ensure_origin(origin)?;
ensure!((statement.len() as u32) < T::MaxStatementLength::get(), Error::<T>::InvalidStatement);
ensure!(
(statement.len() as u32) < T::MaxStatementLength::get(),
Error::<T>::InvalidStatement
);
// Possibly this is worse than having the caller account be the payment account?
Statement::<T>::set(statement);
Self::deposit_event(Event::<T>::StatementUpdated);
@@ -359,9 +392,15 @@ pub mod pallet {
///
/// Origin must match the `ConfigurationOrigin`
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_unlock_block(origin: OriginFor<T>, unlock_block: T::BlockNumber) -> DispatchResult {
pub fn set_unlock_block(
origin: OriginFor<T>,
unlock_block: T::BlockNumber,
) -> DispatchResult {
T::ConfigurationOrigin::ensure_origin(origin)?;
ensure!(unlock_block > frame_system::Pallet::<T>::block_number(), Error::<T>::InvalidUnlockBlock);
ensure!(
unlock_block > frame_system::Pallet::<T>::block_number(),
Error::<T>::InvalidUnlockBlock
);
// Possibly this is worse than having the caller account be the payment account?
UnlockBlock::<T>::set(unlock_block);
Self::deposit_event(Event::<T>::UnlockBlockUpdated(unlock_block));
@@ -392,7 +431,8 @@ impl<T: Config> Pallet<T> {
// This function converts a 32 byte AccountId to its byte-array equivalent form.
fn account_to_bytes<AccountId>(account: &AccountId) -> Result<[u8; 32], DispatchError>
where AccountId: Encode,
where
AccountId: Encode,
{
let account_vec = account.encode();
ensure!(account_vec.len() == 32, "AccountId must be 32 bytes.");
@@ -404,7 +444,8 @@ fn account_to_bytes<AccountId>(account: &AccountId) -> Result<[u8; 32], Dispatch
/// WARNING: Executing this function will clear all storage used by this pallet.
/// Be sure this is what you want...
pub fn remove_pallet<T>() -> frame_support::weights::Weight
where T: frame_system::Config
where
T: frame_system::Config,
{
use frame_support::migration::remove_storage_prefix;
remove_storage_prefix(b"Purchase", b"Accounts", b"");
@@ -419,21 +460,20 @@ pub fn remove_pallet<T>() -> frame_support::weights::Weight
mod tests {
use super::*;
use sp_core::{H256, Pair, Public, crypto::AccountId32, ed25519};
use sp_core::{crypto::AccountId32, ed25519, Pair, Public, H256};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sp_runtime::{
MultiSignature,
traits::{BlakeTwo256, IdentityLookup, Identity, Verify, IdentifyAccount, Dispatchable},
testing::Header
};
use frame_support::{
assert_ok, assert_noop, parameter_types,
ord_parameter_types, dispatch::DispatchError::BadOrigin,
};
use frame_support::traits::Currency;
use pallet_balances::Error as BalancesError;
use crate::purchase;
use frame_support::{
assert_noop, assert_ok, dispatch::DispatchError::BadOrigin, ord_parameter_types,
parameter_types, traits::Currency,
};
use pallet_balances::Error as BalancesError;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, Dispatchable, IdentifyAccount, Identity, IdentityLookup, Verify},
MultiSignature,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -547,7 +587,8 @@ mod tests {
let unlock_block = 100;
Purchase::set_statement(Origin::signed(configuration_origin()), statement).unwrap();
Purchase::set_unlock_block(Origin::signed(configuration_origin()), unlock_block).unwrap();
Purchase::set_payment_account(Origin::signed(configuration_origin()), payment_account()).unwrap();
Purchase::set_payment_account(Origin::signed(configuration_origin()), payment_account())
.unwrap();
Balances::make_free_balance_be(&payment_account(), 100_000);
}
@@ -561,8 +602,9 @@ mod tests {
}
/// Helper function to generate an account ID from seed
fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where
AccountPublic: From<<TPublic::Pair as Pair>::Public>
fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
@@ -622,7 +664,10 @@ mod tests {
Error::<Test>::InvalidStatement,
);
// Just right...
assert_ok!(Purchase::set_statement(Origin::signed(configuration_origin()), statement.clone()));
assert_ok!(Purchase::set_statement(
Origin::signed(configuration_origin()),
statement.clone()
));
assert_eq!(Statement::<Test>::get(), statement);
});
}
@@ -640,11 +685,17 @@ mod tests {
let bad_unlock_block = 50;
System::set_block_number(bad_unlock_block);
assert_noop!(
Purchase::set_unlock_block(Origin::signed(configuration_origin()), bad_unlock_block),
Purchase::set_unlock_block(
Origin::signed(configuration_origin()),
bad_unlock_block
),
Error::<Test>::InvalidUnlockBlock,
);
// Just right...
assert_ok!(Purchase::set_unlock_block(Origin::signed(configuration_origin()), unlock_block));
assert_ok!(Purchase::set_unlock_block(
Origin::signed(configuration_origin()),
unlock_block
));
assert_eq!(UnlockBlock::<Test>::get(), unlock_block);
});
}
@@ -659,7 +710,10 @@ mod tests {
BadOrigin,
);
// Just right...
assert_ok!(Purchase::set_payment_account(Origin::signed(configuration_origin()), payment_account.clone()));
assert_ok!(Purchase::set_payment_account(
Origin::signed(configuration_origin()),
payment_account.clone()
));
assert_eq!(PaymentAccount::<Test>::get(), payment_account);
});
}
@@ -672,8 +726,14 @@ mod tests {
assert_ok!(Purchase::verify_signature(&bob(), &bob_signature()));
// Mixing and matching fails
assert_noop!(Purchase::verify_signature(&alice(), &bob_signature()), Error::<Test>::InvalidSignature);
assert_noop!(Purchase::verify_signature(&bob(), &alice_signature()), Error::<Test>::InvalidSignature);
assert_noop!(
Purchase::verify_signature(&alice(), &bob_signature()),
Error::<Test>::InvalidSignature
);
assert_noop!(
Purchase::verify_signature(&bob(), &alice_signature()),
Error::<Test>::InvalidSignature
);
});
}
@@ -704,13 +764,21 @@ mod tests {
new_test_ext().execute_with(|| {
// Wrong Origin
assert_noop!(
Purchase::create_account(Origin::signed(alice()), alice(), alice_signature().to_vec()),
Purchase::create_account(
Origin::signed(alice()),
alice(),
alice_signature().to_vec()
),
BadOrigin,
);
// Wrong Account/Signature
assert_noop!(
Purchase::create_account(Origin::signed(validity_origin()), alice(), bob_signature().to_vec()),
Purchase::create_account(
Origin::signed(validity_origin()),
alice(),
bob_signature().to_vec()
),
Error::<Test>::InvalidSignature,
);
@@ -722,16 +790,26 @@ mod tests {
50
));
assert_noop!(
Purchase::create_account(Origin::signed(validity_origin()), alice(), alice_signature().to_vec()),
Purchase::create_account(
Origin::signed(validity_origin()),
alice(),
alice_signature().to_vec()
),
Error::<Test>::VestingScheduleExists,
);
// Duplicate Purchasing Account
assert_ok!(
Purchase::create_account(Origin::signed(validity_origin()), bob(), bob_signature().to_vec())
);
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
bob(),
bob_signature().to_vec()
));
assert_noop!(
Purchase::create_account(Origin::signed(validity_origin()), bob(), bob_signature().to_vec()),
Purchase::create_account(
Origin::signed(validity_origin()),
bob(),
bob_signature().to_vec()
),
Error::<Test>::ExistingAccount,
);
});
@@ -791,17 +869,23 @@ mod tests {
fn update_validity_status_handles_basic_errors() {
new_test_ext().execute_with(|| {
// Wrong Origin
assert_noop!(Purchase::update_validity_status(
Origin::signed(alice()),
alice(),
AccountValidity::Pending,
), BadOrigin);
assert_noop!(
Purchase::update_validity_status(
Origin::signed(alice()),
alice(),
AccountValidity::Pending,
),
BadOrigin
);
// Inactive Account
assert_noop!(Purchase::update_validity_status(
Origin::signed(validity_origin()),
alice(),
AccountValidity::Pending,
), Error::<Test>::InvalidAccount);
assert_noop!(
Purchase::update_validity_status(
Origin::signed(validity_origin()),
alice(),
AccountValidity::Pending,
),
Error::<Test>::InvalidAccount
);
// Already Completed
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
@@ -813,11 +897,14 @@ mod tests {
alice(),
AccountValidity::Completed,
));
assert_noop!(Purchase::update_validity_status(
Origin::signed(validity_origin()),
alice(),
AccountValidity::Pending,
), Error::<Test>::AlreadyCompleted);
assert_noop!(
Purchase::update_validity_status(
Origin::signed(validity_origin()),
alice(),
AccountValidity::Pending,
),
Error::<Test>::AlreadyCompleted
);
});
}
@@ -828,8 +915,8 @@ mod tests {
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
alice(),
alice_signature().to_vec())
);
alice_signature().to_vec()
));
// And approved for basic contribution
assert_ok!(Purchase::update_validity_status(
Origin::signed(validity_origin()),
@@ -879,29 +966,32 @@ mod tests {
fn update_balance_handles_basic_errors() {
new_test_ext().execute_with(|| {
// Wrong Origin
assert_noop!(Purchase::update_balance(
Origin::signed(alice()),
alice(),
50,
50,
Permill::zero(),
), BadOrigin);
assert_noop!(
Purchase::update_balance(Origin::signed(alice()), alice(), 50, 50, Permill::zero(),),
BadOrigin
);
// Inactive Account
assert_noop!(Purchase::update_balance(
Origin::signed(validity_origin()),
alice(),
50,
50,
Permill::zero(),
), Error::<Test>::InvalidAccount);
assert_noop!(
Purchase::update_balance(
Origin::signed(validity_origin()),
alice(),
50,
50,
Permill::zero(),
),
Error::<Test>::InvalidAccount
);
// Overflow
assert_noop!(Purchase::update_balance(
Origin::signed(validity_origin()),
alice(),
u64::MAX,
u64::MAX,
Permill::zero(),
), Error::<Test>::InvalidAccount);
assert_noop!(
Purchase::update_balance(
Origin::signed(validity_origin()),
alice(),
u64::MAX,
u64::MAX,
Permill::zero(),
),
Error::<Test>::InvalidAccount
);
});
}
@@ -912,13 +1002,13 @@ mod tests {
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
alice(),
alice_signature().to_vec())
);
alice_signature().to_vec()
));
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
bob(),
bob_signature().to_vec())
);
bob_signature().to_vec()
));
// Alice is approved for basic contribution
assert_ok!(Purchase::update_validity_status(
Origin::signed(validity_origin()),
@@ -947,14 +1037,8 @@ mod tests {
Permill::zero(),
));
// Now we call payout for Alice and Bob.
assert_ok!(Purchase::payout(
Origin::signed(payment_account()),
alice(),
));
assert_ok!(Purchase::payout(
Origin::signed(payment_account()),
bob(),
));
assert_ok!(Purchase::payout(Origin::signed(payment_account()), alice(),));
assert_ok!(Purchase::payout(Origin::signed(payment_account()), bob(),));
// Payment is made.
assert_eq!(<Test as Config>::Currency::free_balance(&payment_account()), 99_650);
assert_eq!(<Test as Config>::Currency::free_balance(&alice()), 100);
@@ -1003,33 +1087,30 @@ mod tests {
fn payout_handles_basic_errors() {
new_test_ext().execute_with(|| {
// Wrong Origin
assert_noop!(Purchase::payout(
Origin::signed(alice()),
alice(),
), BadOrigin);
assert_noop!(Purchase::payout(Origin::signed(alice()), alice(),), BadOrigin);
// Account with Existing Vesting Schedule
assert_ok!(<Test as Config>::VestingSchedule::add_vesting_schedule(
&bob(), 100, 1, 50,
));
assert_noop!(Purchase::payout(
Origin::signed(payment_account()),
bob(),
), Error::<Test>::VestingScheduleExists);
assert_ok!(
<Test as Config>::VestingSchedule::add_vesting_schedule(&bob(), 100, 1, 50,)
);
assert_noop!(
Purchase::payout(Origin::signed(payment_account()), bob(),),
Error::<Test>::VestingScheduleExists
);
// Invalid Account (never created)
assert_noop!(Purchase::payout(
Origin::signed(payment_account()),
alice(),
), Error::<Test>::InvalidAccount);
assert_noop!(
Purchase::payout(Origin::signed(payment_account()), alice(),),
Error::<Test>::InvalidAccount
);
// Invalid Account (created, but not valid)
assert_ok!(Purchase::create_account(
Origin::signed(validity_origin()),
alice(),
alice_signature().to_vec())
alice_signature().to_vec()
));
assert_noop!(
Purchase::payout(Origin::signed(payment_account()), alice(),),
Error::<Test>::InvalidAccount
);
assert_noop!(Purchase::payout(
Origin::signed(payment_account()),
alice(),
), Error::<Test>::InvalidAccount);
// Not enough funds in payment account
assert_ok!(Purchase::update_validity_status(
Origin::signed(validity_origin()),
@@ -1043,10 +1124,10 @@ mod tests {
100_000,
Permill::zero(),
));
assert_noop!(Purchase::payout(
Origin::signed(payment_account()),
alice(),
), BalancesError::<Test, _>::InsufficientBalance);
assert_noop!(
Purchase::payout(Origin::signed(payment_account()), alice(),),
BalancesError::<Test, _>::InsufficientBalance
);
});
}
+10 -1
View File
@@ -17,7 +17,16 @@
//! The `SlotRange` struct which succinctly handles the 36 values that
//! represent all sub ranges between 0 and 7 inclusive.
slot_range_helper::generate_slot_range!(Zero(0), One(1), Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7));
slot_range_helper::generate_slot_range!(
Zero(0),
One(1),
Two(2),
Three(3),
Four(4),
Five(5),
Six(6),
Seven(7)
);
// Will generate:
// pub enum SlotRange {
+10 -14
View File
@@ -209,9 +209,7 @@ pub mod pallet {
// We can try to onboard it.
Some(Some(_lease_info)) => T::Registrar::make_parachain(para)?,
// Otherwise, it does not have a lease.
Some(None) | None => {
return Err(Error::<T>::ParaNotOnboarding.into());
}
Some(None) | None => return Err(Error::<T>::ParaNotOnboarding.into()),
};
Ok(())
}
@@ -232,7 +230,7 @@ impl<T: Config> Pallet<T> {
let mut parachains = Vec::new();
for (para, mut lease_periods) in Leases::<T>::iter() {
if lease_periods.is_empty() {
continue;
continue
}
// ^^ should never be empty since we would have deleted the entry otherwise.
@@ -307,16 +305,15 @@ impl<T: Config> Pallet<T> {
let mut tracker = sp_std::collections::btree_map::BTreeMap::new();
Leases::<T>::get(para).into_iter().for_each(|lease| match lease {
Some((who, amount)) => match tracker.get(&who) {
Some(prev_amount) => {
Some(prev_amount) =>
if amount > *prev_amount {
tracker.insert(who, amount);
}
}
},
None => {
tracker.insert(who, amount);
}
},
},
None => {}
None => {},
});
tracker.into_iter().collect()
@@ -375,7 +372,7 @@ impl<T: Config> Leaser for Pallet<T> {
// attempt.
//
// We bail, not giving any lease and leave it for governance to sort out.
return Err(LeaseError::AlreadyLeased);
return Err(LeaseError::AlreadyLeased)
}
} else if d.len() == i {
// Doesn't exist. This is usual.
@@ -423,13 +420,12 @@ impl<T: Config> Leaser for Pallet<T> {
Leases::<T>::get(para)
.into_iter()
.map(|lease| match lease {
Some((who, amount)) => {
Some((who, amount)) =>
if &who == leaser {
amount
} else {
Zero::zero()
}
}
},
None => Zero::zero(),
})
.max()
@@ -471,7 +467,7 @@ impl<T: Config> Leaser for Pallet<T> {
for slot in offset..=offset + period_count {
if let Some(Some(_)) = leases.get(slot) {
// If there exists any lease period, we exit early and return true.
return true;
return true
}
}
+11 -5
View File
@@ -16,12 +16,12 @@
//! Traits used across pallets for Polkadot.
use sp_std::vec::*;
use primitives::v1::{HeadData, ValidationCode, Id as ParaId};
use frame_support::{
dispatch::DispatchResult,
traits::{Currency, ReservableCurrency},
};
use primitives::v1::{HeadData, Id as ParaId, ValidationCode};
use sp_std::vec::*;
/// Parachain registration API.
pub trait Registrar {
@@ -128,7 +128,10 @@ pub trait Leaser {
/// Return the amount of balance currently held in reserve on `leaser`'s account for leasing `para`. This won't
/// go down outside of a lease period.
fn deposit_held(para: ParaId, leaser: &Self::AccountId) -> <Self::Currency as Currency<Self::AccountId>>::Balance;
fn deposit_held(
para: ParaId,
leaser: &Self::AccountId,
) -> <Self::Currency as Currency<Self::AccountId>>::Balance;
/// The lease period. This is constant, but can't be a `const` due to it being a runtime configurable quantity.
fn lease_period() -> Self::LeasePeriod;
@@ -141,7 +144,7 @@ pub trait Leaser {
fn already_leased(
para_id: ParaId,
first_period: Self::LeasePeriod,
last_period: Self::LeasePeriod
last_period: Self::LeasePeriod,
) -> bool;
}
@@ -204,7 +207,10 @@ pub trait Auctioneer {
/// This can only happen when there isn't already an auction in progress. Accepts the `duration`
/// of this auction and the `lease_period_index` of the initial lease period of the four that
/// are to be auctioned.
fn new_auction(duration: Self::BlockNumber, lease_period_index: Self::LeasePeriod) -> DispatchResult;
fn new_auction(
duration: Self::BlockNumber,
lease_period_index: Self::LeasePeriod,
) -> DispatchResult;
/// Given the current block number, return the current auction status.
fn auction_status(now: Self::BlockNumber) -> AuctionStatus<Self::BlockNumber>;
+8 -4
View File
@@ -17,9 +17,12 @@
//! XCM sender for relay chain.
use parity_scale_codec::Encode;
use sp_std::marker::PhantomData;
use xcm::opaque::{VersionedXcm, v0::{SendXcm, MultiLocation, Junction, Xcm, Result, Error}};
use runtime_parachains::{configuration, dmp};
use sp_std::marker::PhantomData;
use xcm::opaque::{
v0::{Error, Junction, MultiLocation, Result, SendXcm, Xcm},
VersionedXcm,
};
/// XCM sender for relay chain. It only sends downward message.
pub struct ChildParachainRouter<T>(PhantomData<T>);
@@ -34,9 +37,10 @@ impl<T: configuration::Config + dmp::Config> SendXcm for ChildParachainRouter<T>
&config,
id.into(),
VersionedXcm::from(msg).encode(),
).map_err(Into::<Error>::into)?;
)
.map_err(Into::<Error>::into)?;
Ok(())
}
},
d => Err(Error::CannotReachDestination(d, msg)),
}
}
+10 -8
View File
@@ -30,7 +30,7 @@ pub mod currency {
/// Time and blocks.
pub mod time {
use primitives::v0::{Moment, BlockNumber};
use primitives::v0::{BlockNumber, Moment};
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = 1 * HOURS;
@@ -47,13 +47,13 @@ pub mod time {
/// Fee-related.
pub mod fee {
pub use sp_runtime::Perbill;
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use primitives::v0::Balance;
use runtime_common::ExtrinsicBaseWeight;
use frame_support::weights::{
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
};
use smallvec::smallvec;
pub use sp_runtime::Perbill;
/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
@@ -87,10 +87,12 @@ pub mod fee {
#[cfg(test)]
mod tests {
use super::{
currency::{CENTS, MILLICENTS},
fee::WeightToFee,
};
use frame_support::weights::WeightToFeePolynomial;
use runtime_common::{MAXIMUM_BLOCK_WEIGHT, ExtrinsicBaseWeight};
use super::fee::WeightToFee;
use super::currency::{CENTS, MILLICENTS};
use runtime_common::{ExtrinsicBaseWeight, MAXIMUM_BLOCK_WEIGHT};
#[test]
// This function tests that the fee for `MAXIMUM_BLOCK_WEIGHT` of weight is correct
+40 -39
View File
@@ -17,12 +17,11 @@
//! Tests for the Kusama Runtime Configuration
use crate::*;
use frame_support::weights::WeightToFeePolynomial;
use sp_runtime::FixedPointNumber;
use frame_support::weights::GetDispatchInfo;
use parity_scale_codec::Encode;
use frame_support::weights::{GetDispatchInfo, WeightToFeePolynomial};
use pallet_transaction_payment::Multiplier;
use parity_scale_codec::Encode;
use separator::Separatable;
use sp_runtime::FixedPointNumber;
#[test]
fn remove_keys_weight_is_sensible() {
@@ -40,16 +39,18 @@ fn sample_size_is_sensible() {
let max_weight: Weight = RocksDbWeight::get().reads_writes(samples.into(), samples.into());
// Max sample cleanup should be no more than half the total block weight.
assert!(max_weight * 2 < BlockWeights::get().max_block);
assert!(<Runtime as auctions::Config>::WeightInfo::on_initialize() * 2 < BlockWeights::get().max_block);
assert!(
<Runtime as auctions::Config>::WeightInfo::on_initialize() * 2 <
BlockWeights::get().max_block
);
}
#[test]
fn payout_weight_portion() {
use pallet_staking::WeightInfo;
let payout_weight =
<Runtime as pallet_staking::Config>::WeightInfo::payout_stakers_alive_staked(
MaxNominatorRewardedPerValidator::get(),
) as f64;
let payout_weight = <Runtime as pallet_staking::Config>::WeightInfo::payout_stakers_alive_staked(
MaxNominatorRewardedPerValidator::get(),
) as f64;
let block_weight = BlockWeights::get().max_block as f64;
println!(
@@ -78,7 +79,10 @@ fn block_cost() {
#[ignore]
fn transfer_cost_min_multiplier() {
let min_multiplier = runtime_common::MinimumMultiplier::get();
let call = <pallet_balances::Call<Runtime>>::transfer_keep_alive(Default::default(), Default::default());
let call = <pallet_balances::Call<Runtime>>::transfer_keep_alive(
Default::default(),
Default::default(),
);
let info = call.get_dispatch_info();
// convert to outer call.
let call = Call::Balances(call);
@@ -133,37 +137,34 @@ fn nominator_limit() {
#[test]
fn compute_inflation_should_give_sensible_results() {
assert_eq!(pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(75),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
), Perquintill::one());
assert_eq!(pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(50),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
), Perquintill::from_rational(2u64, 3u64));
assert_eq!(pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(80),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
), Perquintill::from_rational(1u64, 2u64));
assert_eq!(
pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(75),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
),
Perquintill::one()
);
assert_eq!(
pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(50),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
),
Perquintill::from_rational(2u64, 3u64)
);
assert_eq!(
pallet_staking_reward_fn::compute_inflation(
Perquintill::from_percent(80),
Perquintill::from_percent(75),
Perquintill::from_percent(5),
),
Perquintill::from_rational(1u64, 2u64)
);
}
#[test]
fn era_payout_should_give_sensible_results() {
assert_eq!(era_payout(
75,
100,
Perquintill::from_percent(10),
Perquintill::one(),
0,
), (10, 0));
assert_eq!(era_payout(
80,
100,
Perquintill::from_percent(10),
Perquintill::one(),
0,
), (6, 4));
assert_eq!(era_payout(75, 100, Perquintill::from_percent(10), Perquintill::one(), 0,), (10, 0));
assert_eq!(era_payout(80, 100, Perquintill::from_percent(10), Perquintill::one(), 0,), (6, 4));
}
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,36 +42,35 @@ use sp_std::marker::PhantomData;
/// Weight functions for `frame_system`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> frame_system::WeightInfo for WeightInfo<T> {
fn remark(_b: u32, ) -> Weight {
fn remark(_b: u32) -> Weight {
(1_234_000 as Weight)
}
fn remark_with_event(b: u32, ) -> Weight {
fn remark_with_event(b: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(b as Weight))
}
fn set_heap_pages() -> Weight {
(1_670_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(1_670_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_changes_trie_config() -> Weight {
(9_897_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn set_storage(i: u32, ) -> Weight {
fn set_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((529_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_storage(i: u32, ) -> Weight {
fn kill_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((381_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_prefix(p: u32, ) -> Weight {
fn kill_prefix(p: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((788_000 as Weight).saturating_mul(p as Weight))
+1 -1
View File
@@ -20,8 +20,8 @@ pub mod pallet_balances;
pub mod pallet_bounties;
pub mod pallet_collective;
pub mod pallet_democracy;
pub mod pallet_elections_phragmen;
pub mod pallet_election_provider_multi_phase;
pub mod pallet_elections_phragmen;
pub mod pallet_gilt;
pub mod pallet_identity;
pub mod pallet_im_online;
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_bounties`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_bounties::WeightInfo for WeightInfo<T> {
fn propose_bounty(d: u32, ) -> Weight {
fn propose_bounty(d: u32) -> Weight {
(43_276_000 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(d as Weight))
@@ -95,7 +94,7 @@ impl<T: frame_system::Config> pallet_bounties::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn spend_funds(b: u32, ) -> Weight {
fn spend_funds(b: u32) -> Weight {
(0 as Weight)
// Standard Error: 14_000
.saturating_add((60_142_000 as Weight).saturating_mul(b as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_collective`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
fn set_members(m: u32, n: u32, p: u32, ) -> Weight {
fn set_members(m: u32, n: u32, p: u32) -> Weight {
(0 as Weight)
// Standard Error: 4_000
.saturating_add((14_115_000 as Weight).saturating_mul(m as Weight))
@@ -56,7 +55,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight)))
}
fn execute(b: u32, m: u32, ) -> Weight {
fn execute(b: u32, m: u32) -> Weight {
(23_670_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
@@ -64,7 +63,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add((83_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn propose_execute(b: u32, m: u32, ) -> Weight {
fn propose_execute(b: u32, m: u32) -> Weight {
(28_523_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
@@ -72,7 +71,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add((163_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
}
fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight {
fn propose_proposed(b: u32, m: u32, p: u32) -> Weight {
(44_252_000 as Weight)
// Standard Error: 0
.saturating_add((4_000 as Weight).saturating_mul(b as Weight))
@@ -83,14 +82,14 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn vote(m: u32, ) -> Weight {
fn vote(m: u32) -> Weight {
(32_883_000 as Weight)
// Standard Error: 0
.saturating_add((214_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn close_early_disapproved(m: u32, p: u32, ) -> Weight {
fn close_early_disapproved(m: u32, p: u32) -> Weight {
(42_090_000 as Weight)
// Standard Error: 0
.saturating_add((166_000 as Weight).saturating_mul(m as Weight))
@@ -99,7 +98,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight {
fn close_early_approved(b: u32, m: u32, p: u32) -> Weight {
(62_491_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
@@ -110,7 +109,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_disapproved(m: u32, p: u32, ) -> Weight {
fn close_disapproved(m: u32, p: u32) -> Weight {
(46_976_000 as Weight)
// Standard Error: 0
.saturating_add((168_000 as Weight).saturating_mul(m as Weight))
@@ -119,7 +118,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_approved(b: u32, m: u32, p: u32, ) -> Weight {
fn close_approved(b: u32, m: u32, p: u32) -> Weight {
(66_976_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
@@ -130,7 +129,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn disapprove_proposal(p: u32, ) -> Weight {
fn disapprove_proposal(p: u32) -> Weight {
(26_129_000 as Weight)
// Standard Error: 0
.saturating_add((379_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -48,21 +47,21 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn second(s: u32, ) -> Weight {
fn second(s: u32) -> Weight {
(39_011_000 as Weight)
// Standard Error: 0
.saturating_add((157_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn vote_new(r: u32, ) -> Weight {
fn vote_new(r: u32) -> Weight {
(43_998_000 as Weight)
// Standard Error: 0
.saturating_add((211_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn vote_existing(r: u32, ) -> Weight {
fn vote_existing(r: u32) -> Weight {
(44_219_000 as Weight)
// Standard Error: 0
.saturating_add((206_000 as Weight).saturating_mul(r as Weight))
@@ -74,14 +73,14 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn blacklist(p: u32, ) -> Weight {
fn blacklist(p: u32) -> Weight {
(77_299_000 as Weight)
// Standard Error: 4_000
.saturating_add((541_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
fn external_propose(v: u32, ) -> Weight {
fn external_propose(v: u32) -> Weight {
(13_334_000 as Weight)
// Standard Error: 0
.saturating_add((80_000 as Weight).saturating_mul(v as Weight))
@@ -89,26 +88,24 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn external_propose_majority() -> Weight {
(2_650_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_650_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn external_propose_default() -> Weight {
(2_667_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_667_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn fast_track() -> Weight {
(27_908_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn veto_external(v: u32, ) -> Weight {
fn veto_external(v: u32) -> Weight {
(28_446_000 as Weight)
// Standard Error: 0
.saturating_add((134_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn cancel_proposal(p: u32, ) -> Weight {
fn cancel_proposal(p: u32) -> Weight {
(51_004_000 as Weight)
// Standard Error: 0
.saturating_add((512_000 as Weight).saturating_mul(p as Weight))
@@ -116,24 +113,23 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn cancel_referendum() -> Weight {
(17_377_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(17_377_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel_queued(r: u32, ) -> Weight {
fn cancel_queued(r: u32) -> Weight {
(33_882_000 as Weight)
// Standard Error: 15_000
.saturating_add((6_070_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn on_initialize_base(r: u32, ) -> Weight {
fn on_initialize_base(r: u32) -> Weight {
(7_295_000 as Weight)
// Standard Error: 4_000
.saturating_add((5_093_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight)))
}
fn delegate(r: u32, ) -> Weight {
fn delegate(r: u32) -> Weight {
(54_128_000 as Weight)
// Standard Error: 5_000
.saturating_add((7_209_000 as Weight).saturating_mul(r as Weight))
@@ -142,7 +138,7 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight)))
}
fn undelegate(r: u32, ) -> Weight {
fn undelegate(r: u32) -> Weight {
(23_613_000 as Weight)
// Standard Error: 4_000
.saturating_add((7_196_000 as Weight).saturating_mul(r as Weight))
@@ -152,52 +148,51 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight)))
}
fn clear_public_proposals() -> Weight {
(2_607_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_607_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn note_preimage(b: u32, ) -> Weight {
fn note_preimage(b: u32) -> Weight {
(42_847_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn note_imminent_preimage(b: u32, ) -> Weight {
fn note_imminent_preimage(b: u32) -> Weight {
(27_699_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn reap_preimage(b: u32, ) -> Weight {
fn reap_preimage(b: u32) -> Weight {
(38_171_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn unlock_remove(r: u32, ) -> Weight {
fn unlock_remove(r: u32) -> Weight {
(37_418_000 as Weight)
// Standard Error: 0
.saturating_add((55_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn unlock_set(r: u32, ) -> Weight {
fn unlock_set(r: u32) -> Weight {
(35_077_000 as Weight)
// Standard Error: 0
.saturating_add((197_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn remove_vote(r: u32, ) -> Weight {
fn remove_vote(r: u32) -> Weight {
(19_476_000 as Weight)
// Standard Error: 0
.saturating_add((183_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn remove_other_vote(r: u32, ) -> Weight {
fn remove_other_vote(r: u32) -> Weight {
(19_518_000 as Weight)
// Standard Error: 0
.saturating_add((186_000 as Weight).saturating_mul(r as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -44,8 +43,7 @@ use sp_std::marker::PhantomData;
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo for WeightInfo<T> {
fn on_initialize_nothing() -> Weight {
(22_984_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
(22_984_000 as Weight).saturating_add(T::DbWeight::get().reads(8 as Weight))
}
fn on_initialize_open_signed() -> Weight {
(83_667_000 as Weight)
@@ -62,19 +60,19 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32, ) -> Weight {
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32) -> Weight {
(8_641_847_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
fn submit(c: u32, ) -> Weight {
fn submit(c: u32) -> Weight {
(84_430_000 as Weight)
// Standard Error: 146_000
.saturating_add((2_758_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 13_000
.saturating_add((4_805_000 as Weight).saturating_mul(v as Weight))
@@ -87,7 +85,7 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn feasibility_check(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 8_000
.saturating_add((4_729_000 as Weight).saturating_mul(v as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,19 +42,19 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_elections_phragmen`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightInfo<T> {
fn vote_equal(v: u32, ) -> Weight {
fn vote_equal(v: u32) -> Weight {
(54_923_000 as Weight)
.saturating_add((324_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vote_more(v: u32, ) -> Weight {
fn vote_more(v: u32) -> Weight {
(83_389_000 as Weight)
.saturating_add((341_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vote_less(v: u32, ) -> Weight {
fn vote_less(v: u32) -> Weight {
(78_865_000 as Weight)
.saturating_add((343_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
@@ -66,13 +65,13 @@ impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn submit_candidacy(c: u32, ) -> Weight {
fn submit_candidacy(c: u32) -> Weight {
(68_455_000 as Weight)
.saturating_add((370_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn renounce_candidacy_candidate(c: u32, ) -> Weight {
fn renounce_candidacy_candidate(c: u32) -> Weight {
(54_009_000 as Weight)
.saturating_add((200_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
@@ -94,17 +93,16 @@ impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
fn remove_member_wrong_refund() -> Weight {
(8_551_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
(8_551_000 as Weight).saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn clean_defunct_voters(v: u32, _d: u32, ) -> Weight {
fn clean_defunct_voters(v: u32, _d: u32) -> Weight {
(0 as Weight)
.saturating_add((151_754_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight {
fn election_phragmen(c: u32, v: u32, e: u32) -> Weight {
(0 as Weight)
.saturating_add((134_602_000 as Weight).saturating_mul(c as Weight))
.saturating_add((111_037_000 as Weight).saturating_mul(v as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_gilt`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_gilt::WeightInfo for WeightInfo<T> {
fn place_bid(l: u32, ) -> Weight {
fn place_bid(l: u32) -> Weight {
(57_179_000 as Weight)
// Standard Error: 0
.saturating_add((195_000 as Weight).saturating_mul(l as Weight))
@@ -55,7 +54,7 @@ impl<T: frame_system::Config> pallet_gilt::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn retract_bid(l: u32, ) -> Weight {
fn retract_bid(l: u32) -> Weight {
(57_082_000 as Weight)
// Standard Error: 0
.saturating_add((166_000 as Weight).saturating_mul(l as Weight))
@@ -73,10 +72,9 @@ impl<T: frame_system::Config> pallet_gilt::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn pursue_target_noop() -> Weight {
(3_347_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
(3_347_000 as Weight).saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn pursue_target_per_item(b: u32, ) -> Weight {
fn pursue_target_per_item(b: u32) -> Weight {
(56_853_000 as Weight)
// Standard Error: 1_000
.saturating_add((10_238_000 as Weight).saturating_mul(b as Weight))
@@ -84,7 +82,7 @@ impl<T: frame_system::Config> pallet_gilt::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
}
fn pursue_target_per_queue(q: u32, ) -> Weight {
fn pursue_target_per_queue(q: u32) -> Weight {
(23_272_000 as Weight)
// Standard Error: 5_000
.saturating_add((16_821_000 as Weight).saturating_mul(q as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,14 +42,14 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_identity`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
fn add_registrar(r: u32, ) -> Weight {
fn add_registrar(r: u32) -> Weight {
(21_339_000 as Weight)
// Standard Error: 2_000
.saturating_add((236_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_identity(r: u32, x: u32, ) -> Weight {
fn set_identity(r: u32, x: u32) -> Weight {
(50_839_000 as Weight)
// Standard Error: 14_000
.saturating_add((223_000 as Weight).saturating_mul(r as Weight))
@@ -59,7 +58,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_subs_new(s: u32, ) -> Weight {
fn set_subs_new(s: u32) -> Weight {
(40_807_000 as Weight)
// Standard Error: 1_000
.saturating_add((6_374_000 as Weight).saturating_mul(s as Weight))
@@ -68,7 +67,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn set_subs_old(p: u32, ) -> Weight {
fn set_subs_old(p: u32) -> Weight {
(40_924_000 as Weight)
// Standard Error: 0
.saturating_add((2_059_000 as Weight).saturating_mul(p as Weight))
@@ -76,7 +75,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight)))
}
fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight {
fn clear_identity(r: u32, s: u32, x: u32) -> Weight {
(51_123_000 as Weight)
// Standard Error: 7_000
.saturating_add((110_000 as Weight).saturating_mul(r as Weight))
@@ -88,7 +87,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn request_judgement(r: u32, x: u32, ) -> Weight {
fn request_judgement(r: u32, x: u32) -> Weight {
(53_230_000 as Weight)
// Standard Error: 5_000
.saturating_add((223_000 as Weight).saturating_mul(r as Weight))
@@ -97,7 +96,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel_request(r: u32, x: u32, ) -> Weight {
fn cancel_request(r: u32, x: u32) -> Weight {
(48_425_000 as Weight)
// Standard Error: 6_000
.saturating_add((161_000 as Weight).saturating_mul(r as Weight))
@@ -106,28 +105,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fee(r: u32, ) -> Weight {
fn set_fee(r: u32) -> Weight {
(8_028_000 as Weight)
// Standard Error: 0
.saturating_add((202_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_account_id(r: u32, ) -> Weight {
fn set_account_id(r: u32) -> Weight {
(8_682_000 as Weight)
// Standard Error: 1_000
.saturating_add((203_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fields(r: u32, ) -> Weight {
fn set_fields(r: u32) -> Weight {
(8_010_000 as Weight)
// Standard Error: 0
.saturating_add((203_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn provide_judgement(r: u32, x: u32, ) -> Weight {
fn provide_judgement(r: u32, x: u32) -> Weight {
(34_291_000 as Weight)
// Standard Error: 5_000
.saturating_add((203_000 as Weight).saturating_mul(r as Weight))
@@ -136,7 +135,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn kill_identity(r: u32, s: u32, x: u32, ) -> Weight {
fn kill_identity(r: u32, s: u32, x: u32) -> Weight {
(62_644_000 as Weight)
// Standard Error: 6_000
.saturating_add((111_000 as Weight).saturating_mul(r as Weight))
@@ -148,28 +147,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn add_sub(s: u32, ) -> Weight {
fn add_sub(s: u32) -> Weight {
(54_234_000 as Weight)
// Standard Error: 0
.saturating_add((154_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn rename_sub(s: u32, ) -> Weight {
fn rename_sub(s: u32) -> Weight {
(16_622_000 as Weight)
// Standard Error: 0
.saturating_add((21_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_sub(s: u32, ) -> Weight {
fn remove_sub(s: u32) -> Weight {
(55_325_000 as Weight)
// Standard Error: 0
.saturating_add((138_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn quit_sub(s: u32, ) -> Weight {
fn quit_sub(s: u32) -> Weight {
(34_002_000 as Weight)
// Standard Error: 0
.saturating_add((138_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_im_online`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_im_online::WeightInfo for WeightInfo<T> {
fn validate_unsigned_and_then_heartbeat(k: u32, e: u32, ) -> Weight {
fn validate_unsigned_and_then_heartbeat(k: u32, e: u32) -> Weight {
(86_872_000 as Weight)
// Standard Error: 0
.saturating_add((158_000 as Weight).saturating_mul(k as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,50 +42,49 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_membership`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_membership::WeightInfo for WeightInfo<T> {
fn add_member(m: u32, ) -> Weight {
fn add_member(m: u32) -> Weight {
(23_736_000 as Weight)
// Standard Error: 3_000
.saturating_add((166_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn remove_member(m: u32, ) -> Weight {
fn remove_member(m: u32) -> Weight {
(28_609_000 as Weight)
// Standard Error: 0
.saturating_add((137_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn swap_member(m: u32, ) -> Weight {
fn swap_member(m: u32) -> Weight {
(28_935_000 as Weight)
// Standard Error: 0
.saturating_add((150_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn reset_member(m: u32, ) -> Weight {
fn reset_member(m: u32) -> Weight {
(29_621_000 as Weight)
// Standard Error: 0
.saturating_add((304_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn change_key(m: u32, ) -> Weight {
fn change_key(m: u32) -> Weight {
(30_393_000 as Weight)
// Standard Error: 0
.saturating_add((145_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn set_prime(m: u32, ) -> Weight {
fn set_prime(m: u32) -> Weight {
(7_534_000 as Weight)
// Standard Error: 0
.saturating_add((79_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn clear_prime(_m: u32, ) -> Weight {
(2_755_000 as Weight)
.saturating_add(T::DbWeight::get().writes(2 as Weight))
fn clear_prime(_m: u32) -> Weight {
(2_755_000 as Weight).saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,10 +42,10 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_multisig`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
fn as_multi_threshold_1(_z: u32, ) -> Weight {
fn as_multi_threshold_1(_z: u32) -> Weight {
(12_153_000 as Weight)
}
fn as_multi_create(s: u32, z: u32, ) -> Weight {
fn as_multi_create(s: u32, z: u32) -> Weight {
(50_455_000 as Weight)
// Standard Error: 0
.saturating_add((103_000 as Weight).saturating_mul(s as Weight))
@@ -55,7 +54,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn as_multi_create_store(s: u32, z: u32, ) -> Weight {
fn as_multi_create_store(s: u32, z: u32) -> Weight {
(56_117_000 as Weight)
// Standard Error: 0
.saturating_add((106_000 as Weight).saturating_mul(s as Weight))
@@ -64,7 +63,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn as_multi_approve(s: u32, z: u32, ) -> Weight {
fn as_multi_approve(s: u32, z: u32) -> Weight {
(29_486_000 as Weight)
// Standard Error: 0
.saturating_add((103_000 as Weight).saturating_mul(s as Weight))
@@ -73,7 +72,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn as_multi_approve_store(s: u32, z: u32, ) -> Weight {
fn as_multi_approve_store(s: u32, z: u32) -> Weight {
(53_516_000 as Weight)
// Standard Error: 0
.saturating_add((118_000 as Weight).saturating_mul(s as Weight))
@@ -82,7 +81,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn as_multi_complete(s: u32, z: u32, ) -> Weight {
fn as_multi_complete(s: u32, z: u32) -> Weight {
(70_795_000 as Weight)
// Standard Error: 0
.saturating_add((205_000 as Weight).saturating_mul(s as Weight))
@@ -91,28 +90,28 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn approve_as_multi_create(s: u32, ) -> Weight {
fn approve_as_multi_create(s: u32) -> Weight {
(50_128_000 as Weight)
// Standard Error: 0
.saturating_add((104_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn approve_as_multi_approve(s: u32, ) -> Weight {
fn approve_as_multi_approve(s: u32) -> Weight {
(28_902_000 as Weight)
// Standard Error: 0
.saturating_add((105_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn approve_as_multi_complete(s: u32, ) -> Weight {
fn approve_as_multi_complete(s: u32) -> Weight {
(112_716_000 as Weight)
// Standard Error: 0
.saturating_add((210_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn cancel_as_multi(s: u32, ) -> Weight {
fn cancel_as_multi(s: u32) -> Weight {
(84_205_000 as Weight)
// Standard Error: 0
.saturating_add((101_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,13 +42,13 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_proxy`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
fn proxy(p: u32, ) -> Weight {
fn proxy(p: u32) -> Weight {
(24_892_000 as Weight)
// Standard Error: 0
.saturating_add((122_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn proxy_announced(a: u32, p: u32, ) -> Weight {
fn proxy_announced(a: u32, p: u32) -> Weight {
(55_405_000 as Weight)
// Standard Error: 1_000
.saturating_add((563_000 as Weight).saturating_mul(a as Weight))
@@ -58,21 +57,21 @@ impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn remove_announcement(a: u32, _p: u32, ) -> Weight {
fn remove_announcement(a: u32, _p: u32) -> Weight {
(37_762_000 as Weight)
// Standard Error: 1_000
.saturating_add((554_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn reject_announcement(a: u32, _p: u32, ) -> Weight {
fn reject_announcement(a: u32, _p: u32) -> Weight {
(37_826_000 as Weight)
// Standard Error: 1_000
.saturating_add((554_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn announce(a: u32, p: u32, ) -> Weight {
fn announce(a: u32, p: u32) -> Weight {
(51_131_000 as Weight)
// Standard Error: 1_000
.saturating_add((562_000 as Weight).saturating_mul(a as Weight))
@@ -81,35 +80,35 @@ impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn add_proxy(p: u32, ) -> Weight {
fn add_proxy(p: u32) -> Weight {
(36_114_000 as Weight)
// Standard Error: 1_000
.saturating_add((223_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_proxy(p: u32, ) -> Weight {
fn remove_proxy(p: u32) -> Weight {
(35_456_000 as Weight)
// Standard Error: 2_000
.saturating_add((246_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_proxies(p: u32, ) -> Weight {
fn remove_proxies(p: u32) -> Weight {
(33_748_000 as Weight)
// Standard Error: 1_000
.saturating_add((136_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn anonymous(p: u32, ) -> Weight {
fn anonymous(p: u32) -> Weight {
(48_409_000 as Weight)
// Standard Error: 1_000
.saturating_add((31_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn kill_anonymous(p: u32, ) -> Weight {
fn kill_anonymous(p: u32) -> Weight {
(35_515_000 as Weight)
// Standard Error: 1_000
.saturating_add((134_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,28 +42,28 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_scheduler`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_scheduler::WeightInfo for WeightInfo<T> {
fn schedule(s: u32, ) -> Weight {
fn schedule(s: u32) -> Weight {
(28_202_000 as Weight)
// Standard Error: 0
.saturating_add((42_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel(s: u32, ) -> Weight {
fn cancel(s: u32) -> Weight {
(27_640_000 as Weight)
// Standard Error: 14_000
.saturating_add((5_699_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn schedule_named(s: u32, ) -> Weight {
fn schedule_named(s: u32) -> Weight {
(34_298_000 as Weight)
// Standard Error: 1_000
.saturating_add((56_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn cancel_named(s: u32, ) -> Weight {
fn cancel_named(s: u32) -> Weight {
(29_004_000 as Weight)
// Standard Error: 15_000
.saturating_add((5_720_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -58,14 +57,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn withdraw_unbonded_update(s: u32, ) -> Weight {
fn withdraw_unbonded_update(s: u32) -> Weight {
(49_532_000 as Weight)
// Standard Error: 0
.saturating_add((29_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
fn withdraw_unbonded_kill(s: u32) -> Weight {
(81_722_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_331_000 as Weight).saturating_mul(s as Weight))
@@ -78,7 +77,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn kick(k: u32, ) -> Weight {
fn kick(k: u32) -> Weight {
(10_120_000 as Weight)
// Standard Error: 6_000
.saturating_add((18_142_000 as Weight).saturating_mul(k as Weight))
@@ -86,7 +85,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(k as Weight)))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight)))
}
fn nominate(n: u32, ) -> Weight {
fn nominate(n: u32) -> Weight {
(37_716_000 as Weight)
// Standard Error: 6_000
.saturating_add((5_240_000 as Weight).saturating_mul(n as Weight))
@@ -95,8 +94,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn chill() -> Weight {
(16_594_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
(16_594_000 as Weight).saturating_add(T::DbWeight::get().reads(3 as Weight))
}
fn set_payee() -> Weight {
(11_260_000 as Weight)
@@ -109,28 +107,24 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn set_validator_count() -> Weight {
(2_123_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_123_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_no_eras() -> Weight {
(2_458_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_458_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_new_era() -> Weight {
(2_428_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_428_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_new_era_always() -> Weight {
(2_435_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_435_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_invulnerables(v: u32, ) -> Weight {
fn set_invulnerables(v: u32) -> Weight {
(2_524_000 as Weight)
// Standard Error: 0
.saturating_add((23_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_unstake(s: u32, ) -> Weight {
fn force_unstake(s: u32) -> Weight {
(57_861_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_315_000 as Weight).saturating_mul(s as Weight))
@@ -138,14 +132,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn cancel_deferred_slash(s: u32, ) -> Weight {
fn cancel_deferred_slash(s: u32) -> Weight {
(3_460_645_000 as Weight)
// Standard Error: 221_000
.saturating_add((19_673_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn payout_stakers_dead_controller(n: u32, ) -> Weight {
fn payout_stakers_dead_controller(n: u32) -> Weight {
(108_055_000 as Weight)
// Standard Error: 15_000
.saturating_add((47_913_000 as Weight).saturating_mul(n as Weight))
@@ -154,7 +148,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(n as Weight)))
}
fn payout_stakers_alive_staked(n: u32, ) -> Weight {
fn payout_stakers_alive_staked(n: u32) -> Weight {
(122_624_000 as Weight)
// Standard Error: 22_000
.saturating_add((60_815_000 as Weight).saturating_mul(n as Weight))
@@ -163,14 +157,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(n as Weight)))
}
fn rebond(l: u32, ) -> Weight {
fn rebond(l: u32) -> Weight {
(46_725_000 as Weight)
// Standard Error: 1_000
.saturating_add((62_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn set_history_depth(e: u32, ) -> Weight {
fn set_history_depth(e: u32) -> Weight {
(0 as Weight)
// Standard Error: 68_000
.saturating_add((32_190_000 as Weight).saturating_mul(e as Weight))
@@ -178,7 +172,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((7 as Weight).saturating_mul(e as Weight)))
}
fn reap_stash(s: u32, ) -> Weight {
fn reap_stash(s: u32) -> Weight {
(68_887_000 as Weight)
// Standard Error: 0
.saturating_add((2_318_000 as Weight).saturating_mul(s as Weight))
@@ -186,7 +180,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(8 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn new_era(v: u32, n: u32, ) -> Weight {
fn new_era(v: u32, n: u32) -> Weight {
(0 as Weight)
// Standard Error: 734_000
.saturating_add((296_342_000 as Weight).saturating_mul(v as Weight))
@@ -198,7 +192,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
fn get_npos_voters(v: u32, n: u32, s: u32) -> Weight {
(0 as Weight)
// Standard Error: 92_000
.saturating_add((24_187_000 as Weight).saturating_mul(v as Weight))
@@ -211,7 +205,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
}
fn get_npos_targets(v: u32, ) -> Weight {
fn get_npos_targets(v: u32) -> Weight {
(0 as Weight)
// Standard Error: 27_000
.saturating_add((10_233_000 as Weight).saturating_mul(v as Weight))
@@ -219,8 +213,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight)))
}
fn set_staking_limits() -> Weight {
(5_708_000 as Weight)
.saturating_add(T::DbWeight::get().writes(5 as Weight))
(5_708_000 as Weight).saturating_add(T::DbWeight::get().writes(5 as Weight))
}
fn chill_other() -> Weight {
(39_559_000 as Weight)
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_tips`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
fn report_awesome(r: u32, ) -> Weight {
fn report_awesome(r: u32) -> Weight {
(49_516_000 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(r as Weight))
@@ -55,7 +54,7 @@ impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn tip_new(r: u32, t: u32, ) -> Weight {
fn tip_new(r: u32, t: u32) -> Weight {
(30_538_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(r as Weight))
@@ -64,21 +63,21 @@ impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn tip(t: u32, ) -> Weight {
fn tip(t: u32) -> Weight {
(18_895_000 as Weight)
// Standard Error: 0
.saturating_add((558_000 as Weight).saturating_mul(t as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn close_tip(t: u32, ) -> Weight {
fn close_tip(t: u32) -> Weight {
(82_263_000 as Weight)
// Standard Error: 0
.saturating_add((290_000 as Weight).saturating_mul(t as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn slash_tip(t: u32, ) -> Weight {
fn slash_tip(t: u32) -> Weight {
(24_307_000 as Weight)
// Standard Error: 0
.saturating_add((7_000 as Weight).saturating_mul(t as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -53,14 +52,14 @@ impl<T: frame_system::Config> pallet_treasury::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn approve_proposal(p: u32, ) -> Weight {
fn approve_proposal(p: u32) -> Weight {
(12_321_000 as Weight)
// Standard Error: 0
.saturating_add((34_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn on_initialize_proposals(p: u32, ) -> Weight {
fn on_initialize_proposals(p: u32) -> Weight {
(76_361_000 as Weight)
// Standard Error: 17_000
.saturating_add((60_132_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_utility`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_utility::WeightInfo for WeightInfo<T> {
fn batch(c: u32, ) -> Weight {
fn batch(c: u32) -> Weight {
(15_334_000 as Weight)
// Standard Error: 0
.saturating_add((2_478_000 as Weight).saturating_mul(c as Weight))
@@ -51,7 +50,7 @@ impl<T: frame_system::Config> pallet_utility::WeightInfo for WeightInfo<T> {
fn as_derivative() -> Weight {
(5_220_000 as Weight)
}
fn batch_all(c: u32, ) -> Weight {
fn batch_all(c: u32) -> Weight {
(16_791_000 as Weight)
// Standard Error: 0
.saturating_add((3_292_000 as Weight).saturating_mul(c as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,42 +42,42 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_vesting`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_vesting::WeightInfo for WeightInfo<T> {
fn vest_locked(l: u32, ) -> Weight {
fn vest_locked(l: u32) -> Weight {
(42_136_000 as Weight)
// Standard Error: 16_000
.saturating_add((235_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn vest_unlocked(l: u32, ) -> Weight {
fn vest_unlocked(l: u32) -> Weight {
(45_276_000 as Weight)
// Standard Error: 10_000
.saturating_add((189_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vest_other_locked(l: u32, ) -> Weight {
fn vest_other_locked(l: u32) -> Weight {
(42_030_000 as Weight)
// Standard Error: 18_000
.saturating_add((243_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vest_other_unlocked(l: u32, ) -> Weight {
fn vest_other_unlocked(l: u32) -> Weight {
(45_211_000 as Weight)
// Standard Error: 10_000
.saturating_add((191_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn vested_transfer(l: u32, ) -> Weight {
fn vested_transfer(l: u32) -> Weight {
(100_375_000 as Weight)
// Standard Error: 13_000
.saturating_add((136_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn force_vested_transfer(l: u32, ) -> Weight {
fn force_vested_transfer(l: u32) -> Weight {
(100_907_000 as Weight)
// Standard Error: 12_000
.saturating_add((101_000 as Weight).saturating_mul(l as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -58,7 +57,7 @@ impl<T: frame_system::Config> runtime_common::crowdloan::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn refund(k: u32, ) -> Weight {
fn refund(k: u32) -> Weight {
(0 as Weight)
// Standard Error: 21_000
.saturating_add((45_890_000 as Weight).saturating_mul(k as Weight))
@@ -87,7 +86,7 @@ impl<T: frame_system::Config> runtime_common::crowdloan::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn on_initialize(n: u32, ) -> Weight {
fn on_initialize(n: u32) -> Weight {
(0 as Weight)
// Standard Error: 19_000
.saturating_add((110_004_000 as Weight).saturating_mul(n as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/kusama/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -48,7 +47,7 @@ impl<T: frame_system::Config> runtime_common::slots::WeightInfo for WeightInfo<T
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn manage_lease_period_start(c: u32, t: u32, ) -> Weight {
fn manage_lease_period_start(c: u32, t: u32) -> Weight {
(0 as Weight)
// Standard Error: 17_000
.saturating_add((16_401_000 as Weight).saturating_mul(c as Weight))
+193 -133
View File
@@ -18,13 +18,13 @@
//!
//! Configuration can change only at session boundaries and is buffered until then.
use sp_std::prelude::*;
use primitives::v1::{Balance, SessionIndex, MAX_CODE_SIZE, MAX_POV_SIZE};
use parity_scale_codec::{Encode, Decode};
use frame_system::pallet_prelude::*;
use frame_support::pallet_prelude::*;
use sp_runtime::traits::Zero;
use crate::shared;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{Balance, SessionIndex, MAX_CODE_SIZE, MAX_POV_SIZE};
use sp_runtime::traits::Zero;
use sp_std::prelude::*;
pub use pallet::*;
@@ -38,7 +38,6 @@ pub struct HostConfiguration<BlockNumber> {
// A parachain requested this struct can only depend on the subset of this struct. Specifically,
// only a first few fields can be depended upon. These fields cannot be changed without
// corresponding migration of the parachains.
/**
* The parameters that are required for the parachains.
*/
@@ -244,8 +243,7 @@ impl<BlockNumber: Zero> HostConfiguration<BlockNumber> {
if self.max_code_size > MAX_CODE_SIZE {
panic!(
"`max_code_size` ({}) is bigger than allowed by the client ({})",
self.max_code_size,
MAX_CODE_SIZE,
self.max_code_size, MAX_CODE_SIZE,
)
}
@@ -275,32 +273,23 @@ pub mod pallet {
/// The active configuration for the current session.
#[pallet::storage]
#[pallet::getter(fn config)]
pub(crate) type ActiveConfig<T: Config> = StorageValue<
_,
HostConfiguration<T::BlockNumber>,
ValueQuery
>;
pub(crate) type ActiveConfig<T: Config> =
StorageValue<_, HostConfiguration<T::BlockNumber>, ValueQuery>;
/// Pending configuration (if any) for the next session.
#[pallet::storage]
pub(crate) type PendingConfig<T: Config> = StorageMap<
_,
Twox64Concat,
SessionIndex,
HostConfiguration<T::BlockNumber>
>;
pub(crate) type PendingConfig<T: Config> =
StorageMap<_, Twox64Concat, SessionIndex, HostConfiguration<T::BlockNumber>>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub config: HostConfiguration<T::BlockNumber>
pub config: HostConfiguration<T::BlockNumber>,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
config: Default::default()
}
GenesisConfig { config: Default::default() }
}
}
@@ -316,7 +305,10 @@ pub mod pallet {
impl<T: Config> Pallet<T> {
/// Set the validation upgrade frequency.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_validation_upgrade_frequency(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_validation_upgrade_frequency(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.validation_upgrade_frequency, new) != new
@@ -326,7 +318,10 @@ pub mod pallet {
/// Set the validation upgrade delay.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_validation_upgrade_delay(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_validation_upgrade_delay(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.validation_upgrade_delay, new) != new
@@ -336,7 +331,10 @@ pub mod pallet {
/// Set the acceptance period for an included candidate.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_code_retention_period(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_code_retention_period(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.code_retention_period, new) != new
@@ -396,10 +394,12 @@ pub mod pallet {
Ok(())
}
/// Set the parachain validator-group rotation frequency
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_group_rotation_frequency(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_group_rotation_frequency(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(!new.is_zero(), Error::<T>::InvalidNewValue);
@@ -412,7 +412,10 @@ pub mod pallet {
/// Set the availability period for parachains.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_chain_availability_period(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_chain_availability_period(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(!new.is_zero(), Error::<T>::InvalidNewValue);
@@ -425,7 +428,10 @@ pub mod pallet {
/// Set the availability period for parathreads.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_thread_availability_period(origin: OriginFor<T>, new: T::BlockNumber) -> DispatchResult {
pub fn set_thread_availability_period(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(!new.is_zero(), Error::<T>::InvalidNewValue);
@@ -448,7 +454,10 @@ pub mod pallet {
/// Set the maximum number of validators to assign to any core.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_max_validators_per_core(origin: OriginFor<T>, new: Option<u32>) -> DispatchResult {
pub fn set_max_validators_per_core(
origin: OriginFor<T>,
new: Option<u32>,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.max_validators_per_core, new) != new
@@ -484,7 +493,8 @@ pub mod pallet {
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.dispute_post_conclusion_acceptance_period, new) != new
sp_std::mem::replace(&mut config.dispute_post_conclusion_acceptance_period, new) !=
new
});
Ok(())
}
@@ -501,9 +511,10 @@ pub mod pallet {
/// Set the dispute conclusion by time out period.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_dispute_conclusion_by_time_out_period(origin: OriginFor<T>, new: T::BlockNumber)
-> DispatchResult
{
pub fn set_dispute_conclusion_by_time_out_period(
origin: OriginFor<T>,
new: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.dispute_conclusion_by_time_out_period, new) != new
@@ -617,7 +628,10 @@ pub mod pallet {
/// Sets the maximum number of messages that a candidate can contain.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_max_upward_message_num_per_candidate(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_max_upward_message_num_per_candidate(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.max_upward_message_num_per_candidate, new) != new
@@ -678,7 +692,10 @@ pub mod pallet {
/// Sets the maximum number of inbound HRMP channels a parachain is allowed to accept.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_hrmp_max_parachain_inbound_channels(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_hrmp_max_parachain_inbound_channels(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.hrmp_max_parachain_inbound_channels, new) != new
@@ -688,7 +705,10 @@ pub mod pallet {
/// Sets the maximum number of inbound HRMP channels a parathread is allowed to accept.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_hrmp_max_parathread_inbound_channels(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_hrmp_max_parathread_inbound_channels(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.hrmp_max_parathread_inbound_channels, new) != new
@@ -708,7 +728,10 @@ pub mod pallet {
/// Sets the maximum number of outbound HRMP channels a parachain is allowed to open.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_hrmp_max_parachain_outbound_channels(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_hrmp_max_parachain_outbound_channels(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.hrmp_max_parachain_outbound_channels, new) != new
@@ -718,7 +741,10 @@ pub mod pallet {
/// Sets the maximum number of outbound HRMP channels a parathread is allowed to open.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_hrmp_max_parathread_outbound_channels(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_hrmp_max_parathread_outbound_channels(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.hrmp_max_parathread_outbound_channels, new) != new
@@ -728,7 +754,10 @@ pub mod pallet {
/// Sets the maximum number of outbound HRMP messages can be sent by a candidate.
#[pallet::weight((1_000, DispatchClass::Operational))]
pub fn set_hrmp_max_message_num_per_candidate(origin: OriginFor<T>, new: u32) -> DispatchResult {
pub fn set_hrmp_max_message_num_per_candidate(
origin: OriginFor<T>,
new: u32,
) -> DispatchResult {
ensure_root(origin)?;
Self::update_config_member(|config| {
sp_std::mem::replace(&mut config.hrmp_max_message_num_per_candidate, new) != new
@@ -745,12 +774,10 @@ impl<T: Config> Pallet<T> {
}
/// Called by the initializer to finalize the configuration module.
pub(crate) fn initializer_finalize() { }
pub(crate) fn initializer_finalize() {}
/// Called by the initializer to note that a new session has started.
pub(crate) fn initializer_on_new_session(
session_index: &SessionIndex,
) {
pub(crate) fn initializer_on_new_session(session_index: &SessionIndex) {
if let Some(pending) = <Self as Store>::PendingConfig::take(session_index) {
<Self as Store>::ActiveConfig::set(pending);
}
@@ -773,9 +800,7 @@ impl<T: Config> Pallet<T> {
// duplicated code (making this function to show up in the top of heaviest functions) only for
// the sake of essentially avoiding an indirect call. Doesn't worth it.
#[inline(never)]
fn update_config_member(
updater: impl FnOnce(&mut HostConfiguration<T::BlockNumber>) -> bool,
) {
fn update_config_member(updater: impl FnOnce(&mut HostConfiguration<T::BlockNumber>) -> bool) {
let scheduled_session = Self::scheduled_session();
let pending = <Self as Store>::PendingConfig::get(scheduled_session);
let mut prev = pending.unwrap_or_else(Self::config);
@@ -867,138 +892,172 @@ mod tests {
assert!(<Configuration as Store>::PendingConfig::get(shared::SESSION_DELAY).is_none());
Configuration::set_validation_upgrade_frequency(
Origin::root(), new_config.validation_upgrade_frequency,
).unwrap();
Origin::root(),
new_config.validation_upgrade_frequency,
)
.unwrap();
Configuration::set_validation_upgrade_delay(
Origin::root(), new_config.validation_upgrade_delay,
).unwrap();
Origin::root(),
new_config.validation_upgrade_delay,
)
.unwrap();
Configuration::set_code_retention_period(
Origin::root(), new_config.code_retention_period,
).unwrap();
Configuration::set_max_code_size(
Origin::root(), new_config.max_code_size,
).unwrap();
Configuration::set_max_pov_size(
Origin::root(), new_config.max_pov_size,
).unwrap();
Configuration::set_max_head_data_size(
Origin::root(), new_config.max_head_data_size,
).unwrap();
Configuration::set_parathread_cores(
Origin::root(), new_config.parathread_cores,
).unwrap();
Configuration::set_parathread_retries(
Origin::root(), new_config.parathread_retries,
).unwrap();
Origin::root(),
new_config.code_retention_period,
)
.unwrap();
Configuration::set_max_code_size(Origin::root(), new_config.max_code_size).unwrap();
Configuration::set_max_pov_size(Origin::root(), new_config.max_pov_size).unwrap();
Configuration::set_max_head_data_size(Origin::root(), new_config.max_head_data_size)
.unwrap();
Configuration::set_parathread_cores(Origin::root(), new_config.parathread_cores)
.unwrap();
Configuration::set_parathread_retries(Origin::root(), new_config.parathread_retries)
.unwrap();
Configuration::set_group_rotation_frequency(
Origin::root(), new_config.group_rotation_frequency,
).unwrap();
Origin::root(),
new_config.group_rotation_frequency,
)
.unwrap();
Configuration::set_chain_availability_period(
Origin::root(), new_config.chain_availability_period,
).unwrap();
Origin::root(),
new_config.chain_availability_period,
)
.unwrap();
Configuration::set_thread_availability_period(
Origin::root(), new_config.thread_availability_period,
).unwrap();
Origin::root(),
new_config.thread_availability_period,
)
.unwrap();
Configuration::set_scheduling_lookahead(
Origin::root(), new_config.scheduling_lookahead,
).unwrap();
Origin::root(),
new_config.scheduling_lookahead,
)
.unwrap();
Configuration::set_max_validators_per_core(
Origin::root(), new_config.max_validators_per_core,
).unwrap();
Configuration::set_max_validators(
Origin::root(), new_config.max_validators,
).unwrap();
Configuration::set_dispute_period(
Origin::root(), new_config.dispute_period,
).unwrap();
Origin::root(),
new_config.max_validators_per_core,
)
.unwrap();
Configuration::set_max_validators(Origin::root(), new_config.max_validators).unwrap();
Configuration::set_dispute_period(Origin::root(), new_config.dispute_period).unwrap();
Configuration::set_dispute_post_conclusion_acceptance_period(
Origin::root(), new_config.dispute_post_conclusion_acceptance_period,
).unwrap();
Origin::root(),
new_config.dispute_post_conclusion_acceptance_period,
)
.unwrap();
Configuration::set_dispute_max_spam_slots(
Origin::root(), new_config.dispute_max_spam_slots,
).unwrap();
Origin::root(),
new_config.dispute_max_spam_slots,
)
.unwrap();
Configuration::set_dispute_conclusion_by_time_out_period(
Origin::root(), new_config.dispute_conclusion_by_time_out_period,
).unwrap();
Configuration::set_no_show_slots(
Origin::root(), new_config.no_show_slots,
).unwrap();
Configuration::set_n_delay_tranches(
Origin::root(), new_config.n_delay_tranches,
).unwrap();
Origin::root(),
new_config.dispute_conclusion_by_time_out_period,
)
.unwrap();
Configuration::set_no_show_slots(Origin::root(), new_config.no_show_slots).unwrap();
Configuration::set_n_delay_tranches(Origin::root(), new_config.n_delay_tranches)
.unwrap();
Configuration::set_zeroth_delay_tranche_width(
Origin::root(), new_config.zeroth_delay_tranche_width,
).unwrap();
Configuration::set_needed_approvals(
Origin::root(), new_config.needed_approvals,
).unwrap();
Origin::root(),
new_config.zeroth_delay_tranche_width,
)
.unwrap();
Configuration::set_needed_approvals(Origin::root(), new_config.needed_approvals)
.unwrap();
Configuration::set_relay_vrf_modulo_samples(
Origin::root(), new_config.relay_vrf_modulo_samples,
).unwrap();
Origin::root(),
new_config.relay_vrf_modulo_samples,
)
.unwrap();
Configuration::set_max_upward_queue_count(
Origin::root(), new_config.max_upward_queue_count,
).unwrap();
Origin::root(),
new_config.max_upward_queue_count,
)
.unwrap();
Configuration::set_max_upward_queue_size(
Origin::root(), new_config.max_upward_queue_size,
).unwrap();
Origin::root(),
new_config.max_upward_queue_size,
)
.unwrap();
Configuration::set_max_downward_message_size(
Origin::root(), new_config.max_downward_message_size,
).unwrap();
Origin::root(),
new_config.max_downward_message_size,
)
.unwrap();
Configuration::set_ump_service_total_weight(
Origin::root(), new_config.ump_service_total_weight,
).unwrap();
Origin::root(),
new_config.ump_service_total_weight,
)
.unwrap();
Configuration::set_max_upward_message_size(
Origin::root(), new_config.max_upward_message_size,
).unwrap();
Origin::root(),
new_config.max_upward_message_size,
)
.unwrap();
Configuration::set_max_upward_message_num_per_candidate(
Origin::root(), new_config.max_upward_message_num_per_candidate,
).unwrap();
Origin::root(),
new_config.max_upward_message_num_per_candidate,
)
.unwrap();
Configuration::set_hrmp_open_request_ttl(
Origin::root(),
new_config.hrmp_open_request_ttl,
).unwrap();
Configuration::set_hrmp_sender_deposit(
Origin::root(),
new_config.hrmp_sender_deposit,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_sender_deposit(Origin::root(), new_config.hrmp_sender_deposit)
.unwrap();
Configuration::set_hrmp_recipient_deposit(
Origin::root(),
new_config.hrmp_recipient_deposit,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_channel_max_capacity(
Origin::root(),
new_config.hrmp_channel_max_capacity,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_channel_max_total_size(
Origin::root(),
new_config.hrmp_channel_max_total_size,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_max_parachain_inbound_channels(
Origin::root(),
new_config.hrmp_max_parachain_inbound_channels,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_max_parathread_inbound_channels(
Origin::root(),
new_config.hrmp_max_parathread_inbound_channels,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_channel_max_message_size(
Origin::root(),
new_config.hrmp_channel_max_message_size,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_max_parachain_outbound_channels(
Origin::root(),
new_config.hrmp_max_parachain_outbound_channels,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_max_parathread_outbound_channels(
Origin::root(),
new_config.hrmp_max_parathread_outbound_channels,
).unwrap();
)
.unwrap();
Configuration::set_hrmp_max_message_num_per_candidate(
Origin::root(),
new_config.hrmp_max_message_num_per_candidate,
).unwrap();
)
.unwrap();
assert_eq!(<Configuration as Store>::PendingConfig::get(shared::SESSION_DELAY), Some(new_config));
assert_eq!(
<Configuration as Store>::PendingConfig::get(shared::SESSION_DELAY),
Some(new_config)
);
})
}
@@ -1012,7 +1071,8 @@ mod tests {
#[test]
fn setting_config_to_same_as_current_is_noop() {
new_test_ext(Default::default()).execute_with(|| {
Configuration::set_validation_upgrade_delay(Origin::root(), Default::default()).unwrap();
Configuration::set_validation_upgrade_delay(Origin::root(), Default::default())
.unwrap();
assert!(<Configuration as Store>::PendingConfig::get(shared::SESSION_DELAY).is_none())
});
}
File diff suppressed because it is too large Load Diff
+21 -33
View File
@@ -19,9 +19,9 @@ use crate::{
initializer,
};
use frame_support::pallet_prelude::*;
use sp_std::{fmt, prelude::*};
use primitives::v1::{DownwardMessage, Hash, Id as ParaId, InboundDownwardMessage};
use sp_runtime::traits::{BlakeTwo256, Hash as HashT, SaturatedConversion};
use primitives::v1::{Id as ParaId, DownwardMessage, InboundDownwardMessage, Hash};
use sp_std::{fmt, prelude::*};
use xcm::v0::Error as XcmError;
pub use pallet::*;
@@ -47,24 +47,16 @@ pub enum ProcessedDownwardMessagesAcceptanceErr {
/// If there are pending messages then `processed_downward_messages` should be at least 1,
AdvancementRule,
/// `processed_downward_messages` should not be greater than the number of pending messages.
Underflow {
processed_downward_messages: u32,
dmq_length: u32,
},
Underflow { processed_downward_messages: u32, dmq_length: u32 },
}
impl fmt::Debug for ProcessedDownwardMessagesAcceptanceErr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use ProcessedDownwardMessagesAcceptanceErr::*;
match *self {
AdvancementRule => write!(
fmt,
"DMQ is not empty, but processed_downward_messages is 0",
),
Underflow {
processed_downward_messages,
dmq_length,
} => write!(
AdvancementRule =>
write!(fmt, "DMQ is not empty, but processed_downward_messages is 0",),
Underflow { processed_downward_messages, dmq_length } => write!(
fmt,
"processed_downward_messages = {}, but dmq_length is only {}",
processed_downward_messages, dmq_length,
@@ -91,7 +83,7 @@ pub mod pallet {
Twox64Concat,
ParaId,
Vec<InboundDownwardMessage<T::BlockNumber>>,
ValueQuery
ValueQuery,
>;
/// A mapping that stores the downward message queue MQC head for each para.
@@ -102,13 +94,8 @@ pub mod pallet {
/// - `B`: is the relay-chain block number in which a message was appended.
/// - `H(M)`: is the hash of the message being appended.
#[pallet::storage]
pub(crate) type DownwardMessageQueueHeads<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
Hash,
ValueQuery,
>;
pub(crate) type DownwardMessageQueueHeads<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Hash, ValueQuery>;
#[pallet::call]
impl<T: Config> Pallet<T> {}
@@ -161,13 +148,11 @@ impl<T: Config> Pallet<T> {
) -> Result<(), QueueDownwardMessageError> {
let serialized_len = msg.len() as u32;
if serialized_len > config.max_downward_message_size {
return Err(QueueDownwardMessageError::ExceedsMaxMessageSize);
return Err(QueueDownwardMessageError::ExceedsMaxMessageSize)
}
let inbound = InboundDownwardMessage {
msg,
sent_at: <frame_system::Pallet<T>>::block_number(),
};
let inbound =
InboundDownwardMessage { msg, sent_at: <frame_system::Pallet<T>>::block_number() };
// obtain the new link in the MQC and update the head.
<Self as Store>::DownwardMessageQueueHeads::mutate(para, |head| {
@@ -191,13 +176,13 @@ impl<T: Config> Pallet<T> {
let dmq_length = Self::dmq_length(para);
if dmq_length > 0 && processed_downward_messages == 0 {
return Err(ProcessedDownwardMessagesAcceptanceErr::AdvancementRule);
return Err(ProcessedDownwardMessagesAcceptanceErr::AdvancementRule)
}
if dmq_length < processed_downward_messages {
return Err(ProcessedDownwardMessagesAcceptanceErr::Underflow {
processed_downward_messages,
dmq_length,
});
})
}
Ok(())
@@ -245,10 +230,10 @@ impl<T: Config> Pallet<T> {
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::{new_test_ext, Configuration, Dmp, MockGenesisConfig, Paras, System};
use hex_literal::hex;
use primitives::v1::BlockNumber;
use parity_scale_codec::Encode;
use crate::mock::{Configuration, new_test_ext, System, Dmp, MockGenesisConfig, Paras};
use primitives::v1::BlockNumber;
pub(crate) fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>>) {
while System::block_number() < to {
@@ -413,8 +398,8 @@ mod tests {
#[test]
fn verify_dmq_mqc_head_is_externally_accessible() {
use primitives::v1::well_known_keys;
use hex_literal::hex;
use primitives::v1::well_known_keys;
let a = ParaId::from(2020);
@@ -427,7 +412,10 @@ mod tests {
let head = sp_io::storage::get(&well_known_keys::dmq_mqc_head(a));
assert_eq!(
head,
Some(hex!["434f8579a2297dfea851bf6be33093c83a78b655a53ae141a7894494c0010589"].to_vec())
Some(
hex!["434f8579a2297dfea851bf6be33093c83a78b655a53ae141a7894494c0010589"]
.to_vec()
)
);
});
}
+139 -338
View File
@@ -15,22 +15,20 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::{
ensure_parachain,
configuration::{self, HostConfiguration},
initializer, paras, dmp,
dmp, ensure_parachain, initializer, paras,
};
use parity_scale_codec::{Decode, Encode};
use frame_support::pallet_prelude::*;
use frame_support::traits::ReservableCurrency;
use frame_support::{pallet_prelude::*, traits::ReservableCurrency};
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{
Balance, Hash, HrmpChannelId, Id as ParaId, InboundHrmpMessage, OutboundHrmpMessage,
SessionIndex,
};
use sp_runtime::traits::{UniqueSaturatedInto, AccountIdConversion, BlakeTwo256, Hash as HashT};
use sp_runtime::traits::{AccountIdConversion, BlakeTwo256, Hash as HashT, UniqueSaturatedInto};
use sp_std::{
mem, fmt,
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
fmt, mem,
prelude::*,
};
@@ -63,7 +61,6 @@ pub struct HrmpChannel {
// A parachain requested this struct can only depend on the subset of this struct. Specifically,
// only a first few fields can be depended upon (See `AbridgedHrmpChannel`). These fields cannot
// be changed without corresponding migration of parachains.
/// The maximum number of messages that can be pending in the channel at once.
pub max_capacity: u32,
/// The maximum total size of the messages that can be pending in the channel at once.
@@ -93,48 +90,20 @@ pub struct HrmpChannel {
/// An error returned by [`check_hrmp_watermark`] that indicates an acceptance criteria check
/// didn't pass.
pub enum HrmpWatermarkAcceptanceErr<BlockNumber> {
AdvancementRule {
new_watermark: BlockNumber,
last_watermark: BlockNumber,
},
AheadRelayParent {
new_watermark: BlockNumber,
relay_chain_parent_number: BlockNumber,
},
LandsOnBlockWithNoMessages {
new_watermark: BlockNumber,
},
AdvancementRule { new_watermark: BlockNumber, last_watermark: BlockNumber },
AheadRelayParent { new_watermark: BlockNumber, relay_chain_parent_number: BlockNumber },
LandsOnBlockWithNoMessages { new_watermark: BlockNumber },
}
/// An error returned by [`check_outbound_hrmp`] that indicates an acceptance criteria check
/// didn't pass.
pub enum OutboundHrmpAcceptanceErr {
MoreMessagesThanPermitted {
sent: u32,
permitted: u32,
},
NotSorted {
idx: u32,
},
NoSuchChannel {
idx: u32,
channel_id: HrmpChannelId,
},
MaxMessageSizeExceeded {
idx: u32,
msg_size: u32,
max_size: u32,
},
TotalSizeExceeded {
idx: u32,
total_size: u32,
limit: u32,
},
CapacityExceeded {
idx: u32,
count: u32,
limit: u32,
},
MoreMessagesThanPermitted { sent: u32, permitted: u32 },
NotSorted { idx: u32 },
NoSuchChannel { idx: u32, channel_id: HrmpChannelId },
MaxMessageSizeExceeded { idx: u32, msg_size: u32, max_size: u32 },
TotalSizeExceeded { idx: u32, total_size: u32, limit: u32 },
CapacityExceeded { idx: u32, count: u32, limit: u32 },
}
impl<BlockNumber> fmt::Debug for HrmpWatermarkAcceptanceErr<BlockNumber>
@@ -144,18 +113,12 @@ where
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use HrmpWatermarkAcceptanceErr::*;
match self {
AdvancementRule {
new_watermark,
last_watermark,
} => write!(
AdvancementRule { new_watermark, last_watermark } => write!(
fmt,
"the HRMP watermark is not advanced relative to the last watermark ({:?} > {:?})",
new_watermark, last_watermark,
),
AheadRelayParent {
new_watermark,
relay_chain_parent_number,
} => write!(
AheadRelayParent { new_watermark, relay_chain_parent_number } => write!(
fmt,
"the HRMP watermark is ahead the relay-parent ({:?} > {:?})",
new_watermark, relay_chain_parent_number
@@ -178,30 +141,19 @@ impl fmt::Debug for OutboundHrmpAcceptanceErr {
"more HRMP messages than permitted by config ({} > {})",
sent, permitted,
),
NotSorted { idx } => write!(
fmt,
"the HRMP messages are not sorted (first unsorted is at index {})",
idx,
),
NotSorted { idx } =>
write!(fmt, "the HRMP messages are not sorted (first unsorted is at index {})", idx,),
NoSuchChannel { idx, channel_id } => write!(
fmt,
"the HRMP message at index {} is sent to a non existent channel {:?}->{:?}",
idx, channel_id.sender, channel_id.recipient,
),
MaxMessageSizeExceeded {
idx,
msg_size,
max_size,
} => write!(
MaxMessageSizeExceeded { idx, msg_size, max_size } => write!(
fmt,
"the HRMP message at index {} exceeds the negotiated channel maximum message size ({} > {})",
idx, msg_size, max_size,
),
TotalSizeExceeded {
idx,
total_size,
limit,
} => write!(
TotalSizeExceeded { idx, total_size, limit } => write!(
fmt,
"sending the HRMP message at index {} would exceed the neogitiated channel total size ({} > {})",
idx, total_size, limit,
@@ -219,13 +171,14 @@ impl fmt::Debug for OutboundHrmpAcceptanceErr {
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + configuration::Config + paras::Config + dmp::Config {
pub trait Config:
frame_system::Config + configuration::Config + paras::Config + dmp::Config
{
/// The outer event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
@@ -294,39 +247,26 @@ pub mod pallet {
/// Invariant:
/// - There are no channels that exists in list but not in the set and vice versa.
#[pallet::storage]
pub type HrmpOpenChannelRequests<T: Config> = StorageMap<
_,
Twox64Concat,
HrmpChannelId,
HrmpOpenChannelRequest
>;
pub type HrmpOpenChannelRequests<T: Config> =
StorageMap<_, Twox64Concat, HrmpChannelId, HrmpOpenChannelRequest>;
#[pallet::storage]
pub type HrmpOpenChannelRequestsList<T: Config> = StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
pub type HrmpOpenChannelRequestsList<T: Config> =
StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
/// This mapping tracks how many open channel requests are initiated by a given sender para.
/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items that has `(X, _)`
/// as the number of `HrmpOpenChannelRequestCount` for `X`.
#[pallet::storage]
pub type HrmpOpenChannelRequestCount<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
u32,
ValueQuery
>;
pub type HrmpOpenChannelRequestCount<T: Config> =
StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
/// This mapping tracks how many open channel requests were accepted by a given recipient para.
/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items `(_, X)` with
/// `confirmed` set to true, as the number of `HrmpAcceptedChannelRequestCount` for `X`.
#[pallet::storage]
pub type HrmpAcceptedChannelRequestCount<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
u32,
ValueQuery
>;
pub type HrmpAcceptedChannelRequestCount<T: Config> =
StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
/// A set of pending HRMP close channel requests that are going to be closed during the session change.
/// Used for checking if a given channel is registered for closure.
@@ -339,7 +279,8 @@ pub mod pallet {
pub type HrmpCloseChannelRequests<T: Config> = StorageMap<_, Twox64Concat, HrmpChannelId, ()>;
#[pallet::storage]
pub type HrmpCloseChannelRequestsList<T: Config> = StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
pub type HrmpCloseChannelRequestsList<T: Config> =
StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
/// The HRMP watermark associated with each para.
/// Invariant:
@@ -367,24 +308,14 @@ pub mod pallet {
/// - there should be no other dangling channels in `HrmpChannels`.
/// - the vectors are sorted.
#[pallet::storage]
pub type HrmpIngressChannelsIndex<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
Vec<ParaId>,
ValueQuery
>;
pub type HrmpIngressChannelsIndex<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
// the format will require migration of parachains.
#[pallet::storage]
pub type HrmpEgressChannelsIndex<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
Vec<ParaId>,
ValueQuery
>;
pub type HrmpEgressChannelsIndex<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
/// Storage for the messages for each channel.
/// Invariant: cannot be non-empty if the corresponding channel in `HrmpChannels` is `None`.
@@ -394,7 +325,7 @@ pub mod pallet {
Twox64Concat,
HrmpChannelId,
Vec<InboundHrmpMessage<T::BlockNumber>>,
ValueQuery
ValueQuery,
>;
/// Maintains a mapping that can be used to answer the question:
@@ -405,13 +336,8 @@ pub mod pallet {
/// - The outer vector is sorted ascending by block number and cannot store two items with the same
/// block number.
#[pallet::storage]
pub type HrmpChannelDigests<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
Vec<(T::BlockNumber, Vec<ParaId>)>,
ValueQuery
>;
pub type HrmpChannelDigests<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<(T::BlockNumber, Vec<ParaId>)>, ValueQuery>;
/// Preopen the given HRMP channels.
///
@@ -432,9 +358,7 @@ pub mod pallet {
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
GenesisConfig {
preopen_hrmp_channels: Default::default(),
}
GenesisConfig { preopen_hrmp_channels: Default::default() }
}
}
@@ -469,13 +393,13 @@ pub mod pallet {
origin,
recipient,
proposed_max_capacity,
proposed_max_message_size
proposed_max_message_size,
)?;
Self::deposit_event(Event::OpenChannelRequested(
origin,
recipient,
proposed_max_capacity,
proposed_max_message_size
proposed_max_message_size,
));
Ok(())
}
@@ -496,7 +420,10 @@ pub mod pallet {
///
/// The closure can only happen on a session change.
#[pallet::weight(0)]
pub fn hrmp_close_channel(origin: OriginFor<T>, channel_id: HrmpChannelId) -> DispatchResult {
pub fn hrmp_close_channel(
origin: OriginFor<T>,
channel_id: HrmpChannelId,
) -> DispatchResult {
let origin = ensure_parachain(<T as Config>::Origin::from(origin))?;
Self::close_channel(origin, channel_id.clone())?;
Self::deposit_event(Event::ChannelClosed(origin, channel_id));
@@ -544,7 +471,9 @@ pub mod pallet {
fn initialize_storage<T: Config>(preopen_hrmp_channels: &[(ParaId, ParaId, u32, u32)]) {
let host_config = configuration::Pallet::<T>::config();
for &(sender, recipient, max_capacity, max_message_size) in preopen_hrmp_channels {
if let Err(err) = preopen_hrmp_channel::<T>(sender, recipient, max_capacity, max_message_size) {
if let Err(err) =
preopen_hrmp_channel::<T>(sender, recipient, max_capacity, max_message_size)
{
panic!("failed to initialize the genesis storage: {:?}", err);
}
}
@@ -556,14 +485,9 @@ fn preopen_hrmp_channel<T: Config>(
sender: ParaId,
recipient: ParaId,
max_capacity: u32,
max_message_size: u32
max_message_size: u32,
) -> DispatchResult {
<Pallet<T>>::init_open_channel(
sender,
recipient,
max_capacity,
max_message_size,
)?;
<Pallet<T>>::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
<Pallet<T>>::accept_open_channel(recipient, sender)?;
Ok(())
}
@@ -603,16 +527,10 @@ impl<T: Config> Pallet<T> {
let ingress = <Self as Store>::HrmpIngressChannelsIndex::take(outgoing_para)
.into_iter()
.map(|sender| HrmpChannelId {
sender,
recipient: outgoing_para.clone(),
});
.map(|sender| HrmpChannelId { sender, recipient: outgoing_para.clone() });
let egress = <Self as Store>::HrmpEgressChannelsIndex::take(outgoing_para)
.into_iter()
.map(|recipient| HrmpChannelId {
sender: outgoing_para.clone(),
recipient,
});
.map(|recipient| HrmpChannelId { sender: outgoing_para.clone(), recipient });
let mut to_close = ingress.chain(egress).collect::<Vec<_>>();
to_close.sort();
to_close.dedup();
@@ -629,7 +547,7 @@ impl<T: Config> Pallet<T> {
fn process_hrmp_open_channel_requests(config: &HostConfiguration<T::BlockNumber>) {
let mut open_req_channels = <Self as Store>::HrmpOpenChannelRequestsList::get();
if open_req_channels.is_empty() {
return;
return
}
// iterate the vector starting from the end making our way to the beginning. This way we
@@ -638,7 +556,7 @@ impl<T: Config> Pallet<T> {
loop {
// bail if we've iterated over all items.
if idx == 0 {
break;
break
}
idx -= 1;
@@ -648,8 +566,8 @@ impl<T: Config> Pallet<T> {
);
if request.confirmed {
if <paras::Pallet<T>>::is_valid_para(channel_id.sender)
&& <paras::Pallet<T>>::is_valid_para(channel_id.recipient)
if <paras::Pallet<T>>::is_valid_para(channel_id.sender) &&
<paras::Pallet<T>>::is_valid_para(channel_id.recipient)
{
<Self as Store>::HrmpChannels::insert(
&channel_id,
@@ -745,11 +663,8 @@ impl<T: Config> Pallet<T> {
/// This function is idempotent, meaning that after the first application it should have no
/// effect (i.e. it won't return the deposits twice).
fn close_hrmp_channel(channel_id: &HrmpChannelId) {
if let Some(HrmpChannel {
sender_deposit,
recipient_deposit,
..
}) = <Self as Store>::HrmpChannels::take(channel_id)
if let Some(HrmpChannel { sender_deposit, recipient_deposit, .. }) =
<Self as Store>::HrmpChannels::take(channel_id)
{
T::Currency::unreserve(
&channel_id.sender.into_account(),
@@ -793,14 +708,14 @@ impl<T: Config> Pallet<T> {
return Err(HrmpWatermarkAcceptanceErr::AdvancementRule {
new_watermark: new_hrmp_watermark,
last_watermark,
});
})
}
}
if new_hrmp_watermark > relay_chain_parent_number {
return Err(HrmpWatermarkAcceptanceErr::AheadRelayParent {
new_watermark: new_hrmp_watermark,
relay_chain_parent_number,
});
})
}
// Second, check where the watermark CAN land. It's one of the following:
@@ -817,7 +732,7 @@ impl<T: Config> Pallet<T> {
{
return Err(HrmpWatermarkAcceptanceErr::LandsOnBlockWithNoMessages {
new_watermark: new_hrmp_watermark,
});
})
}
Ok(())
}
@@ -832,36 +747,28 @@ impl<T: Config> Pallet<T> {
return Err(OutboundHrmpAcceptanceErr::MoreMessagesThanPermitted {
sent: out_hrmp_msgs.len() as u32,
permitted: config.hrmp_max_message_num_per_candidate,
});
})
}
let mut last_recipient = None::<ParaId>;
for (idx, out_msg) in out_hrmp_msgs
.iter()
.enumerate()
.map(|(idx, out_msg)| (idx as u32, out_msg))
for (idx, out_msg) in
out_hrmp_msgs.iter().enumerate().map(|(idx, out_msg)| (idx as u32, out_msg))
{
match last_recipient {
// the messages must be sorted in ascending order and there must be no two messages sent
// to the same recipient. Thus we can check that every recipient is strictly greater than
// the previous one.
Some(last_recipient) if out_msg.recipient <= last_recipient => {
return Err(OutboundHrmpAcceptanceErr::NotSorted { idx });
}
Some(last_recipient) if out_msg.recipient <= last_recipient =>
return Err(OutboundHrmpAcceptanceErr::NotSorted { idx }),
_ => last_recipient = Some(out_msg.recipient),
}
let channel_id = HrmpChannelId {
sender,
recipient: out_msg.recipient,
};
let channel_id = HrmpChannelId { sender, recipient: out_msg.recipient };
let channel = match <Self as Store>::HrmpChannels::get(&channel_id) {
Some(channel) => channel,
None => {
return Err(OutboundHrmpAcceptanceErr::NoSuchChannel { channel_id, idx });
}
None => return Err(OutboundHrmpAcceptanceErr::NoSuchChannel { channel_id, idx }),
};
let msg_size = out_msg.data.len() as u32;
@@ -870,7 +777,7 @@ impl<T: Config> Pallet<T> {
idx,
msg_size,
max_size: channel.max_message_size,
});
})
}
let new_total_size = channel.total_size + out_msg.data.len() as u32;
@@ -879,7 +786,7 @@ impl<T: Config> Pallet<T> {
idx,
total_size: new_total_size,
limit: channel.max_total_size,
});
})
}
let new_msg_count = channel.msg_count + 1;
@@ -888,7 +795,7 @@ impl<T: Config> Pallet<T> {
idx,
count: new_msg_count,
limit: channel.max_capacity,
});
})
}
}
@@ -916,9 +823,8 @@ impl<T: Config> Pallet<T> {
weight += T::DbWeight::get().reads_writes(1, 1);
// having all senders we can trivially find out the channels which we need to prune.
let channels_to_prune = senders
.into_iter()
.map(|sender| HrmpChannelId { sender, recipient });
let channels_to_prune =
senders.into_iter().map(|sender| HrmpChannelId { sender, recipient });
for channel_id in channels_to_prune {
// prune each channel up to the new watermark keeping track how many messages we removed
// and what is the total byte size of them.
@@ -968,24 +874,18 @@ impl<T: Config> Pallet<T> {
let now = <frame_system::Pallet<T>>::block_number();
for out_msg in out_hrmp_msgs {
let channel_id = HrmpChannelId {
sender,
recipient: out_msg.recipient,
};
let channel_id = HrmpChannelId { sender, recipient: out_msg.recipient };
let mut channel = match <Self as Store>::HrmpChannels::get(&channel_id) {
Some(channel) => channel,
None => {
// apparently, that since acceptance of this candidate the recipient was
// offboarded and the channel no longer exists.
continue;
}
continue
},
};
let inbound = InboundHrmpMessage {
sent_at: now,
data: out_msg.data,
};
let inbound = InboundHrmpMessage { sent_at: now, data: out_msg.data };
// book keeping
channel.msg_count += 1;
@@ -1052,27 +952,18 @@ impl<T: Config> Pallet<T> {
);
let config = <configuration::Pallet<T>>::config();
ensure!(
proposed_max_capacity > 0,
Error::<T>::OpenHrmpChannelZeroCapacity,
);
ensure!(proposed_max_capacity > 0, Error::<T>::OpenHrmpChannelZeroCapacity,);
ensure!(
proposed_max_capacity <= config.hrmp_channel_max_capacity,
Error::<T>::OpenHrmpChannelCapacityExceedsLimit,
);
ensure!(
proposed_max_message_size > 0,
Error::<T>::OpenHrmpChannelZeroMessageSize,
);
ensure!(proposed_max_message_size > 0, Error::<T>::OpenHrmpChannelZeroMessageSize,);
ensure!(
proposed_max_message_size <= config.hrmp_channel_max_message_size,
Error::<T>::OpenHrmpChannelMessageSizeExceedsLimit,
);
let channel_id = HrmpChannelId {
sender: origin,
recipient,
};
let channel_id = HrmpChannelId { sender: origin, recipient };
ensure!(
<Self as Store>::HrmpOpenChannelRequests::get(&channel_id).is_none(),
Error::<T>::OpenHrmpChannelAlreadyExists,
@@ -1115,8 +1006,8 @@ impl<T: Config> Pallet<T> {
<Self as Store>::HrmpOpenChannelRequestsList::append(channel_id);
let notification_bytes = {
use xcm::opaque::{v0::Xcm, VersionedXcm};
use parity_scale_codec::Encode as _;
use xcm::opaque::{v0::Xcm, VersionedXcm};
VersionedXcm::from(Xcm::HrmpNewChannelOpenRequest {
sender: u32::from(origin),
@@ -1141,16 +1032,10 @@ impl<T: Config> Pallet<T> {
/// Basically the same as [`hrmp_accept_open_channel`](Pallet::hrmp_accept_open_channel) but
/// intendend for calling directly from other pallets rather than dispatched.
pub fn accept_open_channel(origin: ParaId, sender: ParaId) -> DispatchResult {
let channel_id = HrmpChannelId {
sender,
recipient: origin,
};
let channel_id = HrmpChannelId { sender, recipient: origin };
let mut channel_req = <Self as Store>::HrmpOpenChannelRequests::get(&channel_id)
.ok_or(Error::<T>::AcceptHrmpChannelDoesntExist)?;
ensure!(
!channel_req.confirmed,
Error::<T>::AcceptHrmpChannelAlreadyConfirmed,
);
ensure!(!channel_req.confirmed, Error::<T>::AcceptHrmpChannelAlreadyConfirmed,);
// check if by accepting this open channel request, this parachain would exceed the
// number of inbound channels.
@@ -1183,10 +1068,7 @@ impl<T: Config> Pallet<T> {
use parity_scale_codec::Encode as _;
use xcm::opaque::{v0::Xcm, VersionedXcm};
VersionedXcm::from(Xcm::HrmpChannelAccepted {
recipient: u32::from(origin),
})
.encode()
VersionedXcm::from(Xcm::HrmpChannelAccepted { recipient: u32::from(origin) }).encode()
};
if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
<dmp::Pallet<T>>::queue_downward_message(&config, sender, notification_bytes)
@@ -1233,11 +1115,8 @@ impl<T: Config> Pallet<T> {
})
.encode()
};
let opposite_party = if origin == channel_id.sender {
channel_id.recipient
} else {
channel_id.sender
};
let opposite_party =
if origin == channel_id.sender { channel_id.recipient } else { channel_id.sender };
if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
<dmp::Pallet<T>>::queue_downward_message(&config, opposite_party, notification_bytes)
{
@@ -1292,15 +1171,14 @@ impl<T: Config> Pallet<T> {
mod tests {
use super::*;
use crate::mock::{
new_test_ext, Test, Configuration, Paras, ParasShared, Hrmp, System, MockGenesisConfig,
Event as MockEvent,
new_test_ext, Configuration, Event as MockEvent, Hrmp, MockGenesisConfig, Paras,
ParasShared, System, Test,
};
use frame_support::{assert_noop, assert_ok, traits::Currency as _};
use primitives::v1::BlockNumber;
use std::collections::{BTreeMap, HashSet};
fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>>) {
let config = Configuration::config();
while System::block_number() < to {
let b = System::block_number();
@@ -1500,9 +1378,7 @@ mod tests {
// An entry in `HrmpChannels` indicates that the channel is open. Only open channels can
// have contents.
for (non_empty_channel, contents) in <Hrmp as Store>::HrmpChannelContents::iter() {
assert!(<Hrmp as Store>::HrmpChannels::contains_key(
&non_empty_channel
));
assert!(<Hrmp as Store>::HrmpChannels::contains_key(&non_empty_channel));
// pedantic check: there should be no empty vectors in storage, those should be modeled
// by a removed kv pair.
@@ -1544,10 +1420,7 @@ mod tests {
let channel_set_ground_truth = <Hrmp as Store>::HrmpChannels::iter()
.map(|(k, _)| (k.sender, k.recipient))
.collect::<HashSet<_>>();
assert_eq!(
channel_set_derived_from_ingress,
channel_set_derived_from_egress
);
assert_eq!(channel_set_derived_from_ingress, channel_set_derived_from_egress);
assert_eq!(channel_set_derived_from_egress, channel_set_ground_truth);
<Hrmp as Store>::HrmpIngressChannelsIndex::iter()
@@ -1583,22 +1456,13 @@ mod tests {
fn assert_contains_only_onboarded(iter: impl Iterator<Item = ParaId>, cause: &str) {
for para in iter {
assert!(
Paras::is_valid_para(para),
"{}: {} para is offboarded",
cause,
para
);
assert!(Paras::is_valid_para(para), "{}: {} para is offboarded", cause, para);
}
}
}
fn assert_is_sorted<T: Ord>(slice: &[T], id: &str) {
assert!(
slice.windows(2).all(|xs| xs[0] <= xs[1]),
"{} supposed to be sorted",
id
);
assert!(slice.windows(2).all(|xs| xs[0] <= xs[1]), "{} supposed to be sorted", id);
}
#[test]
@@ -1623,15 +1487,13 @@ mod tests {
run_to_block(5, Some(vec![4, 5]));
Hrmp::hrmp_init_open_channel(para_a_origin.into(), para_b, 2, 8).unwrap();
assert_storage_consistency_exhaustive();
assert!(System::events().iter().any(|record|
record.event == MockEvent::Hrmp(Event::OpenChannelRequested(para_a, para_b, 2, 8))
));
assert!(System::events().iter().any(|record| record.event ==
MockEvent::Hrmp(Event::OpenChannelRequested(para_a, para_b, 2, 8))));
Hrmp::hrmp_accept_open_channel(para_b_origin.into(), para_a).unwrap();
assert_storage_consistency_exhaustive();
assert!(System::events().iter().any(|record|
record.event == MockEvent::Hrmp(Event::OpenChannelAccepted(para_a, para_b))
));
assert!(System::events().iter().any(|record| record.event ==
MockEvent::Hrmp(Event::OpenChannelAccepted(para_a, para_b))));
// Advance to a block 6, but without session change. That means that the channel has
// not been created yet.
@@ -1664,10 +1526,7 @@ mod tests {
// Close the channel. The effect is not immediate, but rather deferred to the next
// session change.
let channel_id = HrmpChannelId {
sender: para_a,
recipient: para_b,
};
let channel_id = HrmpChannelId { sender: para_a, recipient: para_b };
Hrmp::hrmp_close_channel(para_b_origin.into(), channel_id.clone()).unwrap();
assert!(channel_exists(para_a, para_b));
assert_storage_consistency_exhaustive();
@@ -1676,9 +1535,8 @@ mod tests {
run_to_block(8, Some(vec![8]));
assert!(!channel_exists(para_a, para_b));
assert_storage_consistency_exhaustive();
assert!(System::events().iter().any(|record|
record.event == MockEvent::Hrmp(Event::ChannelClosed(para_b, channel_id.clone()))
));
assert!(System::events().iter().any(|record| record.event ==
MockEvent::Hrmp(Event::ChannelClosed(para_b, channel_id.clone()))));
});
}
@@ -1732,27 +1590,31 @@ mod tests {
register_parachain(para_a);
register_parachain(para_b);
run_to_block(2, Some(vec![1,2]));
run_to_block(2, Some(vec![1, 2]));
Hrmp::init_open_channel(para_a, para_b, 2, 20).unwrap();
Hrmp::accept_open_channel(para_b, para_a).unwrap();
run_to_block(3, Some(vec![3]));
let _ = Hrmp::queue_outbound_hrmp(para_a, vec![OutboundHrmpMessage {
recipient: para_b,
data: vec![1, 2, 3],
}]);
let _ = Hrmp::queue_outbound_hrmp(
para_a,
vec![OutboundHrmpMessage { recipient: para_b, data: vec![1, 2, 3] }],
);
run_to_block(4, None);
let _ = Hrmp::queue_outbound_hrmp(para_a, vec![OutboundHrmpMessage {
recipient: para_b,
data: vec![4, 5, 6],
}]);
let _ = Hrmp::queue_outbound_hrmp(
para_a,
vec![OutboundHrmpMessage { recipient: para_b, data: vec![4, 5, 6] }],
);
assert_eq!(
Hrmp::hrmp_mqc_heads(para_b),
vec![
(para_a, hex_literal::hex!["a964fd3b4f3d3ce92a0e25e576b87590d92bb5cb7031909c7f29050e1f04a375"].into()),
],
vec![(
para_a,
hex_literal::hex![
"a964fd3b4f3d3ce92a0e25e576b87590d92bb5cb7031909c7f29050e1f04a375"
]
.into()
),],
);
});
}
@@ -1803,10 +1665,7 @@ mod tests {
run_to_block(6, Some(vec![6]));
assert!(Paras::is_valid_para(para_a));
let msgs = vec![OutboundHrmpMessage {
recipient: para_b,
data: b"knock".to_vec(),
}];
let msgs = vec![OutboundHrmpMessage { recipient: para_b, data: b"knock".to_vec() }];
let config = Configuration::config();
assert!(Hrmp::check_outbound_hrmp(&config, para_a, &msgs).is_ok());
let _ = Hrmp::queue_outbound_hrmp(para_a, msgs.clone());
@@ -1817,13 +1676,7 @@ mod tests {
assert_eq!(
contents,
vec![
(
para_a,
vec![InboundHrmpMessage {
sent_at: 6,
data: b"knock".to_vec(),
}]
),
(para_a, vec![InboundHrmpMessage { sent_at: 6, data: b"knock".to_vec() }]),
(para_c, vec![])
]
.into_iter()
@@ -1891,29 +1744,19 @@ mod tests {
);
let raw_ingress_index =
sp_io::storage::get(
&well_known_keys::hrmp_ingress_channel_index(para_b),
)
.expect("the ingress index must be present for para_b");
sp_io::storage::get(&well_known_keys::hrmp_ingress_channel_index(para_b))
.expect("the ingress index must be present for para_b");
let ingress_index = <Vec<ParaId>>::decode(&mut &raw_ingress_index[..])
.expect("ingress indexx should be decodable as a list of para ids");
assert_eq!(
ingress_index,
vec![para_a],
);
assert_eq!(ingress_index, vec![para_a],);
// Now, verify that we can access and decode the egress index.
let raw_egress_index =
sp_io::storage::get(
&well_known_keys::hrmp_egress_channel_index(para_a)
)
.expect("the egress index must be present for para_a");
sp_io::storage::get(&well_known_keys::hrmp_egress_channel_index(para_a))
.expect("the egress index must be present for para_a");
let egress_index = <Vec<ParaId>>::decode(&mut &raw_egress_index[..])
.expect("egress index should be decodable as a list of para ids");
assert_eq!(
egress_index,
vec![para_b],
);
assert_eq!(egress_index, vec![para_b],);
});
}
@@ -1962,34 +1805,16 @@ mod tests {
run_to_block(5, Some(vec![4, 5]));
Hrmp::init_open_channel(para_a, para_b, 2, 8).unwrap();
Hrmp::accept_open_channel(para_b, para_a).unwrap();
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
80
);
assert_eq!(
<Test as Config>::Currency::free_balance(&para_b.into_account()),
95
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 80);
assert_eq!(<Test as Config>::Currency::free_balance(&para_b.into_account()), 95);
run_to_block(8, Some(vec![8]));
// Now, we close the channel and wait until the next session.
Hrmp::close_channel(
para_b,
HrmpChannelId {
sender: para_a,
recipient: para_b,
},
)
.unwrap();
Hrmp::close_channel(para_b, HrmpChannelId { sender: para_a, recipient: para_b })
.unwrap();
run_to_block(10, Some(vec![10]));
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
100
);
assert_eq!(
<Test as Config>::Currency::free_balance(&para_b.into_account()),
110
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 100);
assert_eq!(<Test as Config>::Currency::free_balance(&para_b.into_account()), 110);
});
}
@@ -2009,28 +1834,16 @@ mod tests {
register_parachain_with_balance(para_b, 110);
run_to_block(5, Some(vec![4, 5]));
Hrmp::init_open_channel(para_a, para_b, 2, 8).unwrap();
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
80
);
assert_eq!(
<Test as Config>::Currency::free_balance(&para_b.into_account()),
110
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 80);
assert_eq!(<Test as Config>::Currency::free_balance(&para_b.into_account()), 110);
// Request age is 1 out of 2
run_to_block(10, Some(vec![10]));
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
80
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 80);
// Request age is 2 out of 2. The request should expire.
run_to_block(20, Some(vec![20]));
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
100
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 100);
});
}
@@ -2049,14 +1862,8 @@ mod tests {
run_to_block(5, Some(vec![4, 5]));
Hrmp::init_open_channel(para_a, para_b, 2, 8).unwrap();
Hrmp::accept_open_channel(para_b, para_a).unwrap();
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
80
);
assert_eq!(
<Test as Config>::Currency::free_balance(&para_b.into_account()),
95
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 80);
assert_eq!(<Test as Config>::Currency::free_balance(&para_b.into_account()), 95);
run_to_block(8, Some(vec![8]));
assert!(channel_exists(para_a, para_b));
@@ -2069,14 +1876,8 @@ mod tests {
assert!(!channel_exists(para_a, para_b));
assert_storage_consistency_exhaustive();
assert_eq!(
<Test as Config>::Currency::free_balance(&para_a.into_account()),
100
);
assert_eq!(
<Test as Config>::Currency::free_balance(&para_b.into_account()),
110
);
assert_eq!(<Test as Config>::Currency::free_balance(&para_a.into_account()), 100);
assert_eq!(<Test as Config>::Currency::free_balance(&para_b.into_account()), 110);
});
}
}
File diff suppressed because it is too large Load Diff
+40 -46
View File
@@ -19,15 +19,15 @@
//!
//! This module can throw fatal errors if session-change notifications are received after initialization.
use sp_std::prelude::*;
use primitives::v1::{ValidatorId, SessionIndex, ConsensusLog, BlockNumber};
use frame_support::traits::{Randomness, OneSessionHandler};
use parity_scale_codec::{Encode, Decode};
use crate::{
configuration::{self, HostConfiguration},
disputes::DisputesHandler,
shared, paras, scheduler, inclusion, session_info, dmp, ump, hrmp,
dmp, hrmp, inclusion, paras, scheduler, session_info, shared, ump,
};
use frame_support::traits::{OneSessionHandler, Randomness};
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{BlockNumber, ConsensusLog, SessionIndex, ValidatorId};
use sp_std::prelude::*;
pub use pallet::*;
@@ -70,9 +70,9 @@ struct BufferedSessionChange {
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -97,7 +97,6 @@ pub mod pallet {
type ForceOrigin: EnsureOrigin<<Self as frame_system::Config>::Origin>;
}
/// Whether the parachains modules have been initialized within this block.
///
/// Semantically a `bool`, but this guarantees it should never hit the trie,
@@ -117,7 +116,8 @@ pub mod pallet {
/// However this is a `Vec` regardless to handle various edge cases that may occur at runtime
/// upgrade boundaries or if governance intervenes.
#[pallet::storage]
pub(super) type BufferedSessionChanges<T: Config> = StorageValue<_, Vec<BufferedSessionChange>, ValueQuery>;
pub(super) type BufferedSessionChanges<T: Config> =
StorageValue<_, Vec<BufferedSessionChange>, ValueQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
@@ -165,11 +165,8 @@ pub mod pallet {
// next block will observe the next session.
//
// Note that we only apply the last session as all others lasted less than a block (weirdly).
if let Some(BufferedSessionChange {
session_index,
validators,
queued,
}) = BufferedSessionChanges::<T>::take().pop()
if let Some(BufferedSessionChange { session_index, validators, queued }) =
BufferedSessionChanges::<T>::take().pop()
{
Self::apply_new_session(session_index, validators, queued);
}
@@ -250,8 +247,8 @@ impl<T: Config> Pallet<T> {
session_index: SessionIndex,
validators: I,
queued: Option<I>,
)
where I: Iterator<Item=(&'a T::AccountId, ValidatorId)>
) where
I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
{
let validators: Vec<_> = validators.map(|(_, v)| v).collect();
let queued: Vec<_> = if let Some(queued) = queued {
@@ -264,13 +261,10 @@ impl<T: Config> Pallet<T> {
// Genesis session should be immediately enacted.
Self::apply_new_session(0, validators, queued);
} else {
BufferedSessionChanges::<T>::mutate(|v| v.push(BufferedSessionChange {
validators,
queued,
session_index,
}));
BufferedSessionChanges::<T>::mutate(|v| {
v.push(BufferedSessionChange { validators, queued, session_index })
});
}
}
// Allow to trigger on_new_session in tests, this is needed as long as pallet_session is not
@@ -281,8 +275,8 @@ impl<T: Config> Pallet<T> {
session_index: SessionIndex,
validators: I,
queued: Option<I>,
)
where I: Iterator<Item=(&'a T::AccountId, ValidatorId)>
) where
I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
{
Self::on_new_session(changed, session_index, validators, queued)
}
@@ -296,29 +290,31 @@ impl<T: pallet_session::Config + Config> OneSessionHandler<T::AccountId> for Pal
type Key = ValidatorId;
fn on_genesis_session<'a, I: 'a>(validators: I)
where I: Iterator<Item=(&'a T::AccountId, Self::Key)>
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
<Pallet<T>>::on_new_session(false, 0, validators, None);
}
fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued: I)
where I: Iterator<Item=(&'a T::AccountId, Self::Key)>
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
let session_index = <pallet_session::Pallet<T>>::current_index();
<Pallet<T>>::on_new_session(changed, session_index, validators, Some(queued));
}
fn on_disabled(_i: usize) { }
fn on_disabled(_i: usize) {}
}
#[cfg(test)]
mod tests {
use super::*;
use primitives::v1::{Id as ParaId};
use crate::mock::{
new_test_ext,
Initializer, System, Dmp, Paras, Configuration, SessionInfo, MockGenesisConfig,
new_test_ext, Configuration, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo,
System,
};
use primitives::v1::Id as ParaId;
use frame_support::{
assert_ok,
@@ -409,26 +405,24 @@ mod tests {
validation_code: Default::default(),
};
new_test_ext(
MockGenesisConfig {
configuration: crate::configuration::GenesisConfig {
config: crate::configuration::HostConfiguration {
max_downward_message_size: 1024,
..Default::default()
},
},
paras: crate::paras::GenesisConfig {
paras: vec![
(a, mock_genesis.clone()),
(b, mock_genesis.clone()),
(c, mock_genesis.clone()),
],
new_test_ext(MockGenesisConfig {
configuration: crate::configuration::GenesisConfig {
config: crate::configuration::HostConfiguration {
max_downward_message_size: 1024,
..Default::default()
},
},
paras: crate::paras::GenesisConfig {
paras: vec![
(a, mock_genesis.clone()),
(b, mock_genesis.clone()),
(c, mock_genesis.clone()),
],
..Default::default()
}
).execute_with(|| {
},
..Default::default()
})
.execute_with(|| {
// enqueue downward messages to A, B and C.
assert_ok!(Dmp::queue_downward_message(&Configuration::config(), a, vec![1, 2, 3]));
assert_ok!(Dmp::queue_downward_message(&Configuration::config(), b, vec![4, 5, 6]));
+7 -7
View File
@@ -24,18 +24,18 @@
pub mod configuration;
pub mod disputes;
pub mod shared;
pub mod dmp;
pub mod hrmp;
pub mod inclusion;
pub mod initializer;
pub mod origin;
pub mod paras;
pub mod paras_inherent;
pub mod reward_points;
pub mod scheduler;
pub mod session_info;
pub mod origin;
pub mod dmp;
pub mod shared;
pub mod ump;
pub mod hrmp;
pub mod reward_points;
pub mod runtime_api_impl;
@@ -44,9 +44,9 @@ mod util;
#[cfg(test)]
mod mock;
pub use origin::{Origin, ensure_parachain};
use primitives::v1::Id as ParaId;
pub use origin::{ensure_parachain, Origin};
pub use paras::ParaLifecycle;
use primitives::v1::Id as ParaId;
/// Schedule a para to be initialized at the start of the next session with the given genesis data.
pub fn schedule_para_initialize<T: paras::Config>(
+21 -25
View File
@@ -16,23 +16,19 @@
//! Mocks for all the traits.
use sp_io::TestExternalities;
use sp_core::H256;
use sp_runtime::traits::{
BlakeTwo256, IdentityLookup,
};
use primitives::v1::{
AuthorityDiscoveryId, Balance, BlockNumber, Header, ValidatorIndex, SessionIndex,
};
use frame_support::parameter_types;
use frame_support::traits::GenesisBuild;
use frame_support_test::TestRandomness;
use std::cell::RefCell;
use std::collections::HashMap;
use crate::{
inclusion, scheduler, dmp, ump, hrmp, session_info, paras, configuration,
initializer, shared, disputes,
configuration, disputes, dmp, hrmp, inclusion, initializer, paras, scheduler, session_info,
shared, ump,
};
use frame_support::{parameter_types, traits::GenesisBuild};
use frame_support_test::TestRandomness;
use primitives::v1::{
AuthorityDiscoveryId, Balance, BlockNumber, Header, SessionIndex, ValidatorIndex,
};
use sp_core::H256;
use sp_io::TestExternalities;
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
use std::{cell::RefCell, collections::HashMap};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -114,16 +110,16 @@ impl crate::initializer::Config for Test {
type ForceOrigin = frame_system::EnsureRoot<u64>;
}
impl crate::configuration::Config for Test { }
impl crate::configuration::Config for Test {}
impl crate::shared::Config for Test { }
impl crate::shared::Config for Test {}
impl crate::paras::Config for Test {
type Origin = Origin;
type Event = Event;
}
impl crate::dmp::Config for Test { }
impl crate::dmp::Config for Test {}
parameter_types! {
pub const FirstMessageFactorPercent: u64 = 100;
@@ -157,7 +153,7 @@ thread_local! {
impl crate::disputes::RewardValidators for Test {
fn reward_dispute_statement(
session: SessionIndex,
validators: impl IntoIterator<Item=ValidatorIndex>
validators: impl IntoIterator<Item = ValidatorIndex>,
) {
REWARD_VALIDATORS.with(|r| r.borrow_mut().push((session, validators.into_iter().collect())))
}
@@ -166,7 +162,7 @@ impl crate::disputes::RewardValidators for Test {
impl crate::disputes::PunishValidators for Test {
fn punish_for_invalid(
session: SessionIndex,
validators: impl IntoIterator<Item=ValidatorIndex>,
validators: impl IntoIterator<Item = ValidatorIndex>,
) {
PUNISH_VALIDATORS_FOR
.with(|r| r.borrow_mut().push((session, validators.into_iter().collect())))
@@ -174,7 +170,7 @@ impl crate::disputes::PunishValidators for Test {
fn punish_against_valid(
session: SessionIndex,
validators: impl IntoIterator<Item=ValidatorIndex>,
validators: impl IntoIterator<Item = ValidatorIndex>,
) {
PUNISH_VALIDATORS_AGAINST
.with(|r| r.borrow_mut().push((session, validators.into_iter().collect())))
@@ -182,14 +178,14 @@ impl crate::disputes::PunishValidators for Test {
fn punish_inconclusive(
session: SessionIndex,
validators: impl IntoIterator<Item=ValidatorIndex>,
validators: impl IntoIterator<Item = ValidatorIndex>,
) {
PUNISH_VALIDATORS_INCONCLUSIVE
.with(|r| r.borrow_mut().push((session, validators.into_iter().collect())))
}
}
impl crate::scheduler::Config for Test { }
impl crate::scheduler::Config for Test {}
impl crate::inclusion::Config for Test {
type Event = Event;
@@ -197,9 +193,9 @@ impl crate::inclusion::Config for Test {
type RewardValidators = TestRewardValidators;
}
impl crate::paras_inherent::Config for Test { }
impl crate::paras_inherent::Config for Test {}
impl crate::session_info::Config for Test { }
impl crate::session_info::Config for Test {}
thread_local! {
pub static DISCOVERY_AUTHORITIES: RefCell<Vec<AuthorityDiscoveryId>> = RefCell::new(Vec::new());
+5 -4
View File
@@ -16,16 +16,17 @@
//! Declaration of the parachain specific origin and a pallet that hosts it.
use sp_std::result;
use sp_runtime::traits::BadOrigin;
use primitives::v1::Id as ParaId;
use sp_runtime::traits::BadOrigin;
use sp_std::result;
pub use pallet::*;
/// Ensure that the origin `o` represents a parachain.
/// Returns `Ok` with the parachain ID that effected the extrinsic or an `Err` otherwise.
pub fn ensure_parachain<OuterOrigin>(o: OuterOrigin) -> result::Result<ParaId, BadOrigin>
where OuterOrigin: Into<result::Result<Origin, OuterOrigin>>
where
OuterOrigin: Into<result::Result<Origin, OuterOrigin>>,
{
match o.into() {
Ok(Origin::Parachain(id)) => Ok(id),
@@ -41,8 +42,8 @@ pub fn ensure_parachain<OuterOrigin>(o: OuterOrigin) -> result::Result<ParaId, B
// ideally, though, the `construct_runtime` should support a free-standing origin.
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use super::*;
use frame_support::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
+223 -213
View File
@@ -23,20 +23,19 @@
//! A para is not considered live until it is registered and activated in this pallet. Activation can
//! only occur at session boundaries.
use sp_std::prelude::*;
use sp_std::result;
use primitives::v1::{
Id as ParaId, ValidationCode, ValidationCodeHash, HeadData, SessionIndex, ConsensusLog,
};
use sp_runtime::{traits::One, DispatchResult, SaturatedConversion};
use frame_system::pallet_prelude::*;
use crate::{configuration, initializer::SessionChangeNotification, shared};
use frame_support::pallet_prelude::*;
use parity_scale_codec::{Encode, Decode};
use crate::{configuration, shared, initializer::SessionChangeNotification};
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use primitives::v1::{
ConsensusLog, HeadData, Id as ParaId, SessionIndex, ValidationCode, ValidationCodeHash,
};
use sp_core::RuntimeDebug;
use sp_runtime::{traits::One, DispatchResult, SaturatedConversion};
use sp_std::{prelude::*, result};
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
pub use crate::Origin as ParachainOrigin;
@@ -123,10 +122,11 @@ impl ParaLifecycle {
/// This also includes transitioning states, so you may want to combine
/// this check with `is_stable` if you specifically want `Paralifecycle::Parachain`.
pub fn is_parachain(&self) -> bool {
matches!(self,
matches!(
self,
ParaLifecycle::Parachain |
ParaLifecycle::DowngradingParachain |
ParaLifecycle::OffboardingParachain
ParaLifecycle::DowngradingParachain |
ParaLifecycle::OffboardingParachain
)
}
@@ -134,10 +134,11 @@ impl ParaLifecycle {
/// This also includes transitioning states, so you may want to combine
/// this check with `is_stable` if you specifically want `Paralifecycle::Parathread`.
pub fn is_parathread(&self) -> bool {
matches!(self,
matches!(
self,
ParaLifecycle::Parathread |
ParaLifecycle::UpgradingParathread |
ParaLifecycle::OffboardingParathread
ParaLifecycle::UpgradingParathread |
ParaLifecycle::OffboardingParathread
)
}
@@ -196,8 +197,8 @@ impl<N: Ord + Copy + PartialEq> ParaPastCodeMeta<N> {
// The earliest stored code replacement needs to be special-cased, since we need to check
// against the pruning state to see if this replacement represents the correct code, or
// is simply after a replacement that actually represents the correct code, but has been pruned.
let was_pruned = replaced_after_pos == 0
&& self.last_pruned.map_or(false, |t| t >= para_at);
let was_pruned =
replaced_after_pos == 0 && self.last_pruned.map_or(false, |t| t >= para_at);
if was_pruned {
None
@@ -210,10 +211,12 @@ impl<N: Ord + Copy + PartialEq> ParaPastCodeMeta<N> {
// we don't know the code necessary anymore. Compare against `last_pruned` to determine.
self.last_pruned.as_ref().map_or(
Some(UseCodeAt::Current), // nothing pruned, use current
|earliest_activation| if &para_at < earliest_activation {
None
} else {
Some(UseCodeAt::Current)
|earliest_activation| {
if &para_at < earliest_activation {
None
} else {
Some(UseCodeAt::Current)
}
},
)
}
@@ -235,7 +238,7 @@ impl<N: Ord + Copy + PartialEq> ParaPastCodeMeta<N> {
//
// returns an iterator of block numbers at which code was replaced, where the replaced
// code should be now pruned, in ascending order.
fn prune_up_to(&'_ mut self, max: N) -> impl Iterator<Item=N> + '_ {
fn prune_up_to(&'_ mut self, max: N) -> impl Iterator<Item = N> + '_ {
let to_prune = self.upgrade_times.iter().take_while(|t| t.activated_at <= max).count();
let drained = if to_prune == 0 {
// no-op prune.
@@ -271,11 +274,7 @@ pub mod pallet {
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config:
frame_system::Config +
configuration::Config +
shared::Config
{
pub trait Config: frame_system::Config + configuration::Config + shared::Config {
/// The outer origin type.
type Origin: From<Origin>
+ From<<Self as frame_system::Config>::Origin>
@@ -331,32 +330,24 @@ pub mod pallet {
///
/// Corresponding code can be retrieved with [`CodeByHash`].
#[pallet::storage]
pub(super) type CurrentCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
pub(super) type CurrentCodeHash<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
/// Actual past code hash, indicated by the para id as well as the block number at which it
/// became outdated.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
#[pallet::storage]
pub(super) type PastCodeHash<T: Config> = StorageMap<
_,
Twox64Concat,
(ParaId, T::BlockNumber),
ValidationCodeHash
>;
pub(super) type PastCodeHash<T: Config> =
StorageMap<_, Twox64Concat, (ParaId, T::BlockNumber), ValidationCodeHash>;
/// Past code of parachains. The parachains themselves may not be registered anymore,
/// but we also keep their code on-chain for the same amount of time as outdated code
/// to keep it available for secondary checkers.
#[pallet::storage]
#[pallet::getter(fn past_code_meta)]
pub(super) type PastCodeMeta<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
ParaPastCodeMeta<T::BlockNumber>,
ValueQuery
>;
pub(super) type PastCodeMeta<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ParaPastCodeMeta<T::BlockNumber>, ValueQuery>;
/// Which paras have past code that needs pruning and the relay-chain block at which the code was replaced.
/// Note that this is the actual height of the included block, not the expected height at which the
@@ -365,33 +356,39 @@ pub mod pallet {
/// from the time at which the parachain perceives a code upgrade as having occurred.
/// Multiple entries for a single para are permitted. Ordered ascending by block number.
#[pallet::storage]
pub(super) type PastCodePruning<T: Config> = StorageValue<_, Vec<(ParaId, T::BlockNumber)>, ValueQuery>;
pub(super) type PastCodePruning<T: Config> =
StorageValue<_, Vec<(ParaId, T::BlockNumber)>, ValueQuery>;
/// The block number at which the planned code change is expected for a para.
/// The change will be applied after the first parablock for this ID included which executes
/// in the context of a relay chain block with a number >= `expected_at`.
#[pallet::storage]
#[pallet::getter(fn future_code_upgrade_at)]
pub(super) type FutureCodeUpgrades<T: Config> = StorageMap<_, Twox64Concat, ParaId, T::BlockNumber>;
pub(super) type FutureCodeUpgrades<T: Config> =
StorageMap<_, Twox64Concat, ParaId, T::BlockNumber>;
/// The actual future code hash of a para.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
#[pallet::storage]
pub(super) type FutureCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
pub(super) type FutureCodeHash<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
/// The actions to perform during the start of a specific session index.
#[pallet::storage]
#[pallet::getter(fn actions_queue)]
pub(super) type ActionsQueue<T: Config> = StorageMap<_, Twox64Concat, SessionIndex, Vec<ParaId>, ValueQuery>;
pub(super) type ActionsQueue<T: Config> =
StorageMap<_, Twox64Concat, SessionIndex, Vec<ParaId>, ValueQuery>;
/// Upcoming paras instantiation arguments.
#[pallet::storage]
pub(super) type UpcomingParasGenesis<T: Config> = StorageMap<_, Twox64Concat, ParaId, ParaGenesisArgs>;
pub(super) type UpcomingParasGenesis<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ParaGenesisArgs>;
/// The number of reference on the validation code in [`CodeByHash`] storage.
#[pallet::storage]
pub(super) type CodeByHashRefs<T: Config> = StorageMap<_, Identity, ValidationCodeHash, u32, ValueQuery>;
pub(super) type CodeByHashRefs<T: Config> =
StorageMap<_, Identity, ValidationCodeHash, u32, ValueQuery>;
/// Validation code stored by its hash.
///
@@ -399,7 +396,8 @@ pub mod pallet {
/// [`PastCodeHash`].
#[pallet::storage]
#[pallet::getter(fn code_by_hash)]
pub(super) type CodeByHash<T: Config> = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>;
pub(super) type CodeByHash<T: Config> =
StorageMap<_, Identity, ValidationCodeHash, ValidationCode>;
#[pallet::genesis_config]
pub struct GenesisConfig {
@@ -409,16 +407,15 @@ pub mod pallet {
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
GenesisConfig {
paras: Default::default(),
}
GenesisConfig { paras: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
let mut parachains: Vec<_> = self.paras
let mut parachains: Vec<_> = self
.paras
.iter()
.filter(|(_, args)| args.parachain)
.map(|&(ref id, _)| id)
@@ -451,7 +448,11 @@ pub mod pallet {
impl<T: Config> Pallet<T> {
/// Set the storage for the parachain validation code immediately.
#[pallet::weight(0)]
pub fn force_set_current_code(origin: OriginFor<T>, para: ParaId, new_code: ValidationCode) -> DispatchResult {
pub fn force_set_current_code(
origin: OriginFor<T>,
para: ParaId,
new_code: ValidationCode,
) -> DispatchResult {
ensure_root(origin)?;
let prior_code_hash = <Self as Store>::CurrentCodeHash::get(&para).unwrap_or_default();
let new_code_hash = new_code.hash();
@@ -466,7 +467,11 @@ pub mod pallet {
/// Set the storage for the current parachain head data immediately.
#[pallet::weight(0)]
pub fn force_set_current_head(origin: OriginFor<T>, para: ParaId, new_head: HeadData) -> DispatchResult {
pub fn force_set_current_head(
origin: OriginFor<T>,
para: ParaId,
new_head: HeadData,
) -> DispatchResult {
ensure_root(origin)?;
<Self as Store>::Heads::insert(&para, new_head);
Self::deposit_event(Event::CurrentHeadUpdated(para));
@@ -479,7 +484,7 @@ pub mod pallet {
origin: OriginFor<T>,
para: ParaId,
new_code: ValidationCode,
expected_at: T::BlockNumber
expected_at: T::BlockNumber,
) -> DispatchResult {
ensure_root(origin)?;
Self::schedule_code_upgrade(para, new_code, expected_at);
@@ -489,7 +494,11 @@ pub mod pallet {
/// Note a new block head for para within the context of the current block.
#[pallet::weight(0)]
pub fn force_note_new_head(origin: OriginFor<T>, para: ParaId, new_head: HeadData) -> DispatchResult {
pub fn force_note_new_head(
origin: OriginFor<T>,
para: ParaId,
new_head: HeadData,
) -> DispatchResult {
ensure_root(origin)?;
let now = frame_system::Pallet::<T>::block_number();
Self::note_new_head(para, new_head, now);
@@ -522,12 +531,14 @@ impl<T: Config> Pallet<T> {
}
/// Called by the initializer to finalize the configuration pallet.
pub(crate) fn initializer_finalize() { }
pub(crate) fn initializer_finalize() {}
/// Called by the initializer to note that a new session has started.
///
/// Returns the list of outgoing paras from the actions queue.
pub(crate) fn initializer_on_new_session(notification: &SessionChangeNotification<T::BlockNumber>) -> Vec<ParaId> {
pub(crate) fn initializer_on_new_session(
notification: &SessionChangeNotification<T::BlockNumber>,
) -> Vec<ParaId> {
let outgoing_paras = Self::apply_actions_queue(notification.session_index);
outgoing_paras
}
@@ -564,7 +575,8 @@ impl<T: Config> Pallet<T> {
for para in actions {
let lifecycle = ParaLifecycles::<T>::get(&para);
match lifecycle {
None | Some(ParaLifecycle::Parathread) | Some(ParaLifecycle::Parachain) => { /* Nothing to do... */ },
None | Some(ParaLifecycle::Parathread) | Some(ParaLifecycle::Parachain) => { /* Nothing to do... */
},
// Onboard a new parathread or parachain.
Some(ParaLifecycle::Onboarding) => {
if let Some(genesis_data) = <Self as Store>::UpcomingParasGenesis::take(&para) {
@@ -598,7 +610,8 @@ impl<T: Config> Pallet<T> {
ParaLifecycles::<T>::insert(&para, ParaLifecycle::Parathread);
},
// Offboard a parathread or parachain from the system
Some(ParaLifecycle::OffboardingParachain) | Some(ParaLifecycle::OffboardingParathread) => {
Some(ParaLifecycle::OffboardingParachain) |
Some(ParaLifecycle::OffboardingParathread) => {
if let Ok(i) = parachains.binary_search(&para) {
parachains.remove(i);
}
@@ -648,8 +661,8 @@ impl<T: Config> Pallet<T> {
// Schedule pruning for this past-code to be removed as soon as it
// exits the slashing window.
<Self as Store>::PastCodePruning::mutate(|pruning| {
let insert_idx = pruning.binary_search_by_key(&at, |&(_, b)| b)
.unwrap_or_else(|idx| idx);
let insert_idx =
pruning.binary_search_by_key(&at, |&(_, b)| b).unwrap_or_else(|idx| idx);
pruning.insert(insert_idx, (id, now));
});
@@ -663,19 +676,18 @@ impl<T: Config> Pallet<T> {
let code_retention_period = config.code_retention_period;
if now <= code_retention_period {
let weight = T::DbWeight::get().reads_writes(1, 0);
return weight;
return weight
}
// The height of any changes we no longer should keep around.
let pruning_height = now - (code_retention_period + One::one());
let pruning_tasks_done =
<Self as Store>::PastCodePruning::mutate(|pruning_tasks: &mut Vec<(_, T::BlockNumber)>| {
let pruning_tasks_done = <Self as Store>::PastCodePruning::mutate(
|pruning_tasks: &mut Vec<(_, T::BlockNumber)>| {
let (pruning_tasks_done, pruning_tasks_to_do) = {
// find all past code that has just exited the pruning window.
let up_to_idx = pruning_tasks.iter()
.take_while(|&(_, at)| at <= &pruning_height)
.count();
let up_to_idx =
pruning_tasks.iter().take_while(|&(_, at)| at <= &pruning_height).count();
(up_to_idx, pruning_tasks.drain(..up_to_idx))
};
@@ -707,7 +719,8 @@ impl<T: Config> Pallet<T> {
}
pruning_tasks_done as u64
});
},
);
// 1 read for the meta for each pruning task, 1 read for the config
// 2 writes: updating the meta and pruning the code
@@ -751,9 +764,7 @@ impl<T: Config> Pallet<T> {
let lifecycle = ParaLifecycles::<T>::get(&id);
match lifecycle {
// If para is not registered, nothing to do!
None => {
return Ok(())
},
None => return Ok(()),
Some(ParaLifecycle::Parathread) => {
ParaLifecycles::<T>::insert(&id, ParaLifecycle::OffboardingParathread);
},
@@ -864,12 +875,7 @@ impl<T: Config> Pallet<T> {
// `now` is only used for registering pruning as part of `fn note_past_code`
let now = <frame_system::Pallet<T>>::block_number();
let weight = Self::note_past_code(
id,
expected_at,
now,
prior_code_hash,
);
let weight = Self::note_past_code(id, expected_at, now, prior_code_hash);
// add 1 to writes due to heads update.
weight + T::DbWeight::get().reads_writes(3, 1 + 3)
@@ -897,7 +903,7 @@ impl<T: Config> Pallet<T> {
assume_intermediate: Option<T::BlockNumber>,
) -> Option<ValidationCodeHash> {
if assume_intermediate.as_ref().map_or(false, |i| &at <= i) {
return None;
return None
}
let planned_upgrade = <Self as Store>::FutureCodeUpgrades::get(&id);
@@ -912,7 +918,8 @@ impl<T: Config> Pallet<T> {
match Self::past_code_meta(&id).code_at(at) {
None => None,
Some(UseCodeAt::Current) => CurrentCodeHash::<T>::get(&id),
Some(UseCodeAt::ReplacedAt(replaced)) => <Self as Store>::PastCodeHash::get(&(id, replaced)),
Some(UseCodeAt::ReplacedAt(replaced)) =>
<Self as Store>::PastCodeHash::get(&(id, replaced)),
}
}
}
@@ -960,7 +967,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn last_code_upgrade(id: ParaId, include_future: bool) -> Option<T::BlockNumber> {
if include_future {
if let Some(at) = Self::future_code_upgrade_at(id) {
return Some(at);
return Some(at)
}
}
@@ -1013,11 +1020,13 @@ impl<T: Config> Pallet<T> {
#[cfg(test)]
mod tests {
use super::*;
use primitives::v1::BlockNumber;
use frame_support::assert_ok;
use primitives::v1::BlockNumber;
use crate::mock::{new_test_ext, Paras, ParasShared, System, MockGenesisConfig};
use crate::configuration::HostConfiguration;
use crate::{
configuration::HostConfiguration,
mock::{new_test_ext, MockGenesisConfig, Paras, ParasShared, System},
};
fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>>) {
while System::block_number() < to {
@@ -1045,7 +1054,10 @@ mod tests {
}
}
fn upgrade_at(expected_at: BlockNumber, activated_at: BlockNumber) -> ReplacementTimes<BlockNumber> {
fn upgrade_at(
expected_at: BlockNumber,
activated_at: BlockNumber,
) -> ReplacementTimes<BlockNumber> {
ReplacementTimes { expected_at, activated_at }
}
@@ -1103,7 +1115,6 @@ mod tests {
assert_eq!(past_code.code_at(24), Some(UseCodeAt::ReplacedAt(20)));
assert_eq!(past_code.code_at(25), Some(UseCodeAt::ReplacedAt(30)));
assert_eq!(past_code.code_at(30), Some(UseCodeAt::Current));
}
#[test]
@@ -1118,66 +1129,80 @@ mod tests {
assert_eq!(old, past_code);
assert_eq!(past_code.prune_up_to(10).collect::<Vec<_>>(), vec![10]);
assert_eq!(past_code, ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(20, 25), upgrade_at(30, 35)],
last_pruned: Some(10),
});
assert_eq!(
past_code,
ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(20, 25), upgrade_at(30, 35)],
last_pruned: Some(10),
}
);
assert!(past_code.prune_up_to(21).collect::<Vec<_>>().is_empty());
assert_eq!(past_code.prune_up_to(26).collect::<Vec<_>>(), vec![20]);
assert_eq!(past_code, ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(30, 35)],
last_pruned: Some(25),
});
assert_eq!(
past_code,
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(30, 35)], last_pruned: Some(25) }
);
past_code.note_replacement(40, 42);
past_code.note_replacement(50, 53);
past_code.note_replacement(60, 66);
assert_eq!(past_code, ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(30, 35), upgrade_at(40, 42), upgrade_at(50, 53), upgrade_at(60, 66)],
last_pruned: Some(25),
});
assert_eq!(
past_code,
ParaPastCodeMeta {
upgrade_times: vec![
upgrade_at(30, 35),
upgrade_at(40, 42),
upgrade_at(50, 53),
upgrade_at(60, 66)
],
last_pruned: Some(25),
}
);
assert_eq!(past_code.prune_up_to(60).collect::<Vec<_>>(), vec![30, 40, 50]);
assert_eq!(past_code, ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(60, 66)],
last_pruned: Some(53),
});
assert_eq!(
past_code,
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(60, 66)], last_pruned: Some(53) }
);
assert_eq!(past_code.most_recent_change(), Some(60));
assert_eq!(past_code.prune_up_to(66).collect::<Vec<_>>(), vec![60]);
assert_eq!(past_code, ParaPastCodeMeta {
upgrade_times: Vec::new(),
last_pruned: Some(66),
});
assert_eq!(
past_code,
ParaPastCodeMeta { upgrade_times: Vec::new(), last_pruned: Some(66) }
);
}
#[test]
fn para_past_code_pruning_in_initialize() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: Default::default(),
}),
(1u32.into(), ParaGenesisArgs {
parachain: false,
genesis_head: Default::default(),
validation_code: Default::default(),
}),
(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: Default::default(),
},
),
(
1u32.into(),
ParaGenesisArgs {
parachain: false,
genesis_head: Default::default(),
validation_code: Default::default(),
},
),
];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1200,11 +1225,17 @@ mod tests {
}
let pruned_at: BlockNumber = included_block + code_retention_period + 1;
assert_eq!(<Paras as Store>::PastCodeHash::get(&(id, at_block)), Some(validation_code.hash()));
assert_eq!(
<Paras as Store>::PastCodeHash::get(&(id, at_block)),
Some(validation_code.hash())
);
check_code_is_stored(&validation_code);
run_to_block(pruned_at - 1, None);
assert_eq!(<Paras as Store>::PastCodeHash::get(&(id, at_block)), Some(validation_code.hash()));
assert_eq!(
<Paras as Store>::PastCodeHash::get(&(id, at_block)),
Some(validation_code.hash())
);
assert_eq!(Paras::past_code_meta(&id).most_recent_change(), Some(at_block));
check_code_is_stored(&validation_code);
@@ -1218,21 +1249,19 @@ mod tests {
#[test]
fn note_new_head_sets_head() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: Default::default(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1253,25 +1282,28 @@ mod tests {
fn note_past_code_sets_up_pruning_correctly() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: Default::default(),
}),
(1u32.into(), ParaGenesisArgs {
parachain: false,
genesis_head: Default::default(),
validation_code: Default::default(),
}),
(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: Default::default(),
},
),
(
1u32.into(),
ParaGenesisArgs {
parachain: false,
genesis_head: Default::default(),
validation_code: Default::default(),
},
),
];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1287,17 +1319,11 @@ mod tests {
assert_eq!(<Paras as Store>::PastCodePruning::get(), vec![(id_a, 12), (id_b, 23)]);
assert_eq!(
Paras::past_code_meta(&id_a),
ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(10, 12)],
last_pruned: None,
}
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(10, 12)], last_pruned: None }
);
assert_eq!(
Paras::past_code_meta(&id_b),
ParaPastCodeMeta {
upgrade_times: vec![upgrade_at(20, 23)],
last_pruned: None,
}
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(20, 23)], last_pruned: None }
);
});
}
@@ -1308,13 +1334,14 @@ mod tests {
let validation_upgrade_delay = 5;
let original_code = ValidationCode(vec![1, 2, 3]);
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: original_code.clone(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
@@ -1376,10 +1403,7 @@ mod tests {
{
Paras::note_new_head(para_id, Default::default(), expected_at);
assert_eq!(
Paras::past_code_meta(&para_id).most_recent_change(),
Some(expected_at),
);
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(expected_at),);
assert_eq!(
<Paras as Store>::PastCodeHash::get(&(para_id, expected_at)),
Some(original_code.hash()),
@@ -1399,13 +1423,14 @@ mod tests {
let validation_upgrade_delay = 5;
let original_code = ValidationCode(vec![1, 2, 3]);
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: original_code.clone(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
@@ -1448,10 +1473,7 @@ mod tests {
{
Paras::note_new_head(para_id, Default::default(), expected_at + 4);
assert_eq!(
Paras::past_code_meta(&para_id).most_recent_change(),
Some(expected_at),
);
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(expected_at),);
// Some hypothetical block which would have triggered the code change
// should still use the old code.
@@ -1489,21 +1511,19 @@ mod tests {
fn submit_code_change_when_not_allowed_is_err() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: vec![1, 2, 3].into(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1533,21 +1553,19 @@ mod tests {
let code_retention_period = 10;
let original_code = ValidationCode(vec![1, 2, 3]);
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: original_code.clone(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1600,12 +1618,15 @@ mod tests {
}
// run to block #4, with a 2 session changes at the end of the block 2 & 3.
run_to_block(4, Some(vec![3,4]));
run_to_block(4, Some(vec![3, 4]));
// cleaning up the parachain should place the current parachain code
// into the past code buffer & schedule cleanup.
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(3));
assert_eq!(<Paras as Store>::PastCodeHash::get(&(para_id, 3)), Some(original_code.hash()));
assert_eq!(
<Paras as Store>::PastCodeHash::get(&(para_id, 3)),
Some(original_code.hash())
);
assert_eq!(<Paras as Store>::PastCodePruning::get(), vec![(para_id, 3)]);
check_code_is_stored(&original_code);
@@ -1688,9 +1709,8 @@ mod tests {
assert_eq!(<Paras as Store>::ParaLifecycles::get(&b), Some(ParaLifecycle::Onboarding));
assert_eq!(<Paras as Store>::ParaLifecycles::get(&c), Some(ParaLifecycle::Onboarding));
// Two sessions pass, so action queue is triggered
run_to_block(4, Some(vec![3,4]));
run_to_block(4, Some(vec![3, 4]));
assert_eq!(Paras::parachains(), vec![c, b]);
assert_eq!(<Paras as Store>::ActionsQueue::get(Paras::scheduled_session()), Vec::new());
@@ -1710,21 +1730,19 @@ mod tests {
fn code_hash_at_with_intermediate() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: vec![1, 2, 3].into(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1762,21 +1780,19 @@ mod tests {
fn code_hash_at_returns_up_to_end_of_code_retention_period() {
let code_retention_period = 10;
let paras = vec![
(0u32.into(), ParaGenesisArgs {
let paras = vec![(
0u32.into(),
ParaGenesisArgs {
parachain: true,
genesis_head: Default::default(),
validation_code: vec![1, 2, 3].into(),
}),
];
},
)];
let genesis_config = MockGenesisConfig {
paras: GenesisConfig { paras, ..Default::default() },
configuration: crate::configuration::GenesisConfig {
config: HostConfiguration {
code_retention_period,
..Default::default()
},
config: HostConfiguration { code_retention_period, ..Default::default() },
..Default::default()
},
..Default::default()
@@ -1791,10 +1807,7 @@ mod tests {
run_to_block(10, None);
Paras::note_new_head(para_id, Default::default(), 7);
assert_eq!(
Paras::past_code_meta(&para_id).upgrade_times,
vec![upgrade_at(2, 10)],
);
assert_eq!(Paras::past_code_meta(&para_id).upgrade_times, vec![upgrade_at(2, 10)],);
assert_eq!(fetch_validation_code_at(para_id, 2, None), Some(old_code.clone()));
assert_eq!(fetch_validation_code_at(para_id, 3, None), Some(old_code.clone()));
@@ -1814,10 +1827,7 @@ mod tests {
assert_eq!(
Paras::past_code_meta(&para_id),
ParaPastCodeMeta {
upgrade_times: Vec::new(),
last_pruned: Some(10),
},
ParaPastCodeMeta { upgrade_times: Vec::new(), last_pruned: Some(10) },
);
assert_eq!(fetch_validation_code_at(para_id, 2, None), None); // pruned :(
@@ -21,26 +21,26 @@
//! as it has no initialization logic and its finalization logic depends only on the details of
//! this module.
use sp_std::prelude::*;
use sp_runtime::traits::Header as HeaderT;
use primitives::v1::{
BackedCandidate, PARACHAINS_INHERENT_IDENTIFIER, InherentData as ParachainsInherentData,
};
use frame_support::{
decl_error, decl_module, decl_storage, ensure,
dispatch::DispatchResultWithPostInfo,
weights::{DispatchClass, Weight},
traits::Get,
inherent::{InherentIdentifier, InherentData, MakeFatalError, ProvideInherent},
};
use frame_system::ensure_none;
use crate::{
disputes::DisputesHandler,
inclusion,
scheduler::{self, FreedReason},
shared,
ump,
shared, ump,
};
use frame_support::{
decl_error, decl_module, decl_storage,
dispatch::DispatchResultWithPostInfo,
ensure,
inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent},
traits::Get,
weights::{DispatchClass, Weight},
};
use frame_system::ensure_none;
use primitives::v1::{
BackedCandidate, InherentData as ParachainsInherentData, PARACHAINS_INHERENT_IDENTIFIER,
};
use sp_runtime::traits::Header as HeaderT;
use sp_std::prelude::*;
const LOG_TARGET: &str = "runtime::inclusion-inherent";
// In the future, we should benchmark these consts; these are all untested assumptions for now.
@@ -249,7 +249,7 @@ fn limit_backed_candidates<T: Config>(
return false
}
code_upgrades +=1;
code_upgrades += 1;
}
true
@@ -258,7 +258,9 @@ fn limit_backed_candidates<T: Config>(
// the weight of the paras inherent is already included in the current block weight,
// so our operation is simple: if the block is currently overloaded, make this intrinsic smaller
if frame_system::Pallet::<T>::block_weight().total() > <T as frame_system::Config>::BlockWeights::get().max_block {
if frame_system::Pallet::<T>::block_weight().total() >
<T as frame_system::Config>::BlockWeights::get().max_block
{
Vec::new()
} else {
backed_candidates
@@ -271,47 +273,41 @@ impl<T: Config> ProvideInherent for Module<T> {
const INHERENT_IDENTIFIER: InherentIdentifier = PARACHAINS_INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let mut inherent_data: ParachainsInherentData<T::Header>
= match data.get_data(&Self::INHERENT_IDENTIFIER)
{
Ok(Some(d)) => d,
Ok(None) => return None,
Err(_) => {
log::warn!(
target: LOG_TARGET,
"ParachainsInherentData failed to decode",
);
let mut inherent_data: ParachainsInherentData<T::Header> =
match data.get_data(&Self::INHERENT_IDENTIFIER) {
Ok(Some(d)) => d,
Ok(None) => return None,
Err(_) => {
log::warn!(target: LOG_TARGET, "ParachainsInherentData failed to decode",);
return None;
}
};
return None
},
};
// filter out any unneeded dispute statements
T::DisputesHandler::filter_multi_dispute_data(&mut inherent_data.disputes);
// Sanity check: session changes can invalidate an inherent, and we _really_ don't want that to happen.
// See github.com/paritytech/polkadot/issues/1327
let inherent_data = match Self::enter(
frame_system::RawOrigin::None.into(),
inherent_data.clone(),
) {
Ok(_) => inherent_data,
Err(err) => {
log::warn!(
target: LOG_TARGET,
"dropping signed_bitfields and backed_candidates because they produced \
let inherent_data =
match Self::enter(frame_system::RawOrigin::None.into(), inherent_data.clone()) {
Ok(_) => inherent_data,
Err(err) => {
log::warn!(
target: LOG_TARGET,
"dropping signed_bitfields and backed_candidates because they produced \
an invalid paras inherent: {:?}",
err,
);
err,
);
ParachainsInherentData {
bitfields: Vec::new(),
backed_candidates: Vec::new(),
disputes: Vec::new(),
parent_header: inherent_data.parent_header,
}
}
};
ParachainsInherentData {
bitfields: Vec::new(),
backed_candidates: Vec::new(),
disputes: Vec::new(),
parent_header: inherent_data.parent_header,
}
},
};
Some(Call::enter(inherent_data))
}
@@ -325,9 +321,7 @@ impl<T: Config> ProvideInherent for Module<T> {
mod tests {
use super::*;
use crate::mock::{
new_test_ext, System, MockGenesisConfig, Test
};
use crate::mock::{new_test_ext, MockGenesisConfig, System, Test};
mod limit_backed_candidates {
use super::*;
@@ -345,7 +339,8 @@ mod tests {
fn does_not_truncate_on_exactly_full_block() {
new_test_ext(MockGenesisConfig::default()).execute_with(|| {
let backed_candidates = vec![BackedCandidate::default()];
let max_block_weight = <Test as frame_system::Config>::BlockWeights::get().max_block;
let max_block_weight =
<Test as frame_system::Config>::BlockWeights::get().max_block;
// if the consumed resources are precisely equal to the max block weight, we do not truncate.
System::set_block_consumed_resources(max_block_weight, 0);
assert_eq!(limit_backed_candidates::<Test>(backed_candidates).len(), 1);
@@ -356,7 +351,8 @@ mod tests {
fn truncates_on_over_full_block() {
new_test_ext(MockGenesisConfig::default()).execute_with(|| {
let backed_candidates = vec![BackedCandidate::default()];
let max_block_weight = <Test as frame_system::Config>::BlockWeights::get().max_block;
let max_block_weight =
<Test as frame_system::Config>::BlockWeights::get().max_block;
// if the consumed resources are precisely equal to the max block weight, we do not truncate.
System::set_block_consumed_resources(max_block_weight + 1, 0);
assert_eq!(limit_backed_candidates::<Test>(backed_candidates).len(), 0);
@@ -367,7 +363,8 @@ mod tests {
fn all_backed_candidates_get_truncated() {
new_test_ext(MockGenesisConfig::default()).execute_with(|| {
let backed_candidates = vec![BackedCandidate::default(); 10];
let max_block_weight = <Test as frame_system::Config>::BlockWeights::get().max_block;
let max_block_weight =
<Test as frame_system::Config>::BlockWeights::get().max_block;
// if the consumed resources are precisely equal to the max block weight, we do not truncate.
System::set_block_consumed_resources(max_block_weight + 1, 0);
assert_eq!(limit_backed_candidates::<Test>(backed_candidates).len(), 0);
@@ -388,9 +385,7 @@ mod tests {
mod paras_inherent_weight {
use super::*;
use crate::mock::{
new_test_ext, System, MockGenesisConfig, Test
};
use crate::mock::{new_test_ext, MockGenesisConfig, System, Test};
use primitives::v1::Header;
use frame_support::traits::UnfilteredDispatchable;
@@ -425,7 +420,8 @@ mod tests {
(backed_candidates.len() as Weight * BACKED_CANDIDATE_WEIGHT);
// we've used half the block weight; there's plenty of margin
let max_block_weight = <Test as frame_system::Config>::BlockWeights::get().max_block;
let max_block_weight =
<Test as frame_system::Config>::BlockWeights::get().max_block;
let used_block_weight = max_block_weight / 2;
System::set_block_consumed_resources(used_block_weight, 0);
@@ -436,7 +432,9 @@ mod tests {
disputes: Vec::new(),
parent_header: default_header(),
})
.dispatch_bypass_filter(None.into()).unwrap_err().post_info;
.dispatch_bypass_filter(None.into())
.unwrap_err()
.post_info;
// we don't directly check the block's weight post-call. Instead, we check that the
// call has returned the appropriate post-dispatch weight for refund, and trust
@@ -470,7 +468,8 @@ mod tests {
let expected_weight = MINIMAL_INCLUSION_INHERENT_WEIGHT;
// oops, looks like this mandatory call pushed the block weight over the limit
let max_block_weight = <Test as frame_system::Config>::BlockWeights::get().max_block;
let max_block_weight =
<Test as frame_system::Config>::BlockWeights::get().max_block;
let used_block_weight = max_block_weight + 1;
System::set_block_consumed_resources(used_block_weight, 0);
@@ -481,15 +480,13 @@ mod tests {
disputes: Vec::new(),
parent_header: header,
})
.dispatch_bypass_filter(None.into()).unwrap();
.dispatch_bypass_filter(None.into())
.unwrap();
// we don't directly check the block's weight post-call. Instead, we check that the
// call has returned the appropriate post-dispatch weight for refund, and trust
// Substrate to do the right thing with that information.
assert_eq!(
post_info.actual_weight.unwrap(),
expected_weight,
);
assert_eq!(post_info.actual_weight.unwrap(), expected_weight,);
});
}
}
@@ -21,9 +21,9 @@
//! which doesn't currently mention availability bitfields. As such, we don't reward them
//! for the time being, although we will build schemes to do so in the future.
use primitives::v1::ValidatorIndex;
use pallet_staking::SessionInterface;
use crate::shared;
use pallet_staking::SessionInterface;
use primitives::v1::ValidatorIndex;
/// The amount of era points given by backing a candidate that is included.
pub const BACKING_POINTS: u32 = 20;
@@ -31,21 +31,27 @@ pub const BACKING_POINTS: u32 = 20;
/// Rewards validators for participating in parachains with era points in pallet-staking.
pub struct RewardValidatorsWithEraPoints<C>(sp_std::marker::PhantomData<C>);
fn validators_to_reward<C, T, I>(validators: &'_ [T], indirect_indices: I) -> impl IntoIterator<Item=&'_ T> where
fn validators_to_reward<C, T, I>(
validators: &'_ [T],
indirect_indices: I,
) -> impl IntoIterator<Item = &'_ T>
where
C: shared::Config,
I: IntoIterator<Item = ValidatorIndex>
I: IntoIterator<Item = ValidatorIndex>,
{
let validator_indirection = <shared::Pallet<C>>::active_validator_indices();
indirect_indices.into_iter()
indirect_indices
.into_iter()
.filter_map(move |i| validator_indirection.get(i.0 as usize).map(|v| v.clone()))
.filter_map(move |i| validators.get(i.0 as usize))
}
impl<C> crate::inclusion::RewardValidators for RewardValidatorsWithEraPoints<C>
where C: pallet_staking::Config + shared::Config,
where
C: pallet_staking::Config + shared::Config,
{
fn reward_backing(indirect_indices: impl IntoIterator<Item=ValidatorIndex>) {
fn reward_backing(indirect_indices: impl IntoIterator<Item = ValidatorIndex>) {
// Fetch the validators from the _session_ because sessions are offset from eras
// and we are rewarding for behavior in current session.
let validators = C::SessionInterface::validators();
@@ -57,16 +63,18 @@ impl<C> crate::inclusion::RewardValidators for RewardValidatorsWithEraPoints<C>
<pallet_staking::Pallet<C>>::reward_by_ids(rewards);
}
fn reward_bitfields(_validators: impl IntoIterator<Item=ValidatorIndex>) { }
fn reward_bitfields(_validators: impl IntoIterator<Item = ValidatorIndex>) {}
}
#[cfg(test)]
mod tests {
use super::*;
use primitives::v1::ValidatorId;
use crate::configuration::HostConfiguration;
use crate::mock::{new_test_ext, MockGenesisConfig, ParasShared, Test};
use crate::{
configuration::HostConfiguration,
mock::{new_test_ext, MockGenesisConfig, ParasShared, Test},
};
use keyring::Sr25519Keyring;
use primitives::v1::ValidatorId;
#[test]
fn rewards_based_on_indirection() {
@@ -88,12 +96,8 @@ mod tests {
let pubkeys = validator_pubkeys(&validators);
let shuffled_pubkeys = ParasShared::initializer_on_new_session(
1,
[1; 32],
&config,
pubkeys,
);
let shuffled_pubkeys =
ParasShared::initializer_on_new_session(1, [1; 32], &config, pubkeys);
assert_eq!(
shuffled_pubkeys,
@@ -121,7 +125,10 @@ mod tests {
validators_to_reward::<Test, _, _>(
&validators,
vec![ValidatorIndex(0), ValidatorIndex(1), ValidatorIndex(2)],
).into_iter().copied().collect::<Vec<_>>(),
)
.into_iter()
.copied()
.collect::<Vec<_>>(),
vec![Sr25519Keyring::Ferdie, Sr25519Keyring::Bob, Sr25519Keyring::Charlie],
);
})
@@ -17,9 +17,9 @@
//! Runtimes implementing the v1 runtime API are recommended to forward directly to these
//! functions.
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use sp_runtime::traits::One;
use crate::{
configuration, dmp, hrmp, inclusion, initializer, paras, scheduler, session_info, shared,
};
use primitives::v1::{
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied,
CoreState, GroupIndex, GroupRotationInfo, Id as ParaId, InboundDownwardMessage,
@@ -27,8 +27,8 @@ use primitives::v1::{
ScheduledCore, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
};
use crate::{initializer, inclusion, scheduler, configuration, paras, session_info, dmp, hrmp, shared};
use sp_runtime::traits::One;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
/// Implementation for the `validators` function of the runtime API.
pub fn validators<T: initializer::Config>() -> Vec<ValidatorId> {
@@ -36,10 +36,8 @@ pub fn validators<T: initializer::Config>() -> Vec<ValidatorId> {
}
/// Implementation for the `validator_groups` function of the runtime API.
pub fn validator_groups<T: initializer::Config>() -> (
Vec<Vec<ValidatorIndex>>,
GroupRotationInfo<T::BlockNumber>,
) {
pub fn validator_groups<T: initializer::Config>(
) -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<T::BlockNumber>) {
let now = <frame_system::Pallet<T>>::block_number() + One::one();
let groups = <scheduler::Pallet<T>>::validator_groups();
@@ -80,10 +78,13 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
}
};
let group_responsible_for = |backed_in_number, core_index| {
match <scheduler::Pallet<T>>::group_assigned_to_core(core_index, backed_in_number) {
let group_responsible_for =
|backed_in_number, core_index| match <scheduler::Pallet<T>>::group_assigned_to_core(
core_index,
backed_in_number,
) {
Some(g) => g,
None => {
None => {
log::warn!(
target: "runtime::polkadot-api::v1",
"Could not determine the group responsible for core extracted \
@@ -91,23 +92,24 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
);
GroupIndex(0)
}
}
};
},
};
let mut core_states: Vec<_> = cores.into_iter().enumerate().map(|(i, core)| match core {
Some(occupied) => {
CoreState::Occupied(match occupied {
let mut core_states: Vec<_> = cores
.into_iter()
.enumerate()
.map(|(i, core)| match core {
Some(occupied) => CoreState::Occupied(match occupied {
CoreOccupied::Parachain => {
let para_id = parachains[i];
let pending_availability = <inclusion::Pallet<T>>
::pending_availability(para_id)
.expect("Occupied core always has pending availability; qed");
let pending_availability =
<inclusion::Pallet<T>>::pending_availability(para_id)
.expect("Occupied core always has pending availability; qed");
let backed_in_number = pending_availability.backed_in_number().clone();
OccupiedCore {
next_up_on_available: <scheduler::Pallet<T>>::next_up_on_available(
CoreIndex(i as u32)
CoreIndex(i as u32),
),
occupied_since: backed_in_number,
time_out_at: time_out_at(
@@ -115,7 +117,7 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
config.chain_availability_period,
),
next_up_on_time_out: <scheduler::Pallet<T>>::next_up_on_time_out(
CoreIndex(i as u32)
CoreIndex(i as u32),
),
availability: pending_availability.availability_votes().clone(),
group_responsible: group_responsible_for(
@@ -125,17 +127,17 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
candidate_hash: pending_availability.candidate_hash(),
candidate_descriptor: pending_availability.candidate_descriptor().clone(),
}
}
},
CoreOccupied::Parathread(p) => {
let para_id = p.claim.0;
let pending_availability = <inclusion::Pallet<T>>
::pending_availability(para_id)
.expect("Occupied core always has pending availability; qed");
let pending_availability =
<inclusion::Pallet<T>>::pending_availability(para_id)
.expect("Occupied core always has pending availability; qed");
let backed_in_number = pending_availability.backed_in_number().clone();
OccupiedCore {
next_up_on_available: <scheduler::Pallet<T>>::next_up_on_available(
CoreIndex(i as u32)
CoreIndex(i as u32),
),
occupied_since: backed_in_number,
time_out_at: time_out_at(
@@ -143,7 +145,7 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
config.thread_availability_period,
),
next_up_on_time_out: <scheduler::Pallet<T>>::next_up_on_time_out(
CoreIndex(i as u32)
CoreIndex(i as u32),
),
availability: pending_availability.availability_votes().clone(),
group_responsible: group_responsible_for(
@@ -153,11 +155,11 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, T:
candidate_hash: pending_availability.candidate_hash(),
candidate_descriptor: pending_availability.candidate_descriptor().clone(),
}
}
})
}
None => CoreState::Free,
}).collect();
},
}),
None => CoreState::Free,
})
.collect();
// This will overwrite only `Free` cores if the scheduler module is working as intended.
for scheduled in <scheduler::Pallet<T>>::scheduled() {
@@ -174,7 +176,8 @@ fn with_assumption<Config, T, F>(
para_id: ParaId,
assumption: OccupiedCoreAssumption,
build: F,
) -> Option<T> where
) -> Option<T>
where
Config: inclusion::Config,
F: FnOnce() -> Option<T>,
{
@@ -182,17 +185,15 @@ fn with_assumption<Config, T, F>(
OccupiedCoreAssumption::Included => {
<inclusion::Pallet<Config>>::force_enact(para_id);
build()
}
OccupiedCoreAssumption::TimedOut => {
build()
}
},
OccupiedCoreAssumption::TimedOut => build(),
OccupiedCoreAssumption::Free => {
if <inclusion::Pallet<Config>>::pending_availability(para_id).is_some() {
None
} else {
build()
}
}
},
}
}
@@ -237,7 +238,8 @@ pub fn session_index_for_child<T: initializer::Config>() -> SessionIndex {
/// Implementation for the `AuthorityDiscoveryApi::authorities()` function of the runtime API.
/// It is a heavy call, but currently only used for authority discovery, so it is fine.
/// Gets next, current and some historical authority ids using `session_info` module.
pub fn relevant_authority_ids<T: initializer::Config + pallet_authority_discovery::Config>() -> Vec<AuthorityDiscoveryId> {
pub fn relevant_authority_ids<T: initializer::Config + pallet_authority_discovery::Config>(
) -> Vec<AuthorityDiscoveryId> {
let current_session_index = session_index_for_child::<T>();
let earliest_stored_session = <session_info::Pallet<T>>::earliest_stored_session();
@@ -267,17 +269,13 @@ pub fn validation_code<T: initializer::Config>(
para_id: ParaId,
assumption: OccupiedCoreAssumption,
) -> Option<ValidationCode> {
with_assumption::<T, _, _>(
para_id,
assumption,
|| <paras::Pallet<T>>::current_code(&para_id),
)
with_assumption::<T, _, _>(para_id, assumption, || <paras::Pallet<T>>::current_code(&para_id))
}
/// Implementation for the `candidate_pending_availability` function of the runtime API.
pub fn candidate_pending_availability<T: initializer::Config>(para_id: ParaId)
-> Option<CommittedCandidateReceipt<T::Hash>>
{
pub fn candidate_pending_availability<T: initializer::Config>(
para_id: ParaId,
) -> Option<CommittedCandidateReceipt<T::Hash>> {
<inclusion::Pallet<T>>::candidate_pending_availability(para_id)
}
@@ -291,17 +289,17 @@ where
{
use inclusion::Event as RawEvent;
<frame_system::Pallet<T>>::events().into_iter()
<frame_system::Pallet<T>>::events()
.into_iter()
.filter_map(|record| extract_event(record.event))
.map(|event| match event {
RawEvent::<T>::CandidateBacked(c, h, core, group)
=> CandidateEvent::CandidateBacked(c, h, core, group),
RawEvent::<T>::CandidateIncluded(c, h, core, group)
=> CandidateEvent::CandidateIncluded(c, h, core, group),
RawEvent::<T>::CandidateTimedOut(c, h, core)
=> CandidateEvent::CandidateTimedOut(c, h, core),
RawEvent::<T>::__Ignore(_, _)
=> unreachable!("__Ignore cannot be used"),
RawEvent::<T>::CandidateBacked(c, h, core, group) =>
CandidateEvent::CandidateBacked(c, h, core, group),
RawEvent::<T>::CandidateIncluded(c, h, core, group) =>
CandidateEvent::CandidateIncluded(c, h, core, group),
RawEvent::<T>::CandidateTimedOut(c, h, core) =>
CandidateEvent::CandidateTimedOut(c, h, core),
RawEvent::<T>::__Ignore(_, _) => unreachable!("__Ignore cannot be used"),
})
.collect()
}
File diff suppressed because it is too large Load Diff
+30 -39
View File
@@ -19,11 +19,9 @@
//!
//! See https://w3f.github.io/parachain-implementers-guide/runtime/session_info.html.
use crate::{configuration, paras, scheduler, shared, util::take_active_subset};
use frame_support::{pallet_prelude::*, traits::OneSessionHandler};
use primitives::v1::{AssignmentId, AuthorityDiscoveryId, SessionIndex, SessionInfo};
use frame_support::pallet_prelude::*;
use frame_support::traits::OneSessionHandler;
use crate::{configuration, paras, scheduler, shared};
use crate::util::take_active_subset;
use sp_std::vec::Vec;
pub use pallet::*;
@@ -51,7 +49,8 @@ pub mod pallet {
/// Note that this API is private due to it being prone to 'off-by-one' at session boundaries.
/// When in doubt, use `Sessions` API instead.
#[pallet::storage]
pub(super) type AssignmentKeysUnsafe<T: Config> = StorageValue<_, Vec<AssignmentId>, ValueQuery>;
pub(super) type AssignmentKeysUnsafe<T: Config> =
StorageValue<_, Vec<AssignmentId>, ValueQuery>;
/// The earliest session for which previous session info is stored.
#[pallet::storage]
@@ -82,7 +81,7 @@ impl<T: pallet_authority_discovery::Config> AuthorityDiscoveryConfig for T {
impl<T: Config> Pallet<T> {
/// Handle an incoming session change.
pub(crate) fn initializer_on_new_session(
notification: &crate::initializer::SessionChangeNotification<T::BlockNumber>
notification: &crate::initializer::SessionChangeNotification<T::BlockNumber>,
) {
let config = <configuration::Pallet<T>>::config();
@@ -104,7 +103,8 @@ impl<T: Config> Pallet<T> {
let new_session_index = notification.session_index;
let old_earliest_stored_session = EarliestStoredSession::<T>::get();
let new_earliest_stored_session = new_session_index.saturating_sub(dispute_period);
let new_earliest_stored_session = core::cmp::max(new_earliest_stored_session, old_earliest_stored_session);
let new_earliest_stored_session =
core::cmp::max(new_earliest_stored_session, old_earliest_stored_session);
// remove all entries from `Sessions` from the previous value up to the new value
// avoid a potentially heavy loop when introduced on a live chain
if old_earliest_stored_session != 0 || Sessions::<T>::get(0).is_some() {
@@ -150,33 +150,35 @@ impl<T: pallet_session::Config + Config> OneSessionHandler<T::AccountId> for Pal
type Key = AssignmentId;
fn on_genesis_session<'a, I: 'a>(_validators: I)
where I: Iterator<Item=(&'a T::AccountId, Self::Key)>
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
}
fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, _queued: I)
where I: Iterator<Item=(&'a T::AccountId, Self::Key)>
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
let assignment_keys: Vec<_> = validators.map(|(_, v)| v).collect();
AssignmentKeysUnsafe::<T>::set(assignment_keys);
}
fn on_disabled(_i: usize) { }
fn on_disabled(_i: usize) {}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::{
new_test_ext, Configuration, SessionInfo, System, MockGenesisConfig,
Origin, ParasShared, Test
use crate::{
configuration::HostConfiguration,
initializer::SessionChangeNotification,
mock::{
new_test_ext, Configuration, MockGenesisConfig, Origin, ParasShared, SessionInfo,
System, Test,
},
};
use crate::initializer::SessionChangeNotification;
use crate::configuration::HostConfiguration;
use primitives::v1::{BlockNumber, ValidatorId, ValidatorIndex};
use keyring::Sr25519Keyring;
use primitives::v1::{BlockNumber, ValidatorId, ValidatorIndex};
fn run_to_block(
to: BlockNumber,
@@ -190,9 +192,7 @@ mod tests {
Configuration::initializer_finalize();
if let Some(notification) = new_session(b + 1) {
Configuration::initializer_on_new_session(
&notification.session_index,
);
Configuration::initializer_on_new_session(&notification.session_index);
ParasShared::initializer_on_new_session(
notification.session_index,
notification.random_seed,
@@ -234,20 +234,14 @@ mod tests {
fn session_changes(n: BlockNumber) -> Option<SessionChangeNotification<BlockNumber>> {
if n % 10 == 0 {
Some(SessionChangeNotification {
session_index: n / 10,
..Default::default()
})
Some(SessionChangeNotification { session_index: n / 10, ..Default::default() })
} else {
None
}
}
fn new_session_every_block(n: BlockNumber) -> Option<SessionChangeNotification<BlockNumber>> {
Some(SessionChangeNotification{
session_index: n,
..Default::default()
})
Some(SessionChangeNotification { session_index: n, ..Default::default() })
}
#[test]
@@ -333,20 +327,17 @@ mod tests {
let active_set = vec![ValidatorIndex(4), ValidatorIndex(0), ValidatorIndex(2)];
let unscrambled_validators: Vec<ValidatorId>
= unscrambled.iter().map(|v| v.public().into()).collect();
let unscrambled_discovery: Vec<AuthorityDiscoveryId>
= unscrambled.iter().map(|v| v.public().into()).collect();
let unscrambled_assignment: Vec<AssignmentId>
= unscrambled.iter().map(|v| v.public().into()).collect();
let unscrambled_validators: Vec<ValidatorId> =
unscrambled.iter().map(|v| v.public().into()).collect();
let unscrambled_discovery: Vec<AuthorityDiscoveryId> =
unscrambled.iter().map(|v| v.public().into()).collect();
let unscrambled_assignment: Vec<AssignmentId> =
unscrambled.iter().map(|v| v.public().into()).collect();
let validators = take_active_subset(&active_set, &unscrambled_validators);
new_test_ext(genesis_config()).execute_with(|| {
ParasShared::set_active_validators_with_indices(
active_set.clone(),
validators.clone(),
);
ParasShared::set_active_validators_with_indices(active_set.clone(), validators.clone());
assert_eq!(ParasShared::active_validator_indices(), active_set);
+18 -39
View File
@@ -19,11 +19,11 @@
//! To avoid cyclic dependencies, it is important that this pallet is not
//! dependent on any of the other pallets.
use primitives::v1::{SessionIndex, ValidatorId, ValidatorIndex};
use frame_support::pallet_prelude::*;
use primitives::v1::{SessionIndex, ValidatorId, ValidatorIndex};
use sp_std::vec::Vec;
use rand::{SeedableRng, seq::SliceRandom};
use rand::{seq::SliceRandom, SeedableRng};
use rand_chacha::ChaCha20Rng;
use crate::configuration::HostConfiguration;
@@ -55,7 +55,8 @@ pub mod pallet {
/// Indices are into the broader validator set.
#[pallet::storage]
#[pallet::getter(fn active_validator_indices)]
pub(super) type ActiveValidatorIndices<T: Config> = StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
pub(super) type ActiveValidatorIndices<T: Config> =
StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
/// The parachain attestation keys of the validators actively participating in parachain consensus.
/// This should be the same length as `ActiveValidatorIndices`.
@@ -74,7 +75,7 @@ impl<T: Config> Pallet<T> {
}
/// Called by the initializer to finalize the configuration pallet.
pub(crate) fn initializer_finalize() { }
pub(crate) fn initializer_finalize() {}
/// Called by the initializer to note that a new session has started.
///
@@ -99,10 +100,8 @@ impl<T: Config> Pallet<T> {
shuffled_indices.truncate(max as usize);
}
let active_validator_keys = crate::util::take_active_subset(
&shuffled_indices,
&all_validators,
);
let active_validator_keys =
crate::util::take_active_subset(&shuffled_indices, &all_validators);
ActiveValidatorIndices::<T>::set(shuffled_indices);
ActiveValidatorKeys::<T>::set(active_validator_keys.clone());
@@ -124,7 +123,7 @@ impl<T: Config> Pallet<T> {
#[cfg(test)]
pub(crate) fn set_active_validators_ascending(active: Vec<ValidatorId>) {
ActiveValidatorIndices::<T>::set(
(0..active.len()).map(|i| ValidatorIndex(i as _)).collect()
(0..active.len()).map(|i| ValidatorIndex(i as _)).collect(),
);
ActiveValidatorKeys::<T>::set(active);
}
@@ -143,8 +142,10 @@ impl<T: Config> Pallet<T> {
#[cfg(test)]
mod tests {
use super::*;
use crate::configuration::HostConfiguration;
use crate::mock::{new_test_ext, MockGenesisConfig, ParasShared};
use crate::{
configuration::HostConfiguration,
mock::{new_test_ext, MockGenesisConfig, ParasShared},
};
use keyring::Sr25519Keyring;
fn validator_pubkeys(val_ids: &[Sr25519Keyring]) -> Vec<ValidatorId> {
@@ -167,12 +168,7 @@ mod tests {
let pubkeys = validator_pubkeys(&validators);
new_test_ext(MockGenesisConfig::default()).execute_with(|| {
let validators = ParasShared::initializer_on_new_session(
1,
[1; 32],
&config,
pubkeys,
);
let validators = ParasShared::initializer_on_new_session(1, [1; 32], &config, pubkeys);
assert_eq!(
validators,
@@ -185,10 +181,7 @@ mod tests {
])
);
assert_eq!(
ParasShared::active_validator_keys(),
validators,
);
assert_eq!(ParasShared::active_validator_keys(), validators,);
assert_eq!(
ParasShared::active_validator_indices(),
@@ -219,32 +212,18 @@ mod tests {
let pubkeys = validator_pubkeys(&validators);
new_test_ext(MockGenesisConfig::default()).execute_with(|| {
let validators = ParasShared::initializer_on_new_session(
1,
[1; 32],
&config,
pubkeys,
);
let validators = ParasShared::initializer_on_new_session(1, [1; 32], &config, pubkeys);
assert_eq!(
validators,
validator_pubkeys(&[
Sr25519Keyring::Ferdie,
Sr25519Keyring::Bob,
])
validator_pubkeys(&[Sr25519Keyring::Ferdie, Sr25519Keyring::Bob,])
);
assert_eq!(
ParasShared::active_validator_keys(),
validators,
);
assert_eq!(ParasShared::active_validator_keys(), validators,);
assert_eq!(
ParasShared::active_validator_indices(),
vec![
ValidatorIndex(4),
ValidatorIndex(1),
]
vec![ValidatorIndex(4), ValidatorIndex(1),]
);
});
}
+104 -133
View File
@@ -18,10 +18,15 @@ use crate::{
configuration::{self, HostConfiguration},
initializer,
};
use sp_std::{prelude::*, fmt, marker::PhantomData, convert::TryFrom};
use sp_std::collections::{btree_map::BTreeMap, vec_deque::VecDeque};
use frame_support::pallet_prelude::*;
use primitives::v1::{Id as ParaId, UpwardMessage};
use sp_std::{
collections::{btree_map::BTreeMap, vec_deque::VecDeque},
convert::TryFrom,
fmt,
marker::PhantomData,
prelude::*,
};
use xcm::v0::Outcome;
pub use pallet::*;
@@ -46,13 +51,21 @@ pub trait UmpSink {
/// it did not begin processing a message since it would otherwise exceed `max_weight`.
///
/// See the trait docs for more details.
fn process_upward_message(origin: ParaId, msg: &[u8], max_weight: Weight) -> Result<Weight, (MessageId, Weight)>;
fn process_upward_message(
origin: ParaId,
msg: &[u8],
max_weight: Weight,
) -> Result<Weight, (MessageId, Weight)>;
}
/// An implementation of a sink that just swallows the message without consuming any weight. Returns
/// `Some(0)` indicating that no messages existed for it to process.
impl UmpSink for () {
fn process_upward_message(_: ParaId, _: &[u8], _: Weight) -> Result<Weight, (MessageId, Weight)> {
fn process_upward_message(
_: ParaId,
_: &[u8],
_: Weight,
) -> Result<Weight, (MessageId, Weight)> {
Ok(0)
}
}
@@ -66,13 +79,19 @@ pub type MessageId = [u8; 32];
pub struct XcmSink<XcmExecutor, Config>(PhantomData<(XcmExecutor, Config)>);
impl<XcmExecutor: xcm::v0::ExecuteXcm<C::Call>, C: Config> UmpSink for XcmSink<XcmExecutor, C> {
fn process_upward_message(origin: ParaId, data: &[u8], max_weight: Weight) -> Result<Weight, (MessageId, Weight)> {
use xcm::VersionedXcm;
use xcm::v0::{Xcm, Junction, MultiLocation, Error as XcmError};
fn process_upward_message(
origin: ParaId,
data: &[u8],
max_weight: Weight,
) -> Result<Weight, (MessageId, Weight)> {
use xcm::{
v0::{Error as XcmError, Junction, MultiLocation, Xcm},
VersionedXcm,
};
let id = sp_io::hashing::blake2_256(&data[..]);
let maybe_msg = VersionedXcm::<C::Call>::decode(&mut &data[..])
.map(Xcm::<C::Call>::try_from);
let maybe_msg =
VersionedXcm::<C::Call>::decode(&mut &data[..]).map(Xcm::<C::Call>::try_from);
match maybe_msg {
Err(_) => {
Pallet::<C>::deposit_event(Event::InvalidFormat(id));
@@ -92,9 +111,9 @@ impl<XcmExecutor: xcm::v0::ExecuteXcm<C::Call>, C: Config> UmpSink for XcmSink<X
let weight_used = outcome.weight_used();
Pallet::<C>::deposit_event(Event::ExecutedUpward(id, outcome));
Ok(weight_used)
}
},
}
}
},
}
}
}
@@ -102,23 +121,10 @@ impl<XcmExecutor: xcm::v0::ExecuteXcm<C::Call>, C: Config> UmpSink for XcmSink<X
/// An error returned by [`check_upward_messages`] that indicates a violation of one of acceptance
/// criteria rules.
pub enum AcceptanceCheckErr {
MoreMessagesThanPermitted {
sent: u32,
permitted: u32,
},
MessageSize {
idx: u32,
msg_size: u32,
max_size: u32,
},
CapacityExceeded {
count: u32,
limit: u32,
},
TotalSizeExceeded {
total_size: u32,
limit: u32,
},
MoreMessagesThanPermitted { sent: u32, permitted: u32 },
MessageSize { idx: u32, msg_size: u32, max_size: u32 },
CapacityExceeded { count: u32, limit: u32 },
TotalSizeExceeded { total_size: u32, limit: u32 },
}
impl fmt::Debug for AcceptanceCheckErr {
@@ -129,11 +135,7 @@ impl fmt::Debug for AcceptanceCheckErr {
"more upward messages than permitted by config ({} > {})",
sent, permitted,
),
AcceptanceCheckErr::MessageSize {
idx,
msg_size,
max_size,
} => write!(
AcceptanceCheckErr::MessageSize { idx, msg_size, max_size } => write!(
fmt,
"upward message idx {} larger than permitted by config ({} > {})",
idx, msg_size, max_size,
@@ -204,13 +206,8 @@ pub mod pallet {
///
/// The messages are processed in FIFO order.
#[pallet::storage]
pub type RelayDispatchQueues<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
VecDeque<UpwardMessage>,
ValueQuery
>;
pub type RelayDispatchQueues<T: Config> =
StorageMap<_, Twox64Concat, ParaId, VecDeque<UpwardMessage>, ValueQuery>;
/// Size of the dispatch queues. Caches sizes of the queues in `RelayDispatchQueue`.
///
@@ -226,13 +223,8 @@ pub mod pallet {
// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
// the format will require migration of parachains.
#[pallet::storage]
pub type RelayDispatchQueueSize<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
(u32, u32),
ValueQuery
>;
pub type RelayDispatchQueueSize<T: Config> =
StorageMap<_, Twox64Concat, ParaId, (u32, u32), ValueQuery>;
/// The ordered list of `ParaId`s that have a `RelayDispatchQueue` entry.
///
@@ -311,7 +303,7 @@ impl<T: Config> Pallet<T> {
return Err(AcceptanceCheckErr::MoreMessagesThanPermitted {
sent: upward_messages.len() as u32,
permitted: config.max_upward_message_num_per_candidate,
});
})
}
let (mut para_queue_count, mut para_queue_size) =
@@ -324,7 +316,7 @@ impl<T: Config> Pallet<T> {
idx: idx as u32,
msg_size,
max_size: config.max_upward_message_size,
});
})
}
para_queue_count += 1;
para_queue_size += msg_size;
@@ -336,13 +328,13 @@ impl<T: Config> Pallet<T> {
return Err(AcceptanceCheckErr::CapacityExceeded {
count: para_queue_count,
limit: config.max_upward_queue_count,
});
})
}
if para_queue_size > config.max_upward_queue_size {
return Err(AcceptanceCheckErr::TotalSizeExceeded {
total_size: para_queue_size,
limit: config.max_upward_queue_size,
});
})
}
Ok(())
@@ -364,10 +356,13 @@ impl<T: Config> Pallet<T> {
v.extend(upward_messages.into_iter())
});
<Self as Store>::RelayDispatchQueueSize::mutate(&para, |(ref mut cnt, ref mut size)| {
*cnt += extra_count;
*size += extra_size;
});
<Self as Store>::RelayDispatchQueueSize::mutate(
&para,
|(ref mut cnt, ref mut size)| {
*cnt += extra_count;
*size += extra_size;
},
);
<Self as Store>::NeedsDispatch::mutate(|v| {
if let Err(i) = v.binary_search(&para) {
@@ -398,7 +393,7 @@ impl<T: Config> Pallet<T> {
// preferred weight for the dispatching stage.
//
// if so - bail.
break;
break
}
let max_weight = if weight_used == 0 {
// we increase the amount of weight that we're allowed to use on the first message to try to prevent
@@ -411,7 +406,11 @@ impl<T: Config> Pallet<T> {
// dequeue the next message from the queue of the dispatchee
let (upward_message, became_empty) = queue_cache.dequeue::<T>(dispatchee);
if let Some(upward_message) = upward_message {
match T::UmpSink::process_upward_message(dispatchee, &upward_message[..], max_weight) {
match T::UmpSink::process_upward_message(
dispatchee,
&upward_message[..],
max_weight,
) {
Ok(used) => weight_used += used,
Err((id, required)) => {
// we process messages in order and don't drop them if we run out of weight, so need to break
@@ -478,11 +477,7 @@ impl QueueCache {
let cache_entry = self.0.entry(para).or_insert_with(|| {
let queue = <Pallet<T> as Store>::RelayDispatchQueues::get(&para);
let (count, total_size) = <Pallet<T> as Store>::RelayDispatchQueueSize::get(&para);
QueueCacheEntry {
queue,
count,
total_size,
}
QueueCacheEntry { queue, count, total_size }
});
let upward_message = cache_entry.queue.pop_front();
if let Some(ref msg) = upward_message {
@@ -499,15 +494,7 @@ impl QueueCache {
// NOTE we use an explicit method here instead of Drop impl because it has unwanted semantics
// within runtime. It is dangerous to use because of double-panics and flushing on a panic
// is not necessary as well.
for (
para,
QueueCacheEntry {
queue,
count,
total_size,
},
) in self.0
{
for (para, QueueCacheEntry { queue, count, total_size }) in self.0 {
if queue.is_empty() {
// remove the entries altogether.
<Pallet<T> as Store>::RelayDispatchQueues::remove(&para);
@@ -551,15 +538,12 @@ impl NeedsDispatchCursor {
// let's select 0 as the starting index as a safe bet.
debug_assert!(false);
0
}
},
},
None => 0,
};
Self {
needs_dispatch,
index: initial_index,
}
Self { needs_dispatch, index: initial_index }
}
/// Returns the item the cursor points to.
@@ -570,7 +554,7 @@ impl NeedsDispatchCursor {
/// Moves the cursor to the next item.
fn advance(&mut self) {
if self.needs_dispatch.is_empty() {
return;
return
}
self.index = (self.index + 1) % self.needs_dispatch.len();
}
@@ -578,7 +562,7 @@ impl NeedsDispatchCursor {
/// Removes the item under the cursor.
fn remove(&mut self) {
if self.needs_dispatch.is_empty() {
return;
return
}
let _ = self.needs_dispatch.remove(self.index);
@@ -615,10 +599,9 @@ pub(crate) mod mock_sink {
//! 2. All messages expected by the probe must be received by the time of dropping it. Unreceived
//! messages will lead to a panic while dropping a probe.
use super::{UmpSink, UpwardMessage, ParaId, MessageId};
use std::cell::RefCell;
use std::collections::vec_deque::VecDeque;
use super::{MessageId, ParaId, UmpSink, UpwardMessage};
use frame_support::weights::Weight;
use std::{cell::RefCell, collections::vec_deque::VecDeque};
#[derive(Debug)]
struct UmpExpectation {
@@ -634,25 +617,30 @@ pub(crate) mod mock_sink {
pub struct MockUmpSink;
impl UmpSink for MockUmpSink {
fn process_upward_message(actual_origin: ParaId, actual_msg: &[u8], _max_weight: Weight) -> Result<Weight, (MessageId, Weight)> {
Ok(HOOK.with(|opt_hook| opt_hook.borrow_mut().as_mut().map(|hook| {
let UmpExpectation {
expected_origin,
expected_msg,
mock_weight,
} = match hook.pop_front() {
Some(expectation) => expectation,
None => {
panic!(
fn process_upward_message(
actual_origin: ParaId,
actual_msg: &[u8],
_max_weight: Weight,
) -> Result<Weight, (MessageId, Weight)> {
Ok(HOOK
.with(|opt_hook| {
opt_hook.borrow_mut().as_mut().map(|hook| {
let UmpExpectation { expected_origin, expected_msg, mock_weight } =
match hook.pop_front() {
Some(expectation) => expectation,
None => {
panic!(
"The probe is active but didn't expect the message:\n\n\t{:?}.",
actual_msg,
);
}
};
assert_eq!(expected_origin, actual_origin);
assert_eq!(expected_msg, &actual_msg[..]);
mock_weight
})).unwrap_or(0))
},
};
assert_eq!(expected_origin, actual_origin);
assert_eq!(expected_msg, &actual_msg[..]);
mock_weight
})
})
.unwrap_or(0))
}
}
@@ -684,15 +672,11 @@ pub(crate) mod mock_sink {
mock_weight: Weight,
) {
HOOK.with(|opt_hook| {
opt_hook
.borrow_mut()
.as_mut()
.unwrap()
.push_back(UmpExpectation {
expected_origin,
expected_msg,
mock_weight,
})
opt_hook.borrow_mut().as_mut().unwrap().push_back(UmpExpectation {
expected_origin,
expected_msg,
mock_weight,
})
});
}
}
@@ -727,9 +711,8 @@ pub(crate) mod mock_sink {
#[cfg(test)]
mod tests {
use super::*;
use super::mock_sink::Probe;
use crate::mock::{Configuration, Ump, new_test_ext, MockGenesisConfig};
use super::{mock_sink::Probe, *};
use crate::mock::{new_test_ext, Configuration, MockGenesisConfig, Ump};
use std::collections::HashSet;
struct GenesisConfigBuilder {
@@ -761,8 +744,7 @@ mod tests {
config.max_upward_message_num_per_candidate = self.max_upward_message_num_per_candidate;
config.max_upward_queue_count = self.max_upward_queue_count;
config.max_upward_queue_size = self.max_upward_queue_size;
config.ump_service_total_weight =
self.ump_service_total_weight;
config.ump_service_total_weight = self.ump_service_total_weight;
genesis
}
}
@@ -811,9 +793,8 @@ mod tests {
let queue_sizes_set = <Ump as Store>::RelayDispatchQueueSize::iter()
.map(|(k, _)| k)
.collect::<HashSet<ParaId>>();
let needs_dispatch_set = <Ump as Store>::NeedsDispatch::get()
.into_iter()
.collect::<HashSet<ParaId>>();
let needs_dispatch_set =
<Ump as Store>::NeedsDispatch::get().into_iter().collect::<HashSet<ParaId>>();
assert_eq!(queue_contents_set, queue_sizes_set);
assert_eq!(queue_contents_set, needs_dispatch_set);
@@ -823,11 +804,7 @@ mod tests {
}
// `NeedsDispatch` is always sorted.
assert!(
<Ump as Store>::NeedsDispatch::get()
.windows(2)
.all(|xs| xs[0] <= xs[1])
);
assert!(<Ump as Store>::NeedsDispatch::get().windows(2).all(|xs| xs[0] <= xs[1]));
}
#[test]
@@ -872,11 +849,7 @@ mod tests {
let q_msg = b"we are Q".to_vec();
new_test_ext(
GenesisConfigBuilder {
ump_service_total_weight: 500,
..Default::default()
}
.build(),
GenesisConfigBuilder { ump_service_total_weight: 500, ..Default::default() }.build(),
)
.execute_with(|| {
queue_upward_msg(q, q_msg.clone());
@@ -946,11 +919,7 @@ mod tests {
let b_msg_1 = vec![4, 5, 6];
new_test_ext(
GenesisConfigBuilder {
ump_service_total_weight: 900,
..Default::default()
}
.build(),
GenesisConfigBuilder { ump_service_total_weight: 900, ..Default::default() }.build(),
)
.execute_with(|| {
// We want to test here an edge case, where we remove the queue with the highest
@@ -982,8 +951,8 @@ mod tests {
// Make sure that the relay dispatch queue size storage entry is accessible via well known
// keys and is decodable into a (u32, u32).
use primitives::v1::well_known_keys;
use parity_scale_codec::Decode as _;
use primitives::v1::well_known_keys;
let a = ParaId::from(228);
let msg = vec![1, 2, 3];
@@ -991,9 +960,11 @@ mod tests {
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
queue_upward_msg(a, msg);
let raw_queue_size = sp_io::storage::get(&well_known_keys::relay_dispatch_queue_size(a))
.expect("enqueing a message should create the dispatch queue\
and it should be accessible via the well known keys");
let raw_queue_size =
sp_io::storage::get(&well_known_keys::relay_dispatch_queue_size(a)).expect(
"enqueing a message should create the dispatch queue\
and it should be accessible via the well known keys",
);
let (cnt, size) = <(u32, u32)>::decode(&mut &raw_queue_size[..])
.expect("the dispatch queue size should be decodable into (u32, u32)");
+3 -2
View File
@@ -20,7 +20,7 @@
use primitives::v1::{Id as ParaId, PersistedValidationData, ValidatorIndex};
use sp_std::vec::Vec;
use crate::{configuration, paras, hrmp};
use crate::{configuration, hrmp, paras};
/// Make the persisted validation data for a particular parachain, a specified relay-parent and it's
/// storage root.
@@ -43,7 +43,8 @@ pub fn make_persisted_validation_data<T: paras::Config + hrmp::Config>(
/// Take the active subset of a set containing all validators.
pub fn take_active_subset<T: Clone>(active_validators: &[ValidatorIndex], set: &[T]) -> Vec<T> {
let subset: Vec<_> = active_validators.iter()
let subset: Vec<_> = active_validators
.iter()
.filter_map(|i| set.get(i.0 as usize))
.cloned()
.collect();
+12 -10
View File
@@ -19,8 +19,8 @@ pub mod currency {
use primitives::v0::Balance;
pub const UNITS: Balance = 10_000_000_000;
pub const DOLLARS: Balance = UNITS; // 10_000_000_000
pub const CENTS: Balance = DOLLARS / 100; // 100_000_000
pub const DOLLARS: Balance = UNITS; // 10_000_000_000
pub const CENTS: Balance = DOLLARS / 100; // 100_000_000
pub const MILLICENTS: Balance = CENTS / 1_000; // 100_000
pub const fn deposit(items: u32, bytes: u32) -> Balance {
@@ -30,7 +30,7 @@ pub mod currency {
/// Time and blocks.
pub mod time {
use primitives::v0::{Moment, BlockNumber};
use primitives::v0::{BlockNumber, Moment};
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = 4 * HOURS;
@@ -46,13 +46,13 @@ pub mod time {
/// Fee-related.
pub mod fee {
pub use sp_runtime::Perbill;
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use primitives::v0::Balance;
use runtime_common::ExtrinsicBaseWeight;
use frame_support::weights::{
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
};
use smallvec::smallvec;
pub use sp_runtime::Perbill;
/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
@@ -86,10 +86,12 @@ pub mod fee {
#[cfg(test)]
mod tests {
use super::{
currency::{CENTS, DOLLARS, MILLICENTS},
fee::WeightToFee,
};
use frame_support::weights::WeightToFeePolynomial;
use runtime_common::{MAXIMUM_BLOCK_WEIGHT, ExtrinsicBaseWeight};
use super::fee::WeightToFee;
use super::currency::{CENTS, DOLLARS, MILLICENTS};
use runtime_common::{ExtrinsicBaseWeight, MAXIMUM_BLOCK_WEIGHT};
#[test]
// This function tests that the fee for `MAXIMUM_BLOCK_WEIGHT` of weight is correct
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,36 +42,35 @@ use sp_std::marker::PhantomData;
/// Weight functions for `frame_system`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> frame_system::WeightInfo for WeightInfo<T> {
fn remark(_b: u32, ) -> Weight {
fn remark(_b: u32) -> Weight {
(990_000 as Weight)
}
fn remark_with_event(b: u32, ) -> Weight {
fn remark_with_event(b: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(b as Weight))
}
fn set_heap_pages() -> Weight {
(1_353_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(1_353_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_changes_trie_config() -> Weight {
(9_064_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn set_storage(i: u32, ) -> Weight {
fn set_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((546_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_storage(i: u32, ) -> Weight {
fn kill_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((402_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_prefix(p: u32, ) -> Weight {
fn kill_prefix(p: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((790_000 as Weight).saturating_mul(p as Weight))
+3 -3
View File
@@ -17,10 +17,11 @@
pub mod frame_system;
pub mod pallet_balances;
pub mod pallet_bounties;
pub mod pallet_collective;
pub mod pallet_democracy;
pub mod pallet_elections_phragmen;
pub mod pallet_election_provider_multi_phase;
pub mod pallet_elections_phragmen;
pub mod pallet_identity;
pub mod pallet_im_online;
pub mod pallet_indices;
@@ -31,9 +32,8 @@ pub mod pallet_scheduler;
pub mod pallet_session;
pub mod pallet_staking;
pub mod pallet_timestamp;
pub mod pallet_tips;
pub mod pallet_treasury;
pub mod pallet_utility;
pub mod pallet_vesting;
pub mod pallet_bounties;
pub mod pallet_tips;
pub mod runtime_common_claims;
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_bounties`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_bounties::WeightInfo for WeightInfo<T> {
fn propose_bounty(d: u32, ) -> Weight {
fn propose_bounty(d: u32) -> Weight {
(41_618_000 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(d as Weight))
@@ -95,7 +94,7 @@ impl<T: frame_system::Config> pallet_bounties::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn spend_funds(b: u32, ) -> Weight {
fn spend_funds(b: u32) -> Weight {
(0 as Weight)
// Standard Error: 14_000
.saturating_add((58_304_000 as Weight).saturating_mul(b as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_collective`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
fn set_members(m: u32, n: u32, p: u32, ) -> Weight {
fn set_members(m: u32, n: u32, p: u32) -> Weight {
(0 as Weight)
// Standard Error: 4_000
.saturating_add((14_051_000 as Weight).saturating_mul(m as Weight))
@@ -56,7 +55,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight)))
}
fn execute(b: u32, m: u32, ) -> Weight {
fn execute(b: u32, m: u32) -> Weight {
(20_424_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
@@ -64,7 +63,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add((82_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn propose_execute(b: u32, m: u32, ) -> Weight {
fn propose_execute(b: u32, m: u32) -> Weight {
(24_961_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
@@ -72,7 +71,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add((160_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
}
fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight {
fn propose_proposed(b: u32, m: u32, p: u32) -> Weight {
(41_826_000 as Weight)
// Standard Error: 0
.saturating_add((4_000 as Weight).saturating_mul(b as Weight))
@@ -83,14 +82,14 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn vote(m: u32, ) -> Weight {
fn vote(m: u32) -> Weight {
(31_640_000 as Weight)
// Standard Error: 0
.saturating_add((216_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn close_early_disapproved(m: u32, p: u32, ) -> Weight {
fn close_early_disapproved(m: u32, p: u32) -> Weight {
(40_355_000 as Weight)
// Standard Error: 0
.saturating_add((165_000 as Weight).saturating_mul(m as Weight))
@@ -99,7 +98,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight {
fn close_early_approved(b: u32, m: u32, p: u32) -> Weight {
(55_837_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
@@ -110,7 +109,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_disapproved(m: u32, p: u32, ) -> Weight {
fn close_disapproved(m: u32, p: u32) -> Weight {
(44_700_000 as Weight)
// Standard Error: 0
.saturating_add((169_000 as Weight).saturating_mul(m as Weight))
@@ -119,7 +118,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn close_approved(b: u32, m: u32, p: u32, ) -> Weight {
fn close_approved(b: u32, m: u32, p: u32) -> Weight {
(60_051_000 as Weight)
// Standard Error: 0
.saturating_add((3_000 as Weight).saturating_mul(b as Weight))
@@ -130,7 +129,7 @@ impl<T: frame_system::Config> pallet_collective::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn disapprove_proposal(p: u32, ) -> Weight {
fn disapprove_proposal(p: u32) -> Weight {
(24_750_000 as Weight)
// Standard Error: 0
.saturating_add((380_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -48,21 +47,21 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn second(s: u32, ) -> Weight {
fn second(s: u32) -> Weight {
(37_688_000 as Weight)
// Standard Error: 0
.saturating_add((154_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn vote_new(r: u32, ) -> Weight {
fn vote_new(r: u32) -> Weight {
(43_654_000 as Weight)
// Standard Error: 0
.saturating_add((208_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn vote_existing(r: u32, ) -> Weight {
fn vote_existing(r: u32) -> Weight {
(43_543_000 as Weight)
// Standard Error: 0
.saturating_add((207_000 as Weight).saturating_mul(r as Weight))
@@ -74,14 +73,14 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn blacklist(p: u32, ) -> Weight {
fn blacklist(p: u32) -> Weight {
(74_916_000 as Weight)
// Standard Error: 4_000
.saturating_add((536_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
fn external_propose(v: u32, ) -> Weight {
fn external_propose(v: u32) -> Weight {
(12_632_000 as Weight)
// Standard Error: 0
.saturating_add((79_000 as Weight).saturating_mul(v as Weight))
@@ -89,26 +88,24 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn external_propose_majority() -> Weight {
(2_396_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_396_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn external_propose_default() -> Weight {
(2_450_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_450_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn fast_track() -> Weight {
(25_867_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn veto_external(v: u32, ) -> Weight {
fn veto_external(v: u32) -> Weight {
(26_789_000 as Weight)
// Standard Error: 0
.saturating_add((133_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn cancel_proposal(p: u32, ) -> Weight {
fn cancel_proposal(p: u32) -> Weight {
(49_939_000 as Weight)
// Standard Error: 0
.saturating_add((511_000 as Weight).saturating_mul(p as Weight))
@@ -116,24 +113,23 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn cancel_referendum() -> Weight {
(15_902_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(15_902_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel_queued(r: u32, ) -> Weight {
fn cancel_queued(r: u32) -> Weight {
(27_621_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_163_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn on_initialize_base(r: u32, ) -> Weight {
fn on_initialize_base(r: u32) -> Weight {
(7_728_000 as Weight)
// Standard Error: 4_000
.saturating_add((5_099_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight)))
}
fn delegate(r: u32, ) -> Weight {
fn delegate(r: u32) -> Weight {
(53_667_000 as Weight)
// Standard Error: 4_000
.saturating_add((7_194_000 as Weight).saturating_mul(r as Weight))
@@ -142,7 +138,7 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight)))
}
fn undelegate(r: u32, ) -> Weight {
fn undelegate(r: u32) -> Weight {
(23_077_000 as Weight)
// Standard Error: 5_000
.saturating_add((7_164_000 as Weight).saturating_mul(r as Weight))
@@ -152,52 +148,51 @@ impl<T: frame_system::Config> pallet_democracy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight)))
}
fn clear_public_proposals() -> Weight {
(2_195_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_195_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn note_preimage(b: u32, ) -> Weight {
fn note_preimage(b: u32) -> Weight {
(41_252_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn note_imminent_preimage(b: u32, ) -> Weight {
fn note_imminent_preimage(b: u32) -> Weight {
(26_149_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn reap_preimage(b: u32, ) -> Weight {
fn reap_preimage(b: u32) -> Weight {
(36_669_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn unlock_remove(r: u32, ) -> Weight {
fn unlock_remove(r: u32) -> Weight {
(37_226_000 as Weight)
// Standard Error: 0
.saturating_add((53_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn unlock_set(r: u32, ) -> Weight {
fn unlock_set(r: u32) -> Weight {
(34_663_000 as Weight)
// Standard Error: 0
.saturating_add((199_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn remove_vote(r: u32, ) -> Weight {
fn remove_vote(r: u32) -> Weight {
(19_247_000 as Weight)
// Standard Error: 0
.saturating_add((182_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn remove_other_vote(r: u32, ) -> Weight {
fn remove_other_vote(r: u32) -> Weight {
(19_335_000 as Weight)
// Standard Error: 0
.saturating_add((184_000 as Weight).saturating_mul(r as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -44,8 +43,7 @@ use sp_std::marker::PhantomData;
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo for WeightInfo<T> {
fn on_initialize_nothing() -> Weight {
(23_244_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
(23_244_000 as Weight).saturating_add(T::DbWeight::get().reads(8 as Weight))
}
fn on_initialize_open_signed() -> Weight {
(82_453_000 as Weight)
@@ -62,12 +60,12 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32, ) -> Weight {
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32) -> Weight {
(5_408_539_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 15_000
.saturating_add((3_352_000 as Weight).saturating_mul(v as Weight))
@@ -80,7 +78,7 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn feasibility_check(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 10_000
.saturating_add((3_365_000 as Weight).saturating_mul(v as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,21 +42,21 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_elections_phragmen`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightInfo<T> {
fn vote_equal(v: u32, ) -> Weight {
fn vote_equal(v: u32) -> Weight {
(40_509_000 as Weight)
// Standard Error: 3_000
.saturating_add((254_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vote_more(v: u32, ) -> Weight {
fn vote_more(v: u32) -> Weight {
(63_177_000 as Weight)
// Standard Error: 5_000
.saturating_add((246_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vote_less(v: u32, ) -> Weight {
fn vote_less(v: u32) -> Weight {
(62_878_000 as Weight)
// Standard Error: 5_000
.saturating_add((269_000 as Weight).saturating_mul(v as Weight))
@@ -69,14 +68,14 @@ impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn submit_candidacy(c: u32, ) -> Weight {
fn submit_candidacy(c: u32) -> Weight {
(51_250_000 as Weight)
// Standard Error: 0
.saturating_add((272_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn renounce_candidacy_candidate(c: u32, ) -> Weight {
fn renounce_candidacy_candidate(c: u32) -> Weight {
(42_742_000 as Weight)
// Standard Error: 0
.saturating_add((156_000 as Weight).saturating_mul(c as Weight))
@@ -99,10 +98,9 @@ impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
fn remove_member_wrong_refund() -> Weight {
(6_347_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
(6_347_000 as Weight).saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn clean_defunct_voters(v: u32, _d: u32, ) -> Weight {
fn clean_defunct_voters(v: u32, _d: u32) -> Weight {
(0 as Weight)
// Standard Error: 43_000
.saturating_add((107_372_000 as Weight).saturating_mul(v as Weight))
@@ -110,7 +108,7 @@ impl<T: frame_system::Config> pallet_elections_phragmen::WeightInfo for WeightIn
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight)))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight {
fn election_phragmen(c: u32, v: u32, e: u32) -> Weight {
(0 as Weight)
// Standard Error: 2_739_000
.saturating_add((126_782_000 as Weight).saturating_mul(c as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,14 +42,14 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_identity`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
fn add_registrar(r: u32, ) -> Weight {
fn add_registrar(r: u32) -> Weight {
(20_345_000 as Weight)
// Standard Error: 2_000
.saturating_add((233_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_identity(r: u32, x: u32, ) -> Weight {
fn set_identity(r: u32, x: u32) -> Weight {
(50_253_000 as Weight)
// Standard Error: 14_000
.saturating_add((196_000 as Weight).saturating_mul(r as Weight))
@@ -59,7 +58,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_subs_new(s: u32, ) -> Weight {
fn set_subs_new(s: u32) -> Weight {
(39_222_000 as Weight)
// Standard Error: 1_000
.saturating_add((6_369_000 as Weight).saturating_mul(s as Weight))
@@ -68,7 +67,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn set_subs_old(p: u32, ) -> Weight {
fn set_subs_old(p: u32) -> Weight {
(39_661_000 as Weight)
// Standard Error: 0
.saturating_add((2_102_000 as Weight).saturating_mul(p as Weight))
@@ -76,7 +75,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight)))
}
fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight {
fn clear_identity(r: u32, s: u32, x: u32) -> Weight {
(48_967_000 as Weight)
// Standard Error: 7_000
.saturating_add((135_000 as Weight).saturating_mul(r as Weight))
@@ -88,7 +87,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn request_judgement(r: u32, x: u32, ) -> Weight {
fn request_judgement(r: u32, x: u32) -> Weight {
(52_197_000 as Weight)
// Standard Error: 4_000
.saturating_add((218_000 as Weight).saturating_mul(r as Weight))
@@ -97,7 +96,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel_request(r: u32, x: u32, ) -> Weight {
fn cancel_request(r: u32, x: u32) -> Weight {
(48_022_000 as Weight)
// Standard Error: 6_000
.saturating_add((141_000 as Weight).saturating_mul(r as Weight))
@@ -106,28 +105,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fee(r: u32, ) -> Weight {
fn set_fee(r: u32) -> Weight {
(7_590_000 as Weight)
// Standard Error: 1_000
.saturating_add((203_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_account_id(r: u32, ) -> Weight {
fn set_account_id(r: u32) -> Weight {
(8_422_000 as Weight)
// Standard Error: 1_000
.saturating_add((210_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fields(r: u32, ) -> Weight {
fn set_fields(r: u32) -> Weight {
(7_561_000 as Weight)
// Standard Error: 0
.saturating_add((207_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn provide_judgement(r: u32, x: u32, ) -> Weight {
fn provide_judgement(r: u32, x: u32) -> Weight {
(33_330_000 as Weight)
// Standard Error: 4_000
.saturating_add((196_000 as Weight).saturating_mul(r as Weight))
@@ -136,7 +135,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn kill_identity(r: u32, s: u32, x: u32, ) -> Weight {
fn kill_identity(r: u32, s: u32, x: u32) -> Weight {
(61_538_000 as Weight)
// Standard Error: 4_000
.saturating_add((106_000 as Weight).saturating_mul(r as Weight))
@@ -148,28 +147,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn add_sub(s: u32, ) -> Weight {
fn add_sub(s: u32) -> Weight {
(52_704_000 as Weight)
// Standard Error: 0
.saturating_add((156_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn rename_sub(s: u32, ) -> Weight {
fn rename_sub(s: u32) -> Weight {
(16_279_000 as Weight)
// Standard Error: 0
.saturating_add((22_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_sub(s: u32, ) -> Weight {
fn remove_sub(s: u32) -> Weight {
(53_681_000 as Weight)
// Standard Error: 0
.saturating_add((138_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn quit_sub(s: u32, ) -> Weight {
fn quit_sub(s: u32) -> Weight {
(32_963_000 as Weight)
// Standard Error: 0
.saturating_add((136_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_im_online`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_im_online::WeightInfo for WeightInfo<T> {
fn validate_unsigned_and_then_heartbeat(k: u32, e: u32, ) -> Weight {
fn validate_unsigned_and_then_heartbeat(k: u32, e: u32) -> Weight {
(88_006_000 as Weight)
// Standard Error: 0
.saturating_add((157_000 as Weight).saturating_mul(k as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,50 +42,49 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_membership`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_membership::WeightInfo for WeightInfo<T> {
fn add_member(m: u32, ) -> Weight {
fn add_member(m: u32) -> Weight {
(22_415_000 as Weight)
// Standard Error: 3_000
.saturating_add((169_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn remove_member(m: u32, ) -> Weight {
fn remove_member(m: u32) -> Weight {
(27_436_000 as Weight)
// Standard Error: 0
.saturating_add((135_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn swap_member(m: u32, ) -> Weight {
fn swap_member(m: u32) -> Weight {
(27_577_000 as Weight)
// Standard Error: 0
.saturating_add((149_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn reset_member(m: u32, ) -> Weight {
fn reset_member(m: u32) -> Weight {
(28_417_000 as Weight)
// Standard Error: 0
.saturating_add((305_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn change_key(m: u32, ) -> Weight {
fn change_key(m: u32) -> Weight {
(29_217_000 as Weight)
// Standard Error: 0
.saturating_add((145_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn set_prime(m: u32, ) -> Weight {
fn set_prime(m: u32) -> Weight {
(7_017_000 as Weight)
// Standard Error: 0
.saturating_add((80_000 as Weight).saturating_mul(m as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn clear_prime(_m: u32, ) -> Weight {
(2_742_000 as Weight)
.saturating_add(T::DbWeight::get().writes(2 as Weight))
fn clear_prime(_m: u32) -> Weight {
(2_742_000 as Weight).saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,10 +42,10 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_multisig`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
fn as_multi_threshold_1(_z: u32, ) -> Weight {
fn as_multi_threshold_1(_z: u32) -> Weight {
(10_355_000 as Weight)
}
fn as_multi_create(s: u32, z: u32, ) -> Weight {
fn as_multi_create(s: u32, z: u32) -> Weight {
(48_627_000 as Weight)
// Standard Error: 0
.saturating_add((106_000 as Weight).saturating_mul(s as Weight))
@@ -55,7 +54,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn as_multi_create_store(s: u32, z: u32, ) -> Weight {
fn as_multi_create_store(s: u32, z: u32) -> Weight {
(54_885_000 as Weight)
// Standard Error: 0
.saturating_add((108_000 as Weight).saturating_mul(s as Weight))
@@ -64,7 +63,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn as_multi_approve(s: u32, z: u32, ) -> Weight {
fn as_multi_approve(s: u32, z: u32) -> Weight {
(28_368_000 as Weight)
// Standard Error: 0
.saturating_add((103_000 as Weight).saturating_mul(s as Weight))
@@ -73,7 +72,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn as_multi_approve_store(s: u32, z: u32, ) -> Weight {
fn as_multi_approve_store(s: u32, z: u32) -> Weight {
(52_085_000 as Weight)
// Standard Error: 0
.saturating_add((116_000 as Weight).saturating_mul(s as Weight))
@@ -82,7 +81,7 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn as_multi_complete(s: u32, z: u32, ) -> Weight {
fn as_multi_complete(s: u32, z: u32) -> Weight {
(66_094_000 as Weight)
// Standard Error: 0
.saturating_add((206_000 as Weight).saturating_mul(s as Weight))
@@ -91,28 +90,28 @@ impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn approve_as_multi_create(s: u32, ) -> Weight {
fn approve_as_multi_create(s: u32) -> Weight {
(48_354_000 as Weight)
// Standard Error: 0
.saturating_add((105_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn approve_as_multi_approve(s: u32, ) -> Weight {
fn approve_as_multi_approve(s: u32) -> Weight {
(27_780_000 as Weight)
// Standard Error: 0
.saturating_add((103_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn approve_as_multi_complete(s: u32, ) -> Weight {
fn approve_as_multi_complete(s: u32) -> Weight {
(108_496_000 as Weight)
// Standard Error: 0
.saturating_add((211_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn cancel_as_multi(s: u32, ) -> Weight {
fn cancel_as_multi(s: u32) -> Weight {
(81_062_000 as Weight)
// Standard Error: 0
.saturating_add((103_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,13 +42,13 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_proxy`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
fn proxy(p: u32, ) -> Weight {
fn proxy(p: u32) -> Weight {
(21_368_000 as Weight)
// Standard Error: 0
.saturating_add((123_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
}
fn proxy_announced(a: u32, p: u32, ) -> Weight {
fn proxy_announced(a: u32, p: u32) -> Weight {
(51_019_000 as Weight)
// Standard Error: 1_000
.saturating_add((562_000 as Weight).saturating_mul(a as Weight))
@@ -58,21 +57,21 @@ impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn remove_announcement(a: u32, _p: u32, ) -> Weight {
fn remove_announcement(a: u32, _p: u32) -> Weight {
(36_491_000 as Weight)
// Standard Error: 1_000
.saturating_add((556_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn reject_announcement(a: u32, _p: u32, ) -> Weight {
fn reject_announcement(a: u32, _p: u32) -> Weight {
(36_142_000 as Weight)
// Standard Error: 1_000
.saturating_add((564_000 as Weight).saturating_mul(a as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn announce(a: u32, p: u32, ) -> Weight {
fn announce(a: u32, p: u32) -> Weight {
(48_515_000 as Weight)
// Standard Error: 2_000
.saturating_add((562_000 as Weight).saturating_mul(a as Weight))
@@ -81,35 +80,35 @@ impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn add_proxy(p: u32, ) -> Weight {
fn add_proxy(p: u32) -> Weight {
(34_650_000 as Weight)
// Standard Error: 1_000
.saturating_add((212_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_proxy(p: u32, ) -> Weight {
fn remove_proxy(p: u32) -> Weight {
(34_378_000 as Weight)
// Standard Error: 2_000
.saturating_add((240_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_proxies(p: u32, ) -> Weight {
fn remove_proxies(p: u32) -> Weight {
(32_543_000 as Weight)
// Standard Error: 1_000
.saturating_add((134_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn anonymous(p: u32, ) -> Weight {
fn anonymous(p: u32) -> Weight {
(46_410_000 as Weight)
// Standard Error: 1_000
.saturating_add((32_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn kill_anonymous(p: u32, ) -> Weight {
fn kill_anonymous(p: u32) -> Weight {
(34_483_000 as Weight)
// Standard Error: 1_000
.saturating_add((133_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,28 +42,28 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_scheduler`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_scheduler::WeightInfo for WeightInfo<T> {
fn schedule(s: u32, ) -> Weight {
fn schedule(s: u32) -> Weight {
(23_340_000 as Weight)
// Standard Error: 0
.saturating_add((39_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel(s: u32, ) -> Weight {
fn cancel(s: u32) -> Weight {
(22_347_000 as Weight)
// Standard Error: 4_000
.saturating_add((1_864_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn schedule_named(s: u32, ) -> Weight {
fn schedule_named(s: u32) -> Weight {
(29_626_000 as Weight)
// Standard Error: 1_000
.saturating_add((58_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn cancel_named(s: u32, ) -> Weight {
fn cancel_named(s: u32) -> Weight {
(25_024_000 as Weight)
// Standard Error: 4_000
.saturating_add((1_882_000 as Weight).saturating_mul(s as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -58,14 +57,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn withdraw_unbonded_update(s: u32, ) -> Weight {
fn withdraw_unbonded_update(s: u32) -> Weight {
(49_182_000 as Weight)
// Standard Error: 0
.saturating_add((31_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn withdraw_unbonded_kill(s: u32, ) -> Weight {
fn withdraw_unbonded_kill(s: u32) -> Weight {
(81_006_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_333_000 as Weight).saturating_mul(s as Weight))
@@ -78,7 +77,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(6 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn kick(k: u32, ) -> Weight {
fn kick(k: u32) -> Weight {
(10_487_000 as Weight)
// Standard Error: 7_000
.saturating_add((16_334_000 as Weight).saturating_mul(k as Weight))
@@ -86,7 +85,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(k as Weight)))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight)))
}
fn nominate(n: u32, ) -> Weight {
fn nominate(n: u32) -> Weight {
(38_083_000 as Weight)
// Standard Error: 10_000
.saturating_add((5_185_000 as Weight).saturating_mul(n as Weight))
@@ -95,8 +94,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn chill() -> Weight {
(16_783_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
(16_783_000 as Weight).saturating_add(T::DbWeight::get().reads(3 as Weight))
}
fn set_payee() -> Weight {
(11_391_000 as Weight)
@@ -109,28 +107,24 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn set_validator_count() -> Weight {
(1_879_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(1_879_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_no_eras() -> Weight {
(2_139_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_139_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_new_era() -> Weight {
(2_096_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_096_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_new_era_always() -> Weight {
(2_089_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(2_089_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_invulnerables(v: u32, ) -> Weight {
fn set_invulnerables(v: u32) -> Weight {
(2_143_000 as Weight)
// Standard Error: 0
.saturating_add((23_000 as Weight).saturating_mul(v as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn force_unstake(s: u32, ) -> Weight {
fn force_unstake(s: u32) -> Weight {
(58_264_000 as Weight)
// Standard Error: 1_000
.saturating_add((2_309_000 as Weight).saturating_mul(s as Weight))
@@ -138,14 +132,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(6 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn cancel_deferred_slash(s: u32, ) -> Weight {
fn cancel_deferred_slash(s: u32) -> Weight {
(3_444_385_000 as Weight)
// Standard Error: 224_000
.saturating_add((19_743_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn payout_stakers_dead_controller(n: u32, ) -> Weight {
fn payout_stakers_dead_controller(n: u32) -> Weight {
(106_496_000 as Weight)
// Standard Error: 13_000
.saturating_add((46_186_000 as Weight).saturating_mul(n as Weight))
@@ -154,7 +148,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(n as Weight)))
}
fn payout_stakers_alive_staked(n: u32, ) -> Weight {
fn payout_stakers_alive_staked(n: u32) -> Weight {
(131_706_000 as Weight)
// Standard Error: 20_000
.saturating_add((60_519_000 as Weight).saturating_mul(n as Weight))
@@ -163,14 +157,14 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(n as Weight)))
}
fn rebond(l: u32, ) -> Weight {
fn rebond(l: u32) -> Weight {
(46_089_000 as Weight)
// Standard Error: 1_000
.saturating_add((64_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn set_history_depth(e: u32, ) -> Weight {
fn set_history_depth(e: u32) -> Weight {
(0 as Weight)
// Standard Error: 67_000
.saturating_add((32_486_000 as Weight).saturating_mul(e as Weight))
@@ -178,7 +172,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((7 as Weight).saturating_mul(e as Weight)))
}
fn reap_stash(s: u32, ) -> Weight {
fn reap_stash(s: u32) -> Weight {
(69_019_000 as Weight)
// Standard Error: 0
.saturating_add((2_317_000 as Weight).saturating_mul(s as Weight))
@@ -186,7 +180,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(8 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn new_era(v: u32, n: u32, ) -> Weight {
fn new_era(v: u32, n: u32) -> Weight {
(0 as Weight)
// Standard Error: 666_000
.saturating_add((306_698_000 as Weight).saturating_mul(v as Weight))
@@ -198,7 +192,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(4 as Weight))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight)))
}
fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight {
fn get_npos_voters(v: u32, n: u32, s: u32) -> Weight {
(0 as Weight)
// Standard Error: 97_000
.saturating_add((25_109_000 as Weight).saturating_mul(v as Weight))
@@ -211,7 +205,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight)))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
}
fn get_npos_targets(v: u32, ) -> Weight {
fn get_npos_targets(v: u32) -> Weight {
(0 as Weight)
// Standard Error: 31_000
.saturating_add((10_220_000 as Weight).saturating_mul(v as Weight))
@@ -219,8 +213,7 @@ impl<T: frame_system::Config> pallet_staking::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight)))
}
fn set_staking_limits() -> Weight {
(5_584_000 as Weight)
.saturating_add(T::DbWeight::get().writes(5 as Weight))
(5_584_000 as Weight).saturating_add(T::DbWeight::get().writes(5 as Weight))
}
fn chill_other() -> Weight {
(39_524_000 as Weight)
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_tips`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
fn report_awesome(r: u32, ) -> Weight {
fn report_awesome(r: u32) -> Weight {
(46_460_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(r as Weight))
@@ -55,7 +54,7 @@ impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn tip_new(r: u32, t: u32, ) -> Weight {
fn tip_new(r: u32, t: u32) -> Weight {
(27_685_000 as Weight)
// Standard Error: 0
.saturating_add((2_000 as Weight).saturating_mul(r as Weight))
@@ -64,21 +63,21 @@ impl<T: frame_system::Config> pallet_tips::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn tip(t: u32, ) -> Weight {
fn tip(t: u32) -> Weight {
(18_081_000 as Weight)
// Standard Error: 0
.saturating_add((565_000 as Weight).saturating_mul(t as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn close_tip(t: u32, ) -> Weight {
fn close_tip(t: u32) -> Weight {
(77_929_000 as Weight)
// Standard Error: 0
.saturating_add((299_000 as Weight).saturating_mul(t as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn slash_tip(t: u32, ) -> Weight {
fn slash_tip(t: u32) -> Weight {
(22_710_000 as Weight)
// Standard Error: 0
.saturating_add((7_000 as Weight).saturating_mul(t as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -53,14 +52,14 @@ impl<T: frame_system::Config> pallet_treasury::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn approve_proposal(p: u32, ) -> Weight {
fn approve_proposal(p: u32) -> Weight {
(11_245_000 as Weight)
// Standard Error: 0
.saturating_add((32_000 as Weight).saturating_mul(p as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn on_initialize_proposals(p: u32, ) -> Weight {
fn on_initialize_proposals(p: u32) -> Weight {
(40_847_000 as Weight)
// Standard Error: 15_000
.saturating_add((56_748_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,7 +42,7 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_utility`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_utility::WeightInfo for WeightInfo<T> {
fn batch(c: u32, ) -> Weight {
fn batch(c: u32) -> Weight {
(13_489_000 as Weight)
// Standard Error: 0
.saturating_add((605_000 as Weight).saturating_mul(c as Weight))
@@ -51,7 +50,7 @@ impl<T: frame_system::Config> pallet_utility::WeightInfo for WeightInfo<T> {
fn as_derivative() -> Weight {
(3_230_000 as Weight)
}
fn batch_all(c: u32, ) -> Weight {
fn batch_all(c: u32) -> Weight {
(13_266_000 as Weight)
// Standard Error: 0
.saturating_add((1_014_000 as Weight).saturating_mul(c as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,42 +42,42 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_vesting`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_vesting::WeightInfo for WeightInfo<T> {
fn vest_locked(l: u32, ) -> Weight {
fn vest_locked(l: u32) -> Weight {
(41_282_000 as Weight)
// Standard Error: 14_000
.saturating_add((225_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn vest_unlocked(l: u32, ) -> Weight {
fn vest_unlocked(l: u32) -> Weight {
(44_048_000 as Weight)
// Standard Error: 10_000
.saturating_add((192_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vest_other_locked(l: u32, ) -> Weight {
fn vest_other_locked(l: u32) -> Weight {
(40_722_000 as Weight)
// Standard Error: 17_000
.saturating_add((242_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn vest_other_unlocked(l: u32, ) -> Weight {
fn vest_other_unlocked(l: u32) -> Weight {
(43_752_000 as Weight)
// Standard Error: 14_000
.saturating_add((215_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn vested_transfer(l: u32, ) -> Weight {
fn vested_transfer(l: u32) -> Weight {
(97_642_000 as Weight)
// Standard Error: 13_000
.saturating_add((133_000 as Weight).saturating_mul(l as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
fn force_vested_transfer(l: u32, ) -> Weight {
fn force_vested_transfer(l: u32) -> Weight {
(97_119_000 as Weight)
// Standard Error: 13_000
.saturating_add((124_000 as Weight).saturating_mul(l as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/polkadot/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
+75 -42
View File
@@ -23,17 +23,25 @@ use bp_messages::{
target_chain::{ProvedMessages, SourceHeaderChain},
InboundLaneData, LaneId, Message, MessageNonce,
};
use bp_rococo::{EXTRA_STORAGE_PROOF_SIZE, MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, max_extrinsic_size, max_extrinsic_weight};
use bp_runtime::{ROCOCO_CHAIN_ID, WOCOCO_CHAIN_ID, ChainId};
use bridge_runtime_common::messages::{
BridgedChainWithMessages, ChainWithMessages, MessageBridge, MessageTransaction, ThisChainWithMessages,
source as messages_source, target as messages_target,
use bp_rococo::{
max_extrinsic_size, max_extrinsic_weight, EXTRA_STORAGE_PROOF_SIZE,
MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
};
use bp_runtime::{ChainId, ROCOCO_CHAIN_ID, WOCOCO_CHAIN_ID};
use bridge_runtime_common::messages::{
source as messages_source, target as messages_target, BridgedChainWithMessages,
ChainWithMessages, MessageBridge, MessageTransaction, ThisChainWithMessages,
};
use frame_support::{
traits::Get,
weights::{Weight, WeightToFeePolynomial},
RuntimeDebug,
};
use frame_support::{traits::Get, weights::{Weight, WeightToFeePolynomial}, RuntimeDebug};
use sp_std::{convert::TryFrom, marker::PhantomData, ops::RangeInclusive};
/// Maximal number of pending outbound messages.
const MAXIMAL_PENDING_MESSAGES_AT_OUTBOUND_LANE: MessageNonce = bp_rococo::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE;
const MAXIMAL_PENDING_MESSAGES_AT_OUTBOUND_LANE: MessageNonce =
bp_rococo::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE;
/// Maximal weight of single message delivery confirmation transaction on Rococo/Wococo chain.
///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` weight formula
@@ -64,16 +72,20 @@ const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000;
const TX_EXTRA_BYTES: u32 = 130;
/// Rococo chain as it is seen at Rococo.
pub type RococoAtRococo = RococoLikeChain<AtRococoWithWococoMessageBridge, crate::RococoGrandpaInstance>;
pub type RococoAtRococo =
RococoLikeChain<AtRococoWithWococoMessageBridge, crate::RococoGrandpaInstance>;
/// Rococo chain as it is seen at Wococo.
pub type RococoAtWococo = RococoLikeChain<AtWococoWithRococoMessageBridge, crate::RococoGrandpaInstance>;
pub type RococoAtWococo =
RococoLikeChain<AtWococoWithRococoMessageBridge, crate::RococoGrandpaInstance>;
/// Wococo chain as it is seen at Wococo.
pub type WococoAtWococo = RococoLikeChain<AtWococoWithRococoMessageBridge, crate::WococoGrandpaInstance>;
pub type WococoAtWococo =
RococoLikeChain<AtWococoWithRococoMessageBridge, crate::WococoGrandpaInstance>;
/// Wococo chain as it is seen at Rococo.
pub type WococoAtRococo = RococoLikeChain<AtRococoWithWococoMessageBridge, crate::WococoGrandpaInstance>;
pub type WococoAtRococo =
RococoLikeChain<AtRococoWithWococoMessageBridge, crate::WococoGrandpaInstance>;
/// Rococo/Wococo chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
@@ -121,7 +133,9 @@ impl<B, GI> ThisChainWithMessages for RococoLikeChain<B, GI> {
fn transaction_payment(transaction: MessageTransaction<Weight>) -> crate::Balance {
// current fee multiplier is used here
bridge_runtime_common::messages::transaction_payment(
crate::BlockWeights::get().get(frame_support::weights::DispatchClass::Normal).base_extrinsic,
crate::BlockWeights::get()
.get(frame_support::weights::DispatchClass::Normal)
.base_extrinsic,
crate::TransactionByteFee::get(),
pallet_transaction_payment::Pallet::<crate::Runtime>::next_fee_multiplier(),
|weight| crate::constants::fee::WeightToFee::calc(&weight),
@@ -137,7 +151,8 @@ impl<B, GI> BridgedChainWithMessages for RococoLikeChain<B, GI> {
fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive<Weight> {
// we don't want to relay too large messages + keep reserve for future upgrades
let upper_limit = messages_target::maximal_incoming_message_dispatch_weight(max_extrinsic_weight());
let upper_limit =
messages_target::maximal_incoming_message_dispatch_weight(max_extrinsic_weight());
// we're charging for payload bytes in `With(Wococo | Rococo)MessageBridge::transaction_payment` function
//
@@ -175,7 +190,9 @@ impl<B, GI> BridgedChainWithMessages for RococoLikeChain<B, GI> {
fn transaction_payment(transaction: MessageTransaction<Weight>) -> crate::Balance {
// current fee multiplier is used here
bridge_runtime_common::messages::transaction_payment(
crate::BlockWeights::get().get(frame_support::weights::DispatchClass::Normal).base_extrinsic,
crate::BlockWeights::get()
.get(frame_support::weights::DispatchClass::Normal)
.base_extrinsic,
crate::TransactionByteFee::get(),
pallet_transaction_payment::Pallet::<crate::Runtime>::next_fee_multiplier(),
|weight| crate::constants::fee::WeightToFee::calc(&weight),
@@ -233,7 +250,7 @@ pub struct GetDeliveryConfirmationTransactionFee;
impl Get<crate::Balance> for GetDeliveryConfirmationTransactionFee {
fn get() -> crate::Balance {
<RococoAtRococo as ThisChainWithMessages>::transaction_payment(
RococoAtRococo::estimate_delivery_confirmation_transaction()
RococoAtRococo::estimate_delivery_confirmation_transaction(),
)
}
}
@@ -255,24 +272,28 @@ mod at_rococo {
type BridgedChain = WococoAtRococo;
type BridgedMessagesInstance = crate::AtWococoWithRococoMessagesInstance;
fn bridged_balance_to_this_balance(bridged_balance: bp_wococo::Balance) -> bp_rococo::Balance {
fn bridged_balance_to_this_balance(
bridged_balance: bp_wococo::Balance,
) -> bp_rococo::Balance {
bridged_balance
}
}
/// Message payload for Rococo -> Wococo messages as it is seen at the Rococo.
pub type ToWococoMessagePayload = messages_source::FromThisChainMessagePayload<AtRococoWithWococoMessageBridge>;
pub type ToWococoMessagePayload =
messages_source::FromThisChainMessagePayload<AtRococoWithWococoMessageBridge>;
/// Message verifier for Rococo -> Wococo messages at Rococo.
pub type ToWococoMessageVerifier = messages_source::FromThisChainMessageVerifier<AtRococoWithWococoMessageBridge>;
pub type ToWococoMessageVerifier =
messages_source::FromThisChainMessageVerifier<AtRococoWithWococoMessageBridge>;
/// Message payload for Wococo -> Rococo messages as it is seen at Rococo.
pub type FromWococoMessagePayload = messages_target::FromBridgedChainMessagePayload<
AtRococoWithWococoMessageBridge
>;
pub type FromWococoMessagePayload =
messages_target::FromBridgedChainMessagePayload<AtRococoWithWococoMessageBridge>;
/// Encoded Rococo Call as it comes from Wococo.
pub type FromWococoEncodedCall = messages_target::FromBridgedChainEncodedMessageCall<crate::Call>;
pub type FromWococoEncodedCall =
messages_target::FromBridgedChainEncodedMessageCall<crate::Call>;
/// Call-dispatch based message dispatch for Wococo -> Rococo messages.
pub type FromWococoMessageDispatch = messages_target::FromBridgedChainMessageDispatch<
@@ -300,24 +321,28 @@ mod at_wococo {
type BridgedChain = RococoAtWococo;
type BridgedMessagesInstance = crate::AtRococoWithWococoMessagesInstance;
fn bridged_balance_to_this_balance(bridged_balance: bp_rococo::Balance) -> bp_wococo::Balance {
fn bridged_balance_to_this_balance(
bridged_balance: bp_rococo::Balance,
) -> bp_wococo::Balance {
bridged_balance
}
}
/// Message payload for Wococo -> Rococo messages as it is seen at the Wococo.
pub type ToRococoMessagePayload = messages_source::FromThisChainMessagePayload<AtWococoWithRococoMessageBridge>;
pub type ToRococoMessagePayload =
messages_source::FromThisChainMessagePayload<AtWococoWithRococoMessageBridge>;
/// Message verifier for Wococo -> Rococo messages at Wococo.
pub type ToRococoMessageVerifier = messages_source::FromThisChainMessageVerifier<AtWococoWithRococoMessageBridge>;
pub type ToRococoMessageVerifier =
messages_source::FromThisChainMessageVerifier<AtWococoWithRococoMessageBridge>;
/// Message payload for Rococo -> Wococo messages as it is seen at Wococo.
pub type FromRococoMessagePayload = messages_target::FromBridgedChainMessagePayload<
AtWococoWithRococoMessageBridge,
>;
pub type FromRococoMessagePayload =
messages_target::FromBridgedChainMessagePayload<AtWococoWithRococoMessageBridge>;
/// Encoded Wococo Call as it comes from Rococo.
pub type FromRococoEncodedCall = messages_target::FromBridgedChainEncodedMessageCall<crate::Call>;
pub type FromRococoEncodedCall =
messages_target::FromBridgedChainEncodedMessageCall<crate::Call>;
/// Call-dispatch based message dispatch for Rococo -> Wococo messages.
pub type FromRococoMessageDispatch = messages_target::FromBridgedChainMessageDispatch<
@@ -330,9 +355,9 @@ mod at_wococo {
#[cfg(test)]
mod tests {
use super::*;
use bridge_runtime_common::messages;
use parity_scale_codec::Encode;
use super::*;
#[test]
fn ensure_rococo_messages_weights_are_correct() {
@@ -361,15 +386,18 @@ mod tests {
bp_rococo::max_extrinsic_size(),
bp_rococo::max_extrinsic_weight(),
max_incoming_message_proof_size,
messages::target::maximal_incoming_message_dispatch_weight(bp_rococo::max_extrinsic_weight()),
messages::target::maximal_incoming_message_dispatch_weight(
bp_rococo::max_extrinsic_weight(),
),
);
let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint(
bp_rococo::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
bp_rococo::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _,
bp_rococo::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _,
)
.unwrap_or(u32::MAX);
let max_incoming_inbound_lane_data_proof_size =
bp_messages::InboundLaneData::<()>::encoded_size_hint(
bp_rococo::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
bp_rococo::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _,
bp_rococo::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _,
)
.unwrap_or(u32::MAX);
pallet_bridge_messages::ensure_able_to_receive_confirmation::<Weights>(
bp_rococo::max_extrinsic_size(),
bp_rococo::max_extrinsic_weight(),
@@ -392,14 +420,19 @@ mod tests {
frame_system::CheckSpecVersion::new(),
frame_system::CheckTxVersion::new(),
frame_system::CheckGenesis::new(),
frame_system::CheckMortality::from(sp_runtime::generic::Era::mortal(u64::MAX, u64::MAX)),
frame_system::CheckMortality::from(sp_runtime::generic::Era::mortal(
u64::MAX,
u64::MAX,
)),
frame_system::CheckNonce::from(primitives::v1::Nonce::MAX),
frame_system::CheckWeight::new(),
pallet_transaction_payment::ChargeTransactionPayment::from(primitives::v1::Balance::MAX),
pallet_transaction_payment::ChargeTransactionPayment::from(
primitives::v1::Balance::MAX,
),
);
let extra_bytes_in_transaction = crate::Address::default().encoded_size()
+ crate::Signature::default().encoded_size()
+ signed_extra.encoded_size();
let extra_bytes_in_transaction = crate::Address::default().encoded_size() +
crate::Signature::default().encoded_size() +
signed_extra.encoded_size();
assert!(
TX_EXTRA_BYTES as usize >= extra_bytes_in_transaction,
"Hardcoded number of extra bytes in Rococo transaction {} is lower than actual value: {}",
+10 -8
View File
@@ -30,7 +30,7 @@ pub mod currency {
/// Time and blocks.
pub mod time {
use primitives::v0::{Moment, BlockNumber};
use primitives::v0::{BlockNumber, Moment};
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
frame_support::parameter_types! {
@@ -48,13 +48,13 @@ pub mod time {
/// Fee-related.
pub mod fee {
pub use sp_runtime::Perbill;
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use primitives::v0::Balance;
use runtime_common::ExtrinsicBaseWeight;
use frame_support::weights::{
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
};
use smallvec::smallvec;
pub use sp_runtime::Perbill;
/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
@@ -88,10 +88,12 @@ pub mod fee {
#[cfg(test)]
mod tests {
use frame_support::weights::{WeightToFeePolynomial, DispatchClass};
use super::{
currency::{CENTS, DOLLARS, MILLICENTS},
fee::WeightToFee,
};
use frame_support::weights::{DispatchClass, WeightToFeePolynomial};
use runtime_common::BlockWeights;
use super::fee::WeightToFee;
use super::currency::{CENTS, DOLLARS, MILLICENTS};
#[test]
// This function tests that the fee for `MaximumBlockWeight` of weight is correct
+141 -130
View File
@@ -20,87 +20,78 @@
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
use pallet_transaction_payment::CurrencyAdapter;
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use parity_scale_codec::{Encode, Decode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment,
GroupRotationInfo, CoreState, Id, ValidationCode, ValidationCodeHash, CandidateEvent,
ValidatorId, ValidatorIndex, CommittedCandidateReceipt, OccupiedCoreAssumption,
PersistedValidationData, InboundDownwardMessage, InboundHrmpMessage,
SessionInfo as SessionInfoData,
};
use runtime_common::{
SlowAdjustingFeeUpdate, impls::ToAuthor, BlockHashCount, BlockWeights, BlockLength, RocksDbWeight,
};
use runtime_parachains::{
self,
runtime_api_impl::v1 as runtime_api_impl,
};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::{crypto::AuthorityId as BeefyId, mmr::MmrLeafVersion};
use frame_support::{
PalletId, construct_runtime, parameter_types,
construct_runtime, parameter_types,
traits::{All, Filter, IsInVec, KeyOwnerProofSystem, OnRuntimeUpgrade, Randomness},
weights::Weight,
PalletId,
};
use frame_system::EnsureRoot;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment,
Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo as SessionInfoData,
Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
};
use runtime_common::{
auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper, slots, xcm_sender,
BlockHashCount, BlockLength, BlockWeights, RocksDbWeight, SlowAdjustingFeeUpdate,
};
use runtime_parachains::{self, runtime_api_impl::v1 as runtime_api_impl};
use sp_core::{OpaqueMetadata, RuntimeDebug};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
ApplyExtrinsicResult, KeyTypeId, Perbill,
transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
traits::{
self, Keccak256, BlakeTwo256, Block as BlockT, OpaqueKeys, AccountIdLookup,
Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
self, AccountIdLookup, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT, Keccak256,
OpaqueKeys, SaturatedConversion, Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, KeyTypeId, Perbill,
};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use sp_staking::SessionIndex;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
use sp_core::{OpaqueMetadata, RuntimeDebug};
use sp_staking::SessionIndex;
use pallet_session::historical as session_historical;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use beefy_primitives::mmr::MmrLeafVersion;
use pallet_mmr_primitives as mmr;
use frame_system::EnsureRoot;
use runtime_common::{paras_sudo_wrapper, paras_registrar, xcm_sender, auctions, crowdloan, slots};
use runtime_parachains::origin as parachains_origin;
use runtime_parachains::configuration as parachains_configuration;
use runtime_parachains::shared as parachains_shared;
use runtime_parachains::inclusion as parachains_inclusion;
use runtime_parachains::paras_inherent as parachains_paras_inherent;
use runtime_parachains::initializer as parachains_initializer;
use runtime_parachains::session_info as parachains_session_info;
use runtime_parachains::paras as parachains_paras;
use runtime_parachains::dmp as parachains_dmp;
use runtime_parachains::ump as parachains_ump;
use runtime_parachains::hrmp as parachains_hrmp;
use runtime_parachains::scheduler as parachains_scheduler;
use runtime_parachains::{
configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp,
inclusion as parachains_inclusion, initializer as parachains_initializer,
origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, scheduler as parachains_scheduler,
session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
};
use bridge_runtime_common::messages::{MessageBridge, source::estimate_message_dispatch_and_delivery_fee};
use bridge_runtime_common::messages::{
source::estimate_message_dispatch_and_delivery_fee, MessageBridge,
};
pub use pallet_balances::Call as BalancesCall;
use polkadot_parachain::primitives::Id as ParaId;
use xcm::v0::{Xcm, MultiLocation, NetworkId, BodyId};
use xcm_executor::XcmExecutor;
use xcm_builder::{
AccountId32Aliases, ChildParachainConvertsVia, SovereignSignedViaLocation,
CurrencyAdapter as XcmCurrencyAdapter, ChildParachainAsNative, SignedAccountId32AsNative,
ChildSystemParachainAsSuperuser, LocationInverter, IsConcrete, FixedWeightBounds,
BackingToPlurality, SignedToAccountId32, UsingComponents,
};
use constants::{time::*, currency::*, fee::*};
use constants::{currency::*, fee::*, time::*};
use frame_support::traits::InstanceFilter;
use xcm::v0::{BodyId, MultiLocation, NetworkId, Xcm};
use xcm_builder::{
AccountId32Aliases, BackingToPlurality, ChildParachainAsNative, ChildParachainConvertsVia,
ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds,
IsConcrete, LocationInverter, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, UsingComponents,
};
use xcm_executor::XcmExecutor;
mod bridge_messages;
/// Constant values used within the runtime.
pub mod constants;
mod bridge_messages;
mod validator_manager;
// Make the WASM binary available.
@@ -125,16 +116,13 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
babe_primitives::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
/// The address format for describing accounts.
@@ -163,9 +151,9 @@ pub struct MigratePalletVersionToStorageVersion;
impl OnRuntimeUpgrade for MigratePalletVersionToStorageVersion {
fn on_runtime_upgrade() -> frame_support::weights::Weight {
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<AllPalletsWithSystem>(
&RocksDbWeight::get()
)
frame_support::migrations::migrate_from_pallet_version_to_storage_version::<
AllPalletsWithSystem,
>(&RocksDbWeight::get())
}
}
@@ -323,7 +311,8 @@ parameter_types! {
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
@@ -334,10 +323,8 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
use sp_runtime::traits::StaticLookup;
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
@@ -349,17 +336,20 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
);
let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
}).ok()?;
let signature = raw_payload.using_encoded(|payload| {
C::sign(payload, public)
})?;
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
Some((call, (address, signature, extra)))
@@ -374,7 +364,9 @@ impl frame_system::offchain::SigningTypes for Runtime {
/// Special `FullIdentificationOf` implementation that is returning for every input `Some(Default::default())`.
pub struct FullIdentificationOf;
impl sp_runtime::traits::Convert<AccountId, Option<()>> for FullIdentificationOf {
fn convert(_: AccountId) -> Option<()> { Some(Default::default()) }
fn convert(_: AccountId) -> Option<()> {
Some(Default::default())
}
}
impl pallet_session::historical::Config for Runtime {
@@ -418,7 +410,8 @@ impl pallet_balances::Config for Runtime {
type WeightInfo = ();
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type OverarchingCall = Call;
@@ -466,7 +459,9 @@ parameter_types! {
/// Special `ValidatorIdOf` implementation that is just returning the input as result.
pub struct ValidatorIdOf;
impl sp_runtime::traits::Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
fn convert(a: AccountId) -> Option<AccountId> { Some(a) }
fn convert(a: AccountId) -> Option<AccountId> {
Some(a)
}
}
impl pallet_session::Config for Runtime {
@@ -542,8 +537,11 @@ impl pallet_grandpa::Config for Runtime {
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation =
pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
type HandleEquivocation = pallet_grandpa::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ReportLongevity,
>;
type WeightInfo = ();
}
@@ -568,8 +566,8 @@ impl parachains_shared::Config for Runtime {}
/// Special `RewardValidators` that does nothing ;)
pub struct RewardValidators;
impl runtime_parachains::inclusion::RewardValidators for RewardValidators {
fn reward_backing(_: impl IntoIterator<Item=ValidatorIndex>) {}
fn reward_bitfields(_: impl IntoIterator<Item=ValidatorIndex>) {}
fn reward_backing(_: impl IntoIterator<Item = ValidatorIndex>) {}
fn reward_bitfields(_: impl IntoIterator<Item = ValidatorIndex>) {}
}
impl parachains_inclusion::Config for Runtime {
@@ -590,24 +588,21 @@ parameter_types! {
pub CheckAccount: AccountId = XcmPallet::check_account();
}
pub type SovereignAccountOf = (
ChildParachainConvertsVia<ParaId, AccountId>,
AccountId32Aliases<RococoNetwork, AccountId>,
);
pub type SovereignAccountOf =
(ChildParachainConvertsVia<ParaId, AccountId>, AccountId32Aliases<RococoNetwork, AccountId>);
pub type LocalAssetTransactor =
XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RocLocation>,
// We can convert the MultiLocations with our converter above:
SovereignAccountOf,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// It's a native asset so we keep track of the teleports to maintain total issuance.
CheckAccount,
>;
pub type LocalAssetTransactor = XcmCurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RocLocation>,
// We can convert the MultiLocations with our converter above:
SovereignAccountOf,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// It's a native asset so we keep track of the teleports to maintain total issuance.
CheckAccount,
>;
type LocalOriginConverter = (
SovereignSignedViaLocation<SovereignAccountOf, Origin>,
@@ -627,7 +622,12 @@ pub type XcmRouter = (
xcm_sender::ChildParachainRouter<Runtime>,
);
use xcm::v0::{MultiAsset, MultiAsset::AllConcreteFungible, MultiLocation::{Null, X1}, Junction::Parachain};
use xcm::v0::{
Junction::Parachain,
MultiAsset,
MultiAsset::AllConcreteFungible,
MultiLocation::{Null, X1},
};
parameter_types! {
pub const RococoForTick: (MultiAsset, MultiLocation) =
(AllConcreteFungible { id: Null }, X1(Parachain(100)));
@@ -655,11 +655,11 @@ parameter_types! {
];
}
use xcm_builder::{TakeWeightCredit, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom};
use xcm_builder::{AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, TakeWeightCredit};
pub type Barrier = (
TakeWeightCredit,
AllowTopLevelPaidExecutionFrom<All<MultiLocation>>,
AllowUnpaidExecutionFrom<IsInVec<AllowUnpaidFrom>>, // <- Trusted parachains get free execution
AllowUnpaidExecutionFrom<IsInVec<AllowUnpaidFrom>>, // <- Trusted parachains get free execution
);
pub struct XcmConfig;
@@ -692,11 +692,15 @@ pub type LocalOriginToLocation = (
);
pub struct OnlyWithdrawTeleportForAccounts;
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdrawTeleportForAccounts {
impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)>
for OnlyWithdrawTeleportForAccounts
{
fn contains((ref origin, ref msg): &(MultiLocation, Xcm<Call>)) -> bool {
use xcm::v0::{
Xcm::WithdrawAsset, Order::{BuyExecution, InitiateTeleport, DepositAsset},
MultiAsset::{All, ConcreteFungible}, Junction::{AccountId32, Plurality},
Junction::{AccountId32, Plurality},
MultiAsset::{All, ConcreteFungible},
Order::{BuyExecution, DepositAsset, InitiateTeleport},
Xcm::WithdrawAsset,
};
match origin {
// Root and collective are allowed to execute anything.
@@ -731,7 +735,7 @@ impl frame_support::traits::Contains<(MultiLocation, Xcm<Call>)> for OnlyWithdra
)
)
)
}
},
// Nobody else is allowed to execute anything.
_ => false,
}
@@ -821,9 +825,7 @@ impl pallet_beefy_mmr::ParachainHeadsProvider for ParasProvider {
fn parachain_heads() -> Vec<(u32, Vec<u8>)> {
Paras::parachains()
.into_iter()
.filter_map(|id| {
Paras::para_head(&id).map(|head| (id.into(), head.0))
})
.filter_map(|id| Paras::para_head(&id).map(|head| (id.into(), head.0)))
.collect()
}
}
@@ -942,12 +944,13 @@ impl pallet_bridge_messages::Config<AtWococoWithRococoMessagesInstance> for Runt
type TargetHeaderChain = crate::bridge_messages::RococoAtWococo;
type LaneMessageVerifier = crate::bridge_messages::ToRococoMessageVerifier;
type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
crate::bridge_messages::GetDeliveryConfirmationTransactionFee,
RootAccountForPayments,
>;
type MessageDeliveryAndDispatchPayment =
pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
crate::bridge_messages::GetDeliveryConfirmationTransactionFee,
RootAccountForPayments,
>;
type OnDeliveryConfirmed = ();
type SourceHeaderChain = crate::bridge_messages::RococoAtWococo;
@@ -976,12 +979,13 @@ impl pallet_bridge_messages::Config<AtRococoWithWococoMessagesInstance> for Runt
type TargetHeaderChain = crate::bridge_messages::WococoAtRococo;
type LaneMessageVerifier = crate::bridge_messages::ToWococoMessageVerifier;
type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
crate::bridge_messages::GetDeliveryConfirmationTransactionFee,
RootAccountForPayments,
>;
type MessageDeliveryAndDispatchPayment =
pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
crate::bridge_messages::GetDeliveryConfirmationTransactionFee,
RootAccountForPayments,
>;
type OnDeliveryConfirmed = ();
type SourceHeaderChain = crate::bridge_messages::WococoAtRococo;
@@ -991,7 +995,9 @@ impl pallet_bridge_messages::Config<AtRococoWithWococoMessagesInstance> for Runt
impl Randomness<Hash, BlockNumber> for ParentHashRandomness {
fn random(subject: &[u8]) -> (Hash, BlockNumber) {
(
(System::parent_hash(), subject).using_encoded(sp_io::hashing::blake2_256).into(),
(System::parent_hash(), subject)
.using_encoded(sp_io::hashing::blake2_256)
.into(),
System::block_number(),
)
}
@@ -1074,19 +1080,24 @@ parameter_types! {
}
/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen)]
#[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen,
)]
pub enum ProxyType {
Any,
CancelProxy,
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<Call> for ProxyType {
fn filter(&self, c: &Call) -> bool {
match self {
ProxyType::Any => true,
ProxyType::CancelProxy => matches!(c,
Call::Proxy(pallet_proxy::Call::reject_announcement(..))
)
ProxyType::CancelProxy =>
matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))),
}
}
fn is_superset(&self, o: &Self) -> bool {
@@ -16,10 +16,7 @@
//! A pallet for managing validators on Rococo.
use frame_support::{
decl_event, decl_error, decl_module, decl_storage,
traits::EnsureOrigin,
};
use frame_support::{decl_error, decl_event, decl_module, decl_storage, traits::EnsureOrigin};
use sp_staking::SessionIndex;
use sp_std::vec::Vec;
@@ -99,7 +96,7 @@ impl<T: Config> Module<T> {}
impl<T: Config> pallet_session::SessionManager<T::ValidatorId> for Module<T> {
fn new_session(new_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {
if new_index <= 1 {
return None;
return None
}
let mut validators = Session::<T>::validators();
@@ -125,9 +122,7 @@ impl<T: Config> pallet_session::SessionManager<T::ValidatorId> for Module<T> {
}
impl<T: Config> pallet_session::historical::SessionManager<T::ValidatorId, ()> for Module<T> {
fn new_session(
new_index: SessionIndex,
) -> Option<Vec<(T::ValidatorId, ())>> {
fn new_session(new_index: SessionIndex) -> Option<Vec<(T::ValidatorId, ())>> {
<Self as pallet_session::SessionManager<_>>::new_session(new_index)
.map(|r| r.into_iter().map(|v| (v, Default::default())).collect())
}
@@ -26,7 +26,7 @@ pub mod currency {
/// Time and blocks.
pub mod time {
use primitives::v0::{Moment, BlockNumber};
use primitives::v0::{BlockNumber, Moment};
// Testnet
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
@@ -44,13 +44,13 @@ pub mod time {
/// Fee-related.
pub mod fee {
pub use sp_runtime::Perbill;
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use primitives::v0::Balance;
use runtime_common::ExtrinsicBaseWeight;
use frame_support::weights::{
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
};
use smallvec::smallvec;
pub use sp_runtime::Perbill;
/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
+65 -65
View File
@@ -21,70 +21,65 @@
#![recursion_limit = "256"]
use pallet_transaction_payment::CurrencyAdapter;
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use parity_scale_codec::Encode;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
use polkadot_runtime_parachains::configuration as parachains_configuration;
use polkadot_runtime_parachains::shared as parachains_shared;
use polkadot_runtime_parachains::inclusion as parachains_inclusion;
use polkadot_runtime_parachains::paras_inherent as parachains_paras_inherent;
use polkadot_runtime_parachains::initializer as parachains_initializer;
use polkadot_runtime_parachains::session_info as parachains_session_info;
use polkadot_runtime_parachains::paras as parachains_paras;
use polkadot_runtime_parachains::dmp as parachains_dmp;
use polkadot_runtime_parachains::ump as parachains_ump;
use polkadot_runtime_parachains::hrmp as parachains_hrmp;
use polkadot_runtime_parachains::scheduler as parachains_scheduler;
use polkadot_runtime_parachains::disputes as parachains_disputes;
use polkadot_runtime_parachains::runtime_api_impl::v1 as runtime_impl;
use polkadot_runtime_parachains::{
configuration as parachains_configuration, disputes as parachains_disputes,
dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion,
initializer as parachains_initializer, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, runtime_api_impl::v1 as runtime_impl,
scheduler as parachains_scheduler, session_info as parachains_session_info,
shared as parachains_shared, ump as parachains_ump,
};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{construct_runtime, parameter_types, traits::KeyOwnerProofSystem};
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use polkadot_runtime_parachains::reward_points::RewardValidatorsWithEraPoints;
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
InboundDownwardMessage, InboundHrmpMessage, SessionInfo as SessionInfoData,
CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData,
SessionInfo as SessionInfoData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
};
use runtime_common::{
claims, SlowAdjustingFeeUpdate, paras_sudo_wrapper,
BlockHashCount, BlockWeights, BlockLength,
claims, paras_sudo_wrapper, BlockHashCount, BlockLength, BlockWeights, SlowAdjustingFeeUpdate,
};
use sp_core::OpaqueMetadata;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
ApplyExtrinsicResult, Perbill, KeyTypeId,
transaction_validity::{TransactionValidity, TransactionSource},
create_runtime_str,
curve::PiecewiseLinear,
generic, impl_opaque_keys,
traits::{
BlakeTwo256, Block as BlockT, StaticLookup, OpaqueKeys, ConvertInto,
Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT, OpaqueKeys,
SaturatedConversion, StaticLookup, Verify,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, KeyTypeId, Perbill,
};
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
use sp_staking::SessionIndex;
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
use frame_support::{parameter_types, construct_runtime, traits::KeyOwnerProofSystem};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use pallet_session::historical as session_historical;
use polkadot_runtime_parachains::reward_points::RewardValidatorsWithEraPoints;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use pallet_mmr_primitives as mmr;
use sp_version::RuntimeVersion;
pub use pallet_balances::Call as BalancesCall;
#[cfg(feature = "std")]
pub use pallet_staking::StakerStatus;
pub use pallet_sudo::Call as SudoCall;
pub use pallet_timestamp::Call as TimestampCall;
pub use paras_sudo_wrapper::Call as ParasSudoWrapperCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use paras_sudo_wrapper::Call as ParasSudoWrapperCall;
pub use pallet_sudo::Call as SudoCall;
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};
use constants::{currency::*, fee::*, time::*};
// Make the WASM binary available.
#[cfg(feature = "std")]
@@ -105,16 +100,13 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
babe_primitives::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
sp_api::decl_runtime_apis! {
@@ -155,7 +147,8 @@ impl frame_system::Config for Runtime {
type OnSetCode = ();
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type OverarchingCall = Call;
@@ -339,7 +332,8 @@ impl pallet_staking::Config for Runtime {
type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
type NextNewSession = Session;
type ElectionProvider = frame_election_provider_support::onchain::OnChainSequentialPhragmen<Self>;
type ElectionProvider =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<Self>;
type GenesisElectionProvider =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<Self>;
type WeightInfo = ();
@@ -364,7 +358,8 @@ impl pallet_grandpa::Config for Runtime {
type WeightInfo = ();
}
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
@@ -373,30 +368,29 @@ impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for R
account: AccountId,
nonce: <Runtime as frame_system::Config>::Index,
) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
.saturating_sub(1);
let current_block = System::block_number().saturated_into::<u64>().saturating_sub(1);
let tip = 0;
let extra: SignedExtra = (
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
);
let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
}).ok()?;
let signature = raw_payload.using_encoded(|payload| {
C::sign(payload, public)
})?;
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let (call, extra, _) = raw_payload.deconstruct();
let address = Indices::unlookup(account);
Some((call, (address, signature, extra)))
@@ -571,12 +565,18 @@ pub type SignedExtra = (
frame_system::CheckMortality<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllPallets>;
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPallets,
>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
+10 -8
View File
@@ -30,7 +30,7 @@ pub mod currency {
/// Time and blocks.
pub mod time {
use primitives::v0::{Moment, BlockNumber};
use primitives::v0::{BlockNumber, Moment};
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = 1 * HOURS;
@@ -46,13 +46,13 @@ pub mod time {
/// Fee-related.
pub mod fee {
pub use sp_runtime::Perbill;
use frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
};
use primitives::v0::Balance;
use runtime_common::ExtrinsicBaseWeight;
use frame_support::weights::{
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
};
use smallvec::smallvec;
pub use sp_runtime::Perbill;
/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
@@ -86,10 +86,12 @@ pub mod fee {
#[cfg(test)]
mod tests {
use super::{
currency::{CENTS, MILLICENTS},
fee::WeightToFee,
};
use frame_support::weights::WeightToFeePolynomial;
use runtime_common::{MAXIMUM_BLOCK_WEIGHT, ExtrinsicBaseWeight};
use super::fee::WeightToFee;
use super::currency::{CENTS, MILLICENTS};
use runtime_common::{ExtrinsicBaseWeight, MAXIMUM_BLOCK_WEIGHT};
#[test]
// This function tests that the fee for `MAXIMUM_BLOCK_WEIGHT` of weight is correct
+4 -2
View File
@@ -34,6 +34,8 @@ fn sample_size_is_sensible() {
let max_weight: Weight = RocksDbWeight::get().reads_writes(samples.into(), samples.into());
// Max sample cleanup should be no more than half the total block weight.
assert!(max_weight * 2 < BlockWeights::get().max_block);
assert!(<Runtime as auctions::Config>::WeightInfo::on_initialize() * 2 < BlockWeights::get().max_block);
assert!(
<Runtime as auctions::Config>::WeightInfo::on_initialize() * 2 <
BlockWeights::get().max_block
);
}
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/westend/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,36 +42,35 @@ use sp_std::marker::PhantomData;
/// Weight functions for `frame_system`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> frame_system::WeightInfo for WeightInfo<T> {
fn remark(_b: u32, ) -> Weight {
fn remark(_b: u32) -> Weight {
(1_238_000 as Weight)
}
fn remark_with_event(b: u32, ) -> Weight {
fn remark_with_event(b: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((1_000 as Weight).saturating_mul(b as Weight))
}
fn set_heap_pages() -> Weight {
(1_689_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(1_689_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_changes_trie_config() -> Weight {
(9_679_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn set_storage(i: u32, ) -> Weight {
fn set_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((532_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_storage(i: u32, ) -> Weight {
fn kill_storage(i: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((380_000 as Weight).saturating_mul(i as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight)))
}
fn kill_prefix(p: u32, ) -> Weight {
fn kill_prefix(p: u32) -> Weight {
(0 as Weight)
// Standard Error: 0
.saturating_add((789_000 as Weight).saturating_mul(p as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/westend/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/westend/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -44,8 +43,7 @@ use sp_std::marker::PhantomData;
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo for WeightInfo<T> {
fn on_initialize_nothing() -> Weight {
(23_792_000 as Weight)
.saturating_add(T::DbWeight::get().reads(8 as Weight))
(23_792_000 as Weight).saturating_add(T::DbWeight::get().reads(8 as Weight))
}
fn on_initialize_open_signed() -> Weight {
(86_272_000 as Weight)
@@ -62,12 +60,12 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32, ) -> Weight {
fn elect_queued(_v: u32, _t: u32, _a: u32, _d: u32) -> Weight {
(5_511_380_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn submit_unsigned(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 12_000
.saturating_add((3_399_000 as Weight).saturating_mul(v as Weight))
@@ -80,7 +78,7 @@ impl<T: frame_system::Config> pallet_election_provider_multi_phase::WeightInfo f
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight {
fn feasibility_check(v: u32, t: u32, a: u32, d: u32) -> Weight {
(0 as Weight)
// Standard Error: 7_000
.saturating_add((3_426_000 as Weight).saturating_mul(v as Weight))
@@ -33,7 +33,6 @@
// --header=./file_header.txt
// --output=./runtime/westend/src/weights/
#![allow(unused_parens)]
#![allow(unused_imports)]
@@ -43,14 +42,14 @@ use sp_std::marker::PhantomData;
/// Weight functions for `pallet_identity`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
fn add_registrar(r: u32, ) -> Weight {
fn add_registrar(r: u32) -> Weight {
(20_852_000 as Weight)
// Standard Error: 2_000
.saturating_add((249_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_identity(r: u32, x: u32, ) -> Weight {
fn set_identity(r: u32, x: u32) -> Weight {
(50_867_000 as Weight)
// Standard Error: 14_000
.saturating_add((216_000 as Weight).saturating_mul(r as Weight))
@@ -59,7 +58,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_subs_new(s: u32, ) -> Weight {
fn set_subs_new(s: u32) -> Weight {
(39_701_000 as Weight)
// Standard Error: 1_000
.saturating_add((6_376_000 as Weight).saturating_mul(s as Weight))
@@ -68,7 +67,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn set_subs_old(p: u32, ) -> Weight {
fn set_subs_old(p: u32) -> Weight {
(40_181_000 as Weight)
// Standard Error: 0
.saturating_add((2_045_000 as Weight).saturating_mul(p as Weight))
@@ -76,7 +75,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight)))
}
fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight {
fn clear_identity(r: u32, s: u32, x: u32) -> Weight {
(48_884_000 as Weight)
// Standard Error: 6_000
.saturating_add((140_000 as Weight).saturating_mul(r as Weight))
@@ -88,7 +87,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn request_judgement(r: u32, x: u32, ) -> Weight {
fn request_judgement(r: u32, x: u32) -> Weight {
(52_661_000 as Weight)
// Standard Error: 5_000
.saturating_add((250_000 as Weight).saturating_mul(r as Weight))
@@ -97,7 +96,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn cancel_request(r: u32, x: u32, ) -> Weight {
fn cancel_request(r: u32, x: u32) -> Weight {
(48_072_000 as Weight)
// Standard Error: 7_000
.saturating_add((173_000 as Weight).saturating_mul(r as Weight))
@@ -106,28 +105,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fee(r: u32, ) -> Weight {
fn set_fee(r: u32) -> Weight {
(7_817_000 as Weight)
// Standard Error: 1_000
.saturating_add((220_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_account_id(r: u32, ) -> Weight {
fn set_account_id(r: u32) -> Weight {
(8_397_000 as Weight)
// Standard Error: 1_000
.saturating_add((223_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_fields(r: u32, ) -> Weight {
fn set_fields(r: u32) -> Weight {
(7_854_000 as Weight)
// Standard Error: 1_000
.saturating_add((216_000 as Weight).saturating_mul(r as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn provide_judgement(r: u32, x: u32, ) -> Weight {
fn provide_judgement(r: u32, x: u32) -> Weight {
(33_563_000 as Weight)
// Standard Error: 5_000
.saturating_add((232_000 as Weight).saturating_mul(r as Weight))
@@ -136,7 +135,7 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn kill_identity(r: u32, s: u32, _x: u32, ) -> Weight {
fn kill_identity(r: u32, s: u32, _x: u32) -> Weight {
(49_152_000 as Weight)
// Standard Error: 3_000
.saturating_add((72_000 as Weight).saturating_mul(r as Weight))
@@ -146,28 +145,28 @@ impl<T: frame_system::Config> pallet_identity::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().writes(3 as Weight))
.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
}
fn add_sub(s: u32, ) -> Weight {
fn add_sub(s: u32) -> Weight {
(53_373_000 as Weight)
// Standard Error: 0
.saturating_add((162_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn rename_sub(s: u32, ) -> Weight {
fn rename_sub(s: u32) -> Weight {
(16_191_000 as Weight)
// Standard Error: 0
.saturating_add((19_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn remove_sub(s: u32, ) -> Weight {
fn remove_sub(s: u32) -> Weight {
(54_328_000 as Weight)
// Standard Error: 0
.saturating_add((143_000 as Weight).saturating_mul(s as Weight))
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn quit_sub(s: u32, ) -> Weight {
fn quit_sub(s: u32) -> Weight {
(32_901_000 as Weight)
// Standard Error: 0
.saturating_add((145_000 as Weight).saturating_mul(s as Weight))

Some files were not shown because too many files have changed in this diff Show More