Skip to content

Commit

Permalink
Add error information back into metadata to roll back removal in #394
Browse files Browse the repository at this point in the history
  • Loading branch information
jsdw committed Feb 16, 2022
1 parent 0e0553a commit ad6f19f
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions subxt/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ pub struct Metadata {
metadata: RuntimeMetadataLastVersion,
pallets: HashMap<String, PalletMetadata>,
events: HashMap<(u8, u8), EventMetadata>,
errors: HashMap<(u8, u8), ErrorMetadata>,
}

impl Metadata {
Expand All @@ -107,6 +108,19 @@ impl Metadata {
Ok(event)
}

/// Returns the metadata for the error at the given pallet and error indices.
pub fn error(
&self,
pallet_index: u8,
error_index: u8,
) -> Result<&ErrorMetadata, MetadataError> {
let error = self
.errors
.get(&(pallet_index, error_index))
.ok_or(MetadataError::ErrorNotFound(pallet_index, error_index))?;
Ok(error)
}

/// Resolve a type definition.
pub fn resolve_type(&self, id: u32) -> Option<&Type<PortableForm>> {
self.metadata.types.resolve(id)
Expand Down Expand Up @@ -193,6 +207,30 @@ impl EventMetadata {
}
}

#[derive(Clone, Debug)]
pub struct ErrorMetadata {
pallet: String,
error: String,
variant: Variant<PortableForm>,
}

impl ErrorMetadata {
/// Get the name of the pallet from which the error originates.
pub fn pallet(&self) -> &str {
&self.pallet
}

/// Get the name of the specific pallet error.
pub fn error(&self) -> &str {
&self.error
}

/// Get the description of the specific pallet error.
pub fn description(&self) -> &[String] {
self.variant.docs()
}
}

#[derive(Debug, thiserror::Error)]
pub enum InvalidMetadataError {
#[error("Invalid prefix")]
Expand Down Expand Up @@ -293,10 +331,36 @@ impl TryFrom<RuntimeMetadataPrefixed> for Metadata {
})
.collect();

let pallet_errors = metadata
.pallets
.iter()
.filter_map(|pallet| {
pallet.error.as_ref().map(|error| {
let type_def_variant = get_type_def_variant(error.ty.id())?;
Ok((pallet, type_def_variant))
})
})
.collect::<Result<Vec<_>, _>>()?;
let errors = pallet_errors
.iter()
.flat_map(|(pallet, type_def_variant)| {
type_def_variant.variants().iter().map(move |var| {
let key = (pallet.index, var.index());
let value = ErrorMetadata {
pallet: pallet.name.clone(),
error: var.name().clone(),
variant: var.clone(),
};
(key, value)
})
})
.collect();

Ok(Self {
metadata,
pallets,
events,
errors,
})
}
}

0 comments on commit ad6f19f

Please sign in to comment.