Update to latest Substrate master (#703)

* Update to latest Substrate master

* Fix tests
This commit is contained in:
Bastian Köcher
2019-12-19 21:51:44 +01:00
committed by GitHub
parent f0c66f9b99
commit 96f24d4fe7
8 changed files with 218 additions and 225 deletions
+153 -170
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -21,7 +21,7 @@
use rstd::prelude::*; use rstd::prelude::*;
use codec::{Encode, Decode}; use codec::{Encode, Decode};
use frame_support::{decl_storage, decl_module, ensure, dispatch::Result, traits::Get}; use frame_support::{decl_storage, decl_module, ensure, dispatch::DispatchResult, traits::Get};
use primitives::{Hash, parachain::{AttestedCandidate, CandidateReceipt, Id as ParaId}}; use primitives::{Hash, parachain::{AttestedCandidate, CandidateReceipt, Id as ParaId}};
use sp_runtime::RuntimeDebug; use sp_runtime::RuntimeDebug;
@@ -110,7 +110,7 @@ decl_module! {
/// Parachain-attestations module. /// Parachain-attestations module.
pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin { pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
/// Provide candidate receipts for parachains, in ascending order by id. /// Provide candidate receipts for parachains, in ascending order by id.
fn more_attestations(origin, _more: MoreAttestations) -> Result { fn more_attestations(origin, _more: MoreAttestations) -> DispatchResult {
ensure_none(origin)?; ensure_none(origin)?;
ensure!(!<DidUpdate>::exists(), "More attestations can be added only once in a block."); ensure!(!<DidUpdate>::exists(), "More attestations can be added only once in a block.");
<DidUpdate>::put(true); <DidUpdate>::put(true);
+4 -3
View File
@@ -305,6 +305,7 @@ mod tests {
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type Version = (); type Version = ();
type ModuleToIndex = ();
} }
parameter_types! { parameter_types! {
@@ -407,7 +408,7 @@ mod tests {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_noop!( assert_noop!(
Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, None), Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, None),
"RequireRootOrigin" sp_runtime::traits::BadOrigin,
); );
assert_eq!(Balances::free_balance(&42), 0); assert_eq!(Balances::free_balance(&42), 0);
assert_noop!( assert_noop!(
@@ -426,7 +427,7 @@ mod tests {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_noop!( assert_noop!(
Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, Some((50, 10, 1))), Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, Some((50, 10, 1))),
"RequireRootOrigin" sp_runtime::traits::BadOrigin,
); );
assert_eq!(Balances::free_balance(&42), 0); assert_eq!(Balances::free_balance(&42), 0);
assert_noop!( assert_noop!(
@@ -446,7 +447,7 @@ mod tests {
assert_eq!(Balances::free_balance(&42), 0); assert_eq!(Balances::free_balance(&42), 0);
assert_err!( assert_err!(
Claims::claim(Origin::signed(42), 42, sig(&alice(), &42u64.encode())), Claims::claim(Origin::signed(42), 42, sig(&alice(), &42u64.encode())),
"RequireNoOrigin", sp_runtime::traits::BadOrigin,
); );
}); });
} }
+6 -3
View File
@@ -506,7 +506,7 @@ mod tests {
// The testing primitives are very useful for avoiding having to work with signatures // 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. // or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use sp_runtime::{ use sp_runtime::{
Perbill, Permill, testing::Header, Perbill, Permill, testing::Header, DispatchResult,
traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup}, traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup},
}; };
use crate::registrar::Registrar; use crate::registrar::Registrar;
@@ -542,6 +542,7 @@ mod tests {
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type Version = (); type Version = ();
type ModuleToIndex = ();
} }
parameter_types! { parameter_types! {
pub const ExistentialDeposit: u64 = 0; pub const ExistentialDeposit: u64 = 0;
@@ -594,12 +595,13 @@ mod tests {
(*p.borrow() - 1).into() (*p.borrow() - 1).into()
}) })
} }
fn register_para( fn register_para(
id: ParaId, id: ParaId,
_info: ParaInfo, _info: ParaInfo,
code: Vec<u8>, code: Vec<u8>,
initial_head_data: Vec<u8> initial_head_data: Vec<u8>
) -> Result<(), &'static str> { ) -> DispatchResult {
PARACHAINS.with(|p| { PARACHAINS.with(|p| {
if p.borrow().contains_key(&id.into()) { if p.borrow().contains_key(&id.into()) {
panic!("ID already exists") panic!("ID already exists")
@@ -608,7 +610,8 @@ mod tests {
Ok(()) Ok(())
}) })
} }
fn deregister_para(id: ParaId) -> Result<(), &'static str> {
fn deregister_para(id: ParaId) -> DispatchResult {
PARACHAINS.with(|p| { PARACHAINS.with(|p| {
if !p.borrow().contains_key(&id.into()) { if !p.borrow().contains_key(&id.into()) {
panic!("ID doesn't exist") panic!("ID doesn't exist")
+2 -1
View File
@@ -97,7 +97,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("kusama"), spec_name: create_runtime_str!("kusama"),
impl_name: create_runtime_str!("parity-kusama"), impl_name: create_runtime_str!("parity-kusama"),
authoring_version: 2, authoring_version: 2,
spec_version: 1031, spec_version: 1032,
impl_version: 0, impl_version: 0,
apis: RUNTIME_API_VERSIONS, apis: RUNTIME_API_VERSIONS,
}; };
@@ -163,6 +163,7 @@ impl system::Trait for Runtime {
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type Version = Version; type Version = Version;
type ModuleToIndex = ModuleToIndex;
} }
parameter_types! { parameter_types! {
+28 -27
View File
@@ -23,7 +23,7 @@ use codec::{Encode, Decode};
use sp_runtime::traits::{ use sp_runtime::traits::{
Hash as HashT, BlakeTwo256, Saturating, One, Zero, Dispatchable, Hash as HashT, BlakeTwo256, Saturating, One, Zero, Dispatchable,
AccountIdConversion, AccountIdConversion, BadOrigin,
}; };
use frame_support::weights::SimpleDispatchInfo; use frame_support::weights::SimpleDispatchInfo;
use primitives::{ use primitives::{
@@ -34,7 +34,7 @@ use primitives::{
}, },
}; };
use frame_support::{ use frame_support::{
Parameter, dispatch::Result, decl_storage, decl_module, ensure, Parameter, dispatch::DispatchResult, decl_storage, decl_module, ensure,
traits::{Currency, Get, WithdrawReason, ExistenceRequirement, Randomness}, traits::{Currency, Get, WithdrawReason, ExistenceRequirement, Randomness},
}; };
@@ -74,7 +74,7 @@ fn number_range<N>(low: N, high: N) -> BlockNumberRange<N> {
// doesn't work.` // doesn't work.`
pub trait ParachainCurrency<AccountId> { pub trait ParachainCurrency<AccountId> {
fn free_balance(para_id: ParaId) -> Balance; fn free_balance(para_id: ParaId) -> Balance;
fn deduct(para_id: ParaId, amount: Balance) -> Result; fn deduct(para_id: ParaId, amount: Balance) -> DispatchResult;
} }
impl<AccountId, T: Currency<AccountId>> ParachainCurrency<AccountId> for T where impl<AccountId, T: Currency<AccountId>> ParachainCurrency<AccountId> for T where
@@ -86,7 +86,7 @@ impl<AccountId, T: Currency<AccountId>> ParachainCurrency<AccountId> for T where
T::free_balance(&para_account).into() T::free_balance(&para_account).into()
} }
fn deduct(para_id: ParaId, amount: Balance) -> Result { fn deduct(para_id: ParaId, amount: Balance) -> DispatchResult {
let para_account = para_id.into_account(); let para_account = para_id.into_account();
// burn the fee. // burn the fee.
@@ -197,7 +197,7 @@ decl_module! {
pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin { pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
/// Provide candidate receipts for parachains, in ascending order by id. /// Provide candidate receipts for parachains, in ascending order by id.
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
pub fn set_heads(origin, heads: Vec<AttestedCandidate>) -> Result { pub fn set_heads(origin, heads: Vec<AttestedCandidate>) -> DispatchResult {
ensure_none(origin)?; ensure_none(origin)?;
ensure!(!<DidUpdate>::exists(), "Parachain heads must be updated only once in the block"); ensure!(!<DidUpdate>::exists(), "Parachain heads must be updated only once in the block");
@@ -350,7 +350,7 @@ impl<T: Trait> Module<T> {
upward_messages: &[UpwardMessage], upward_messages: &[UpwardMessage],
max_queue_count: usize, max_queue_count: usize,
watermark_queue_size: usize, watermark_queue_size: usize,
) -> Result { ) -> DispatchResult {
// Either there are no more messages to add... // Either there are no more messages to add...
if !upward_messages.is_empty() { if !upward_messages.is_empty() {
let (count, size) = <RelayDispatchQueueSize>::get(id); let (count, size) = <RelayDispatchQueueSize>::get(id);
@@ -616,32 +616,32 @@ impl<T: Trait> Module<T> {
fn check_egress_queue_roots( fn check_egress_queue_roots(
head: &AttestedCandidate, head: &AttestedCandidate,
active_parachains: &[(ParaId, Option<(CollatorId, Retriable)>)] active_parachains: &[(ParaId, Option<(CollatorId, Retriable)>)]
) -> Result { ) -> DispatchResult {
let mut last_egress_id = None; let mut last_egress_id = None;
let mut iter = active_parachains.iter().map(|x| x.0); let mut iter = active_parachains.iter().map(|x| x.0);
for (egress_para_id, root) in &head.candidate.egress_queue_roots { for (egress_para_id, root) in &head.candidate.egress_queue_roots {
// egress routes should be ascending order by parachain ID without duplicate. // egress routes should be ascending order by parachain ID without duplicate.
ensure!( ensure!(
last_egress_id.as_ref().map_or(true, |x| x < &egress_para_id), last_egress_id.as_ref().map_or(true, |x| x < &egress_para_id),
"Egress routes out of order by ID" "Egress routes out of order by ID",
); );
// a parachain can't route to self // a parachain can't route to self
ensure!( ensure!(
*egress_para_id != head.candidate.parachain_index, *egress_para_id != head.candidate.parachain_index,
"Parachain routing to self" "Parachain routing to self",
); );
// no empty trie roots // no empty trie roots
ensure!( ensure!(
*root != EMPTY_TRIE_ROOT.into(), *root != EMPTY_TRIE_ROOT.into(),
"Empty trie root included" "Empty trie root included",
); );
// can't route to a parachain which doesn't exist // can't route to a parachain which doesn't exist
ensure!( ensure!(
iter.find(|x| x == egress_para_id).is_some(), iter.find(|x| x == egress_para_id).is_some(),
"Routing to non-existent parachain" "Routing to non-existent parachain",
); );
last_egress_id = Some(egress_para_id) last_egress_id = Some(egress_para_id)
@@ -654,7 +654,7 @@ impl<T: Trait> Module<T> {
fn check_candidates( fn check_candidates(
attested_candidates: &[AttestedCandidate], attested_candidates: &[AttestedCandidate],
active_parachains: &[(ParaId, Option<(CollatorId, Retriable)>)] active_parachains: &[(ParaId, Option<(CollatorId, Retriable)>)]
) -> rstd::result::Result<IncludedBlocks<T>, &'static str> ) -> rstd::result::Result<IncludedBlocks<T>, sp_runtime::DispatchError>
{ {
use primitives::parachain::ValidityAttestation; use primitives::parachain::ValidityAttestation;
use sp_runtime::traits::AppVerify; use sp_runtime::traits::AppVerify;
@@ -739,12 +739,12 @@ impl<T: Trait> Module<T> {
ensure!( ensure!(
candidate.validity_votes.len() >= majority_of(validator_group.len()), candidate.validity_votes.len() >= majority_of(validator_group.len()),
"Not enough validity attestations" "Not enough validity attestations",
); );
ensure!( ensure!(
candidate.validity_votes.len() <= authorities.len(), candidate.validity_votes.len() <= authorities.len(),
"The number of attestations exceeds the number of authorities" "The number of attestations exceeds the number of authorities",
); );
let fees = candidate.candidate().fees; let fees = candidate.candidate().fees;
@@ -762,7 +762,7 @@ impl<T: Trait> Module<T> {
.enumerate() .enumerate()
{ {
let validity_attestation = match candidate.validity_votes.get(vote_index) { let validity_attestation = match candidate.validity_votes.get(vote_index) {
None => return Err("Not enough validity votes"), None => Err("Not enough validity votes")?,
Some(v) => { Some(v) => {
expected_votes_len = vote_index + 1; expected_votes_len = vote_index + 1;
v v
@@ -770,7 +770,7 @@ impl<T: Trait> Module<T> {
}; };
if validator_group.iter().find(|&(idx, _)| *idx == auth_index).is_none() { if validator_group.iter().find(|&(idx, _)| *idx == auth_index).is_none() {
return Err("Attesting validator not on this chain's validation duty."); Err("Attesting validator not on this chain's validation duty.")?
} }
let (payload, sig) = match validity_attestation { let (payload, sig) = match validity_attestation {
@@ -796,15 +796,15 @@ impl<T: Trait> Module<T> {
ensure!( ensure!(
sig.verify(&payload[..], &authorities[auth_index]), sig.verify(&payload[..], &authorities[auth_index]),
"Candidate validity attestation signature is bad." "Candidate validity attestation signature is bad.",
); );
} }
para_block_hashes.push(candidate_hash.unwrap_or_else(|| candidate.candidate().hash())); para_block_hashes.push(candidate_hash.unwrap_or_else(|| candidate.candidate().hash()));
ensure!( ensure!(
candidate.validity_votes.len() == expected_votes_len, candidate.validity_votes.len() == expected_votes_len,
"Extra untagged validity votes along with candidate" "Extra untagged validity votes along with candidate",
); );
} }
@@ -887,12 +887,12 @@ impl<T: Trait> ProvideInherent for Module<T> {
/// Ensure that the origin `o` represents a parachain. /// Ensure that the origin `o` represents a parachain.
/// Returns `Ok` with the parachain ID that effected the extrinsic or an `Err` otherwise. /// Returns `Ok` with the parachain ID that effected the extrinsic or an `Err` otherwise.
pub fn ensure_parachain<OuterOrigin>(o: OuterOrigin) -> result::Result<ParaId, &'static str> 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() { match o.into() {
Ok(Origin::Parachain(id)) => Ok(id), Ok(Origin::Parachain(id)) => Ok(id),
_ => Err("bad origin: expected to be a parachain origin"), _ => Err(BadOrigin),
} }
} }
@@ -961,6 +961,7 @@ mod tests {
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type Version = (); type Version = ();
type ModuleToIndex = ();
} }
parameter_types! { parameter_types! {
@@ -1516,7 +1517,7 @@ mod tests {
]; ];
assert_err!( assert_err!(
Parachains::check_upward_messages(0.into(), &messages, 2, 3), Parachains::check_upward_messages(0.into(), &messages, 2, 3),
"Messages added when queue full" "Messages added when queue full",
); );
}); });
} }
@@ -1537,7 +1538,7 @@ mod tests {
]; ];
assert_err!( assert_err!(
Parachains::check_upward_messages(0.into(), &messages, 2, 3), Parachains::check_upward_messages(0.into(), &messages, 2, 3),
"Messages added when queue full" "Messages added when queue full",
); );
}); });
} }
@@ -1967,7 +1968,7 @@ mod tests {
Origin::NONE, Origin::NONE,
); );
assert_eq!(Err("Routing to non-existent parachain"), result); assert_eq!(Err("Routing to non-existent parachain".into()), result);
}); });
} }
@@ -1992,7 +1993,7 @@ mod tests {
Origin::NONE, Origin::NONE,
); );
assert_eq!(Err("Parachain routing to self"), result); assert_eq!(Err("Parachain routing to self".into()), result);
}); });
} }
@@ -2017,7 +2018,7 @@ mod tests {
Origin::NONE, Origin::NONE,
); );
assert_eq!(Err("Egress routes out of order by ID"), result); assert_eq!(Err("Egress routes out of order by ID".into()), result);
}); });
} }
@@ -2042,7 +2043,7 @@ mod tests {
Origin::NONE, Origin::NONE,
); );
assert_eq!(Err("Empty trie root included"), result); assert_eq!(Err("Empty trie root included".into()), result);
}); });
} }
+11 -10
View File
@@ -30,7 +30,7 @@ use sp_runtime::{
use frame_support::{ use frame_support::{
decl_storage, decl_module, decl_event, ensure, decl_storage, decl_module, decl_event, ensure,
dispatch::{Result, IsSubType}, traits::{Get, Currency, ReservableCurrency}, dispatch::{DispatchResult, IsSubType}, traits::{Get, Currency, ReservableCurrency},
weights::{SimpleDispatchInfo, DispatchInfo}, weights::{SimpleDispatchInfo, DispatchInfo},
}; };
use system::{self, ensure_root, ensure_signed}; use system::{self, ensure_root, ensure_signed};
@@ -53,10 +53,10 @@ pub trait Registrar<AccountId> {
info: ParaInfo, info: ParaInfo,
code: Vec<u8>, code: Vec<u8>,
initial_head_data: Vec<u8>, initial_head_data: Vec<u8>,
) -> Result; ) -> DispatchResult;
/// Deregister a parachain with given `id`. If `id` is not currently registered, an error is returned. /// Deregister a parachain with given `id`. If `id` is not currently registered, an error is returned.
fn deregister_para(id: ParaId) -> Result; fn deregister_para(id: ParaId) -> DispatchResult;
} }
impl<T: Trait> Registrar<T::AccountId> for Module<T> { impl<T: Trait> Registrar<T::AccountId> for Module<T> {
@@ -69,7 +69,7 @@ impl<T: Trait> Registrar<T::AccountId> for Module<T> {
info: ParaInfo, info: ParaInfo,
code: Vec<u8>, code: Vec<u8>,
initial_head_data: Vec<u8>, initial_head_data: Vec<u8>,
) -> Result { ) -> DispatchResult {
ensure!(!Paras::exists(id), "Parachain already exists"); ensure!(!Paras::exists(id), "Parachain already exists");
if let Scheduling::Always = info.scheduling { if let Scheduling::Always = info.scheduling {
Parachains::mutate(|parachains| Parachains::mutate(|parachains|
@@ -87,7 +87,7 @@ impl<T: Trait> Registrar<T::AccountId> for Module<T> {
Ok(()) Ok(())
} }
fn deregister_para(id: ParaId) -> Result { fn deregister_para(id: ParaId) -> DispatchResult {
let info = Paras::take(id).ok_or("Invalid id")?; let info = Paras::take(id).ok_or("Invalid id")?;
if let Scheduling::Always = info.scheduling { if let Scheduling::Always = info.scheduling {
Parachains::mutate(|parachains| Parachains::mutate(|parachains|
@@ -227,7 +227,7 @@ decl_module! {
info: ParaInfo, info: ParaInfo,
code: Vec<u8>, code: Vec<u8>,
initial_head_data: Vec<u8>, initial_head_data: Vec<u8>,
) -> Result { ) -> DispatchResult {
ensure_root(origin)?; ensure_root(origin)?;
<Self as Registrar<T::AccountId>>:: <Self as Registrar<T::AccountId>>::
register_para(id, info, code, initial_head_data) register_para(id, info, code, initial_head_data)
@@ -235,7 +235,7 @@ decl_module! {
/// Deregister a parachain with given id /// Deregister a parachain with given id
#[weight = SimpleDispatchInfo::FixedOperational(10_000)] #[weight = SimpleDispatchInfo::FixedOperational(10_000)]
pub fn deregister_para(origin, #[compact] id: ParaId) -> Result { pub fn deregister_para(origin, #[compact] id: ParaId) -> DispatchResult {
ensure_root(origin)?; ensure_root(origin)?;
<Self as Registrar<T::AccountId>>::deregister_para(id) <Self as Registrar<T::AccountId>>::deregister_para(id)
} }
@@ -540,7 +540,7 @@ impl<T: Trait + Send + Sync> SignedExtension for LimitParathreadCommits<T> where
let thread_count = ThreadCount::get() as usize; let thread_count = ThreadCount::get() as usize;
ensure!( ensure!(
selected_threads.len() < thread_count, selected_threads.len() < thread_count,
InvalidTransaction::ExhaustsResources.into() InvalidTransaction::ExhaustsResources,
); );
// ensure that this is not selecting a duplicate parathread ID // ensure that this is not selecting a duplicate parathread ID
@@ -554,7 +554,7 @@ impl<T: Trait + Send + Sync> SignedExtension for LimitParathreadCommits<T> where
let e = TransactionValidityError::from(InvalidTransaction::Custom(Error::InvalidId as u8)); let e = TransactionValidityError::from(InvalidTransaction::Custom(Error::InvalidId as u8));
let head = <parachains::Module<T>>::parachain_head(id).ok_or(e)?; let head = <parachains::Module<T>>::parachain_head(id).ok_or(e)?;
let actual = T::Hashing::hash(&head); let actual = T::Hashing::hash(&head);
ensure!(&actual == hash, InvalidTransaction::Stale.into()); ensure!(&actual == hash, InvalidTransaction::Stale);
// updated the selected threads. // updated the selected threads.
selected_threads.insert(pos, (*id, collator.clone())); selected_threads.insert(pos, (*id, collator.clone()));
@@ -635,6 +635,7 @@ mod tests {
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type Version = (); type Version = ();
type ModuleToIndex = ();
} }
parameter_types! { parameter_types! {
@@ -1335,7 +1336,7 @@ mod tests {
assert_noop!( assert_noop!(
LimitParathreadCommits::<Test>(std::marker::PhantomData) LimitParathreadCommits::<Test>(std::marker::PhantomData)
.validate(&0, &call, info, 0), .validate(&0, &call, info, 0),
InvalidTransaction::ExhaustsResources.into() InvalidTransaction::ExhaustsResources,
); );
} }
} }
+12 -9
View File
@@ -25,7 +25,7 @@ use sp_runtime::traits::{
use frame_support::weights::SimpleDispatchInfo; use frame_support::weights::SimpleDispatchInfo;
use codec::{Encode, Decode, Codec}; use codec::{Encode, Decode, Codec};
use frame_support::{ use frame_support::{
decl_module, decl_storage, decl_event, ensure, decl_module, decl_storage, decl_event, ensure, dispatch::DispatchResult,
traits::{Currency, ReservableCurrency, WithdrawReason, ExistenceRequirement, Get, Randomness}, traits::{Currency, ReservableCurrency, WithdrawReason, ExistenceRequirement, Get, Randomness},
}; };
use primitives::parachain::{ use primitives::parachain::{
@@ -379,7 +379,7 @@ decl_module! {
if let IncomingParachain::Unset(ref nb) = details { if let IncomingParachain::Unset(ref nb) = details {
ensure!(nb.who == who && nb.sub == sub, "parachain not registered by origin"); ensure!(nb.who == who && nb.sub == sub, "parachain not registered by origin");
} else { } else {
return Err("already registered") Err("already registered")?
} }
let item = (starts, IncomingParachain::Fixed{code_hash, initial_head_data}); let item = (starts, IncomingParachain::Fixed{code_hash, initial_head_data});
<Onboarding<T>>::insert(&para_id, item); <Onboarding<T>>::insert(&para_id, item);
@@ -398,7 +398,7 @@ decl_module! {
/// - `para_id` is the parachain ID whose code will be elaborated. /// - `para_id` is the parachain ID whose code will be elaborated.
/// - `code` is the preimage of the registered `code_hash` of `para_id`. /// - `code` is the preimage of the registered `code_hash` of `para_id`.
#[weight = SimpleDispatchInfo::FixedNormal(5_000_000)] #[weight = SimpleDispatchInfo::FixedNormal(5_000_000)]
pub fn elaborate_deploy_data(_origin, #[compact] para_id: ParaId, code: Vec<u8>) { pub fn elaborate_deploy_data(_origin, #[compact] para_id: ParaId, code: Vec<u8>) -> DispatchResult {
let (starts, details) = <Onboarding<T>>::get(&para_id) let (starts, details) = <Onboarding<T>>::get(&para_id)
.ok_or("parachain id not in onboarding")?; .ok_or("parachain id not in onboarding")?;
if let IncomingParachain::Fixed{code_hash, initial_head_data} = details { if let IncomingParachain::Fixed{code_hash, initial_head_data} = details {
@@ -414,8 +414,10 @@ decl_module! {
let _ = T::Parachains:: let _ = T::Parachains::
register_para(para_id, PARACHAIN_INFO, code, initial_head_data); register_para(para_id, PARACHAIN_INFO, code, initial_head_data);
} }
Ok(())
} else { } else {
return Err("deploy data not yet fixed") Err("deploy data not yet fixed".into())
} }
} }
} }
@@ -680,7 +682,7 @@ impl<T: Trait> Module<T> {
first_slot: LeasePeriodOf<T>, first_slot: LeasePeriodOf<T>,
last_slot: LeasePeriodOf<T>, last_slot: LeasePeriodOf<T>,
amount: BalanceOf<T> amount: BalanceOf<T>
) -> Result<(), &'static str> { ) -> DispatchResult {
// Bidding on latest auction. // Bidding on latest auction.
ensure!(auction_index == <AuctionCounter>::get(), "not current auction"); ensure!(auction_index == <AuctionCounter>::get(), "not current auction");
// Assume it's actually an auction (this should never fail because of above). // Assume it's actually an auction (this should never fail because of above).
@@ -706,7 +708,7 @@ impl<T: Trait> Module<T> {
.expect("array has SLOT_RANGE_COUNT items; index never reaches that value; qed") .expect("array has SLOT_RANGE_COUNT items; index never reaches that value; qed")
) )
)), )),
"bidder winning non-intersecting range" "bidder winning non-intersecting range",
); );
// Ok; we are the new winner of this range - reserve the additional amount and record. // Ok; we are the new winner of this range - reserve the additional amount and record.
@@ -818,7 +820,7 @@ impl<T: Trait> Module<T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::{result::Result, collections::HashMap, cell::RefCell}; use std::{collections::HashMap, cell::RefCell};
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
@@ -860,6 +862,7 @@ mod tests {
type MaximumBlockLength = MaximumBlockLength; type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio; type AvailableBlockRatio = AvailableBlockRatio;
type Version = (); type Version = ();
type ModuleToIndex = ();
} }
parameter_types! { parameter_types! {
@@ -899,7 +902,7 @@ mod tests {
_info: ParaInfo, _info: ParaInfo,
code: Vec<u8>, code: Vec<u8>,
initial_head_data: Vec<u8> initial_head_data: Vec<u8>
) -> Result<(), &'static str> { ) -> DispatchResult {
PARACHAINS.with(|p| { PARACHAINS.with(|p| {
if p.borrow().contains_key(&id.into()) { if p.borrow().contains_key(&id.into()) {
panic!("ID already exists") panic!("ID already exists")
@@ -908,7 +911,7 @@ mod tests {
Ok(()) Ok(())
}) })
} }
fn deregister_para(id: ParaId) -> Result<(), &'static str> { fn deregister_para(id: ParaId) -> DispatchResult {
PARACHAINS.with(|p| { PARACHAINS.with(|p| {
if !p.borrow().contains_key(&id.into()) { if !p.borrow().contains_key(&id.into()) {
panic!("ID doesn't exist") panic!("ID doesn't exist")