Allow pallet error enum variants to contain fields (#10242)

* Allow pallet errors to contain at most one field

* Update docs on pallet::error

* Reword documentation

* cargo fmt

* Introduce CompactPalletError trait and require #[pallet::error] fields to implement them

* cargo fmt

* Do not assume tuple variants

* Add CompactPalletError derive macro

* Check for error type compactness in construct_runtime

* cargo fmt

* Derive CompactPalletError instead of implementing it directly during macro expansion

* Implement CompactPalletError on OptionBool instead of Option<bool>

* Check for type idents instead of variant ident

* Add doc comments for ErrorCompactnessTest

* Add an trait implementation of ErrorCompactnessTest for ()

* Convert the error field of DispatchError to a 4-element byte array

* Add static check for pallet error size

* Rename to MAX_PALLET_ERROR_ENCODED_SIZE

* Remove ErrorCompactnessTest trait

* Remove check_compactness

* Return only the most significant byte when constructing a custom InvalidTransaction

* Rename CompactPalletError to PalletError

* Use counter to generate unique idents for assert macros

* Make declarative pallet macros compile with pallet error size checks

* Remove unused doc comment

* Try and fix build errors

* Fix build errors

* Add macro_use for some test modules

* Test fix

* Fix compilation errors

* Remove unneeded #[macro_use]

* Resolve import ambiguity

* Make path to pallet Error enum more specific

* Fix test expectation

* Disambiguate imports

* Fix test expectations

* Revert appending pallet module name to path

* Rename bags_list::list::Error to BagError

* Fixes

* Fixes

* Fixes

* Fix test expectations

* Fix test expectation

* Add more implementations for PalletError

* Lift the 1-field requirement for nested pallet errors

* Fix UI test expectation

* Remove PalletError impl for OptionBool

* Use saturating operations

* cargo fmt

* Delete obsolete test

* Fix test expectation

* Try and use assert macro in const context

* Pull out the pallet error size check macro

* Fix UI test for const assertion

* cargo fmt

* Apply clippy suggestion

* Fix doc comment

* Docs for create_tt_return_macro

* Ensure TryInto is imported in earlier Rust editions

* Apply suggestions from code review

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Fix up comments and names

* Implement PalletError for Never

* cargo fmt

* Don't compile example code

* Bump API version for block builder

* Factor in codec attributes while derving PalletError

* Rename module and fix unit test

* Add missing attribute

* Check API version and convert ApplyExtrinsicResult accordingly

* Rename BagError to ListError

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Use codec crate re-exported from frame support

* Add links to types mentioned in doc comments

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* cargo fmt

* cargo fmt

* Re-add attribute for hidden docs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Keith Yeung
2022-03-24 09:11:14 +01:00
committed by GitHub
parent 5c9f23af13
commit 208be86934
38 changed files with 1263 additions and 241 deletions
@@ -0,0 +1,20 @@
// This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Runtime types that existed in old API versions.
pub mod byte_sized_error;
@@ -0,0 +1,100 @@
// This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Runtime types that existed prior to BlockBuilder API version 6.
use crate::{ArithmeticError, TokenError};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
/// [`ModuleError`] type definition before BlockBuilder API version 6.
#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct ModuleError {
/// Module index, matching the metadata module index.
pub index: u8,
/// Module specific error value.
pub error: u8,
/// Optional error message.
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
pub message: Option<&'static str>,
}
impl PartialEq for ModuleError {
fn eq(&self, other: &Self) -> bool {
(self.index == other.index) && (self.error == other.error)
}
}
/// [`DispatchError`] type definition before BlockBuilder API version 6.
#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum DispatchError {
/// Some error occurred.
Other(
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
&'static str,
),
/// Failed to lookup some data.
CannotLookup,
/// A bad origin.
BadOrigin,
/// A custom error in a module.
Module(ModuleError),
/// At least one consumer is remaining so the account cannot be destroyed.
ConsumerRemaining,
/// There are no providers so the account cannot be created.
NoProviders,
/// There are too many consumers so the account cannot be created.
TooManyConsumers,
/// An error to do with tokens.
Token(TokenError),
/// An arithmetic error.
Arithmetic(ArithmeticError),
}
/// [`DispatchOutcome`] type definition before BlockBuilder API version 6.
pub type DispatchOutcome = Result<(), DispatchError>;
/// [`ApplyExtrinsicResult`] type definition before BlockBuilder API version 6.
pub type ApplyExtrinsicResult =
Result<DispatchOutcome, crate::transaction_validity::TransactionValidityError>;
/// Convert the legacy `ApplyExtrinsicResult` type to the latest version.
pub fn convert_to_latest(old: ApplyExtrinsicResult) -> crate::ApplyExtrinsicResult {
old.map(|outcome| {
outcome.map_err(|e| match e {
DispatchError::Other(s) => crate::DispatchError::Other(s),
DispatchError::CannotLookup => crate::DispatchError::CannotLookup,
DispatchError::BadOrigin => crate::DispatchError::BadOrigin,
DispatchError::Module(err) => crate::DispatchError::Module(crate::ModuleError {
index: err.index,
error: [err.error, 0, 0, 0],
message: err.message,
}),
DispatchError::ConsumerRemaining => crate::DispatchError::ConsumerRemaining,
DispatchError::NoProviders => crate::DispatchError::NoProviders,
DispatchError::TooManyConsumers => crate::DispatchError::TooManyConsumers,
DispatchError::Token(err) => crate::DispatchError::Token(err),
DispatchError::Arithmetic(err) => crate::DispatchError::Arithmetic(err),
})
})
}
+14 -9
View File
@@ -57,6 +57,7 @@ use scale_info::TypeInfo;
pub mod curve;
pub mod generic;
pub mod legacy;
mod multiaddress;
pub mod offchain;
pub mod runtime_logger;
@@ -97,6 +98,10 @@ pub use sp_arithmetic::{
pub use either::Either;
/// The number of bytes of the module-specific `error` field defined in [`ModuleError`].
/// In FRAME, this is the maximum encoded size of a pallet error type.
pub const MAX_MODULE_ERROR_ENCODED_SIZE: usize = 4;
/// An abstraction over justification for a block's validity under a consensus algorithm.
///
/// Essentially a finality proof. The exact formulation will vary between consensus
@@ -468,7 +473,7 @@ pub struct ModuleError {
/// Module index, matching the metadata module index.
pub index: u8,
/// Module specific error value.
pub error: u8,
pub error: [u8; MAX_MODULE_ERROR_ENCODED_SIZE],
/// Optional error message.
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
@@ -922,15 +927,15 @@ mod tests {
fn dispatch_error_encoding() {
let error = DispatchError::Module(ModuleError {
index: 1,
error: 2,
error: [2, 0, 0, 0],
message: Some("error message"),
});
let encoded = error.encode();
let decoded = DispatchError::decode(&mut &encoded[..]).unwrap();
assert_eq!(encoded, vec![3, 1, 2]);
assert_eq!(encoded, vec![3, 1, 2, 0, 0, 0]);
assert_eq!(
decoded,
DispatchError::Module(ModuleError { index: 1, error: 2, message: None })
DispatchError::Module(ModuleError { index: 1, error: [2, 0, 0, 0], message: None })
);
}
@@ -943,9 +948,9 @@ mod tests {
Other("bar"),
CannotLookup,
BadOrigin,
Module(ModuleError { index: 1, error: 1, message: None }),
Module(ModuleError { index: 1, error: 2, message: None }),
Module(ModuleError { index: 2, error: 1, message: None }),
Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: None }),
Module(ModuleError { index: 1, error: [2, 0, 0, 0], message: None }),
Module(ModuleError { index: 2, error: [1, 0, 0, 0], message: None }),
ConsumerRemaining,
NoProviders,
Token(TokenError::NoFunds),
@@ -970,8 +975,8 @@ mod tests {
// Ignores `message` field in `Module` variant.
assert_eq!(
Module(ModuleError { index: 1, error: 1, message: Some("foo") }),
Module(ModuleError { index: 1, error: 1, message: None }),
Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: Some("foo") }),
Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: None }),
);
}
@@ -1554,6 +1554,12 @@ impl Printable for &[u8] {
}
}
impl<const N: usize> Printable for [u8; N] {
fn print(&self) {
sp_io::misc::print_hex(&self[..]);
}
}
impl Printable for &str {
fn print(&self) {
sp_io::misc::print_utf8(self.as_bytes());