Skip to content

Commit

Permalink
clippy and fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
jsdw committed Oct 31, 2023
1 parent c089f55 commit 6bcba67
Show file tree
Hide file tree
Showing 20 changed files with 54 additions and 66 deletions.
11 changes: 5 additions & 6 deletions bin/tx-decoder/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,13 @@ impl<'a> AppState<'a> {
let upgrade_block = get_upgrade_block(&self.app.network, version.try_into()?);
let mut len = 0;
let mut error_count = 0;
let decoder = self.decoder.read();
while let Some(Ok(block)) = blocks.next().await {
let version = if upgrade_block == Some(block.block_num.try_into()?) && upgrade_block != Some(0) {
previous.expect("Upgrade block must have previous version; qed")
} else {
version
};
let decoder = self.decoder.read();
if Self::decode(&decoder, block, version.try_into()?, errors).is_err() {
error_count += 1;
}
Expand Down Expand Up @@ -142,16 +142,15 @@ impl<'a> AppState<'a> {
/// returns the previous spec version.
async fn register_metadata(&self, conn: &mut PgConnection, version: SpecVersion) -> Result<Option<u32>, Error> {
let (past, present) = past_and_present_version(conn, version.try_into()?).await?;
let mut decoder = self.decoder.write();
if !decoder.has_version(&present) {
if !self.decoder.read().has_version(&present) {
let meta = metadata(conn, present.try_into()?).await?;
decoder.register_version(present, &meta)?;
self.decoder.write().register_version(present, &meta)?;
}

if let Some(p) = past {
if !decoder.has_version(&p) {
if !self.decoder.read().has_version(&p) {
let meta = metadata(conn, p.try_into()?).await?;
decoder.register_version(p, &meta)?;
self.decoder.write().register_version(p, &meta)?;
}
}
Ok(past)
Expand Down
2 changes: 1 addition & 1 deletion desub-current/src/decoder/decode_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ pub struct StorageMapKey<'b> {
pub hasher: StorageHasher,
}

impl<'m, 'b> StorageMapKey<'b> {
impl<'b> StorageMapKey<'b> {
pub fn into_owned(self) -> StorageMapKey<'static> {
StorageMapKey { bytes: Cow::Owned(self.bytes.into_owned()), ty: self.ty, hasher: self.hasher }
}
Expand Down
10 changes: 5 additions & 5 deletions desub-current/src/decoder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ mod extrinsic_bytes;

use crate::metadata::Metadata;
use crate::TypeId;
use extrinsic_bytes::{AllExtrinsicBytes, ExtrinsicBytesError};
use parity_scale_codec::{Compact, Decode};
use scale_decode::DecodeAsType;
use scale_value::Value;
use parity_scale_codec::{Compact, Decode};
use extrinsic_bytes::{AllExtrinsicBytes, ExtrinsicBytesError};
use serde::Serialize;
use sp_runtime::{AccountId32, MultiAddress, MultiSignature};
use std::borrow::Cow;
Expand Down Expand Up @@ -67,8 +67,8 @@ pub enum DecodeError {

/// Decode a single [`Value`] from a piece of scale encoded data, given some metadata and the ID of the type that we
/// are expecting it to decode into.
pub fn decode_value_by_id<'a, Id: Into<TypeId>>(
metadata: &'a Metadata,
pub fn decode_value_by_id<Id: Into<TypeId>>(
metadata: &Metadata,
ty: Id,
data: &mut &[u8],
) -> Result<Value<TypeId>, DecodeValueError> {
Expand Down Expand Up @@ -158,7 +158,7 @@ pub fn decode_extrinsics<'a>(
metadata: &'a Metadata,
data: &mut &[u8],
) -> Result<Vec<Extrinsic<'a>>, (Vec<Extrinsic<'a>>, DecodeError)> {
let extrinsic_bytes = AllExtrinsicBytes::new(*data).map_err(|e| (Vec::new(), e.into()))?;
let extrinsic_bytes = AllExtrinsicBytes::new(data).map_err(|e| (Vec::new(), e.into()))?;

log::trace!("Decoding {} Total Extrinsics.", extrinsic_bytes.len());

Expand Down
2 changes: 1 addition & 1 deletion desub-current/src/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ mod u8_map;
mod version_14;

use crate::{ScaleInfoTypeId, Type, TypeId};
use parity_scale_codec::Decode;
use frame_metadata::{RuntimeMetadata, RuntimeMetadataPrefixed};
use parity_scale_codec::Decode;
use readonly_array::ReadonlyArray;
use scale_info::{form::PortableForm, PortableRegistry};
use u8_map::U8Map;
Expand Down
5 changes: 2 additions & 3 deletions desub-current/src/metadata/version_14.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ pub fn decode(meta: RuntimeMetadataV14) -> Result<Metadata, MetadataError> {
.map(|call_md| {
// Get the type representing the variant of available calls:
let calls_type_id = call_md.ty;
let calls_type = registry
.resolve(calls_type_id.id)
.ok_or_else(|| MetadataError::TypeNotFound(calls_type_id.id))?;
let calls_type =
registry.resolve(calls_type_id.id).ok_or_else(|| MetadataError::TypeNotFound(calls_type_id.id))?;

// Expect that type to be a variant:
let calls_type_def = &calls_type.type_def;
Expand Down
15 changes: 6 additions & 9 deletions desub-current/tests/decode_extrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

use desub_current::{
decoder::{self, SignedExtensionWithAdditional},
Metadata, Value, ValueDef
Metadata, Value, ValueDef,
};
use scale_value::{Composite, Variant};

Expand All @@ -40,11 +40,11 @@ fn singleton_value(x: Value<()>) -> Value<()> {
}

fn hash_value(xs: Vec<u8>) -> Value<()> {
singleton_value(Value::from_bytes(&xs))
singleton_value(Value::from_bytes(xs))
}

fn assert_args_equal<T: Clone>(args: &[Value<T>], expected: Vec<Value<()>>) {
let args: Vec<_> = args.into_iter().map(|v| v.clone().remove_context()).collect();
let args: Vec<_> = args.iter().map(|v| v.clone().remove_context()).collect();
assert_eq!(&args, &expected);
}

Expand Down Expand Up @@ -182,8 +182,8 @@ fn technical_committee_execute_unsigned() {
name,
values: Composite::Unnamed(args)
}), .. }
if &*name == "Balances"
&& matches!(&args[0], Value { value: ValueDef::Variant(Variant { name, ..}), .. } if &*name == "transfer")
if name == "Balances"
&& matches!(&args[0], Value { value: ValueDef::Variant(Variant { name, ..}), .. } if name == "transfer")
));
assert_eq!(ext.call_data.arguments[1].clone().remove_context(), Value::u128(500));
}
Expand All @@ -201,10 +201,7 @@ fn tips_report_awesome_unsigned() {
assert_eq!(&*ext.call_data.ty.name, "report_awesome");
assert_eq!(ext.call_data.arguments.len(), 2);

assert_eq!(
ext.call_data.arguments[0].clone().remove_context(),
Value::from_bytes("This person rocks!")
);
assert_eq!(ext.call_data.arguments[0].clone().remove_context(), Value::from_bytes("This person rocks!"));
}

// Named structs shouldn't be an issue; this extrinsic contains one.
Expand Down
6 changes: 3 additions & 3 deletions desub-current/tests/decode_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with substrate-desub. If not, see <http://www.gnu.org/licenses/>.

use parity_scale_codec::Encode;
use desub_current::{
decoder::{self, StorageHasher},
Metadata, Value,
};
use parity_scale_codec::Encode;

static V14_METADATA_POLKADOT_SCALE: &[u8] = include_bytes!("data/v14_metadata_polkadot.scale");

Expand Down Expand Up @@ -141,7 +141,7 @@ fn balances_account() {
let keys = entry.details.map_keys();

let bobs_accountid = sp_keyring::AccountKeyring::Bob.to_account_id();
let bobs_value = account_id_to_value(&bobs_accountid);
let bobs_value = account_id_to_value(bobs_accountid);

assert_eq!(keys.len(), 1);
assert_hasher_eq!(keys[0].hasher, StorageHasher::Blake2_128Concat, bobs_value);
Expand All @@ -164,7 +164,7 @@ fn imonline_authoredblocks() {
let keys = entry.details.map_keys();

let bobs_accountid = sp_keyring::AccountKeyring::Bob.to_account_id();
let bobs_value = account_id_to_value(&bobs_accountid);
let bobs_value = account_id_to_value(bobs_accountid);

// Because the hashers are Twox64Concat, we can check the keys we provided:
assert_eq!(keys.len(), 2);
Expand Down
2 changes: 1 addition & 1 deletion desub-json-resolver/src/extrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Extrinsics {
}

pub fn get(&self, ty: &str, spec: u32, chain: &str) -> Option<&desub_legacy::RustTypeMarker> {
if let Some(ty) = self.get_chain_types(chain, spec).map(|c| c.get(ty)).flatten() {
if let Some(ty) = self.get_chain_types(chain, spec).and_then(|c| c.get(ty)) {
Some(ty)
} else {
self.default.get(ty)
Expand Down
6 changes: 3 additions & 3 deletions desub-json-resolver/src/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl Modules {

/// Iterate over all the types in each module
pub fn iter_types(&self) -> impl Iterator<Item = (&String, &RustTypeMarker)> {
self.modules.values().map(|v| v.types.iter()).flatten()
self.modules.values().flat_map(|v| v.types.iter())
}
}

Expand All @@ -75,8 +75,8 @@ impl ModuleTypes {
pub fn merge(&self, other: &ModuleTypes) -> ModuleTypes {
let (mut types, mut fallbacks) = (self.types.clone(), self.fallbacks.clone());
let other = other.clone();
types.extend(other.types.into_iter());
fallbacks.extend(other.fallbacks.into_iter());
types.extend(other.types);
fallbacks.extend(other.fallbacks);

ModuleTypes { types, fallbacks }
}
Expand Down
4 changes: 2 additions & 2 deletions desub-legacy/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ pub use frame_metadata::v14::StorageEntryType;

use crate::{
error::Error,
substrate_types::{self, StructField, SubstrateType, pallet_democracy},
substrate_types::{self, pallet_democracy, StructField, SubstrateType},
CommonTypes, RustTypeMarker, TypeDetective,
};
use bitvec::order::Lsb0 as BitOrderLsb0;
use parity_scale_codec::{Compact, CompactLen, Decode, Input};
use desub_common::SpecVersion;
use parity_scale_codec::{Compact, CompactLen, Decode, Input};
use std::{
cell::RefCell,
collections::HashMap,
Expand Down
2 changes: 1 addition & 1 deletion desub-legacy/src/decoder/extrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl fmt::Display for GenericExtrinsic {
if let Some(v) = &self.signature {
s.push_str(&format!("{}", v));
} else {
s.push_str(&"None".to_string());
s.push_str("None");
}
s.push('\n');
s.push_str("CALL");
Expand Down
4 changes: 2 additions & 2 deletions desub-legacy/src/decoder/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ pub use frame_metadata::{decode_different::DecodeDifferent, RuntimeMetadata, Run
use super::storage::{StorageInfo, StorageLookupTable};
use crate::RustTypeMarker;
use parity_scale_codec::{Decode, Encode, EncodeAsRef, HasCompact};
use sp_core::{storage::StorageKey, twox_128};
use serde::{Deserialize, Serialize};
use sp_core::{storage::StorageKey, twox_128};

use std::{
collections::{HashMap, HashSet},
Expand Down Expand Up @@ -229,7 +229,7 @@ impl<'a> Metadata {
}

fn generate_key<S: AsRef<str>>(prefix: S) -> Vec<u8> {
prefix.as_ref().split_ascii_whitespace().map(|s| twox_128(s.as_bytes()).to_vec()).flatten().collect()
prefix.as_ref().split_ascii_whitespace().flat_map(|s| twox_128(s.as_bytes()).to_vec()).collect()
}

/// print out a detailed but human readable description of the module
Expand Down
2 changes: 1 addition & 1 deletion desub-legacy/src/decoder/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl StorageLookupTable {

pub fn meta_for_key(&self, key: &[u8]) -> Option<&StorageInfo> {
let key = self.table.keys().find(|&k| &key[..k.len()] == k.as_slice());
key.map(|k| self.lookup(k)).flatten()
key.and_then(|k| self.lookup(k))
}

pub fn extra_key_data<'a>(&self, key: &'a [u8]) -> Option<&'a [u8]> {
Expand Down
22 changes: 11 additions & 11 deletions desub-legacy/src/regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ pub fn remove_empty_generic<S: AsRef<str>>(s: S) -> Option<String> {
/// Sanitizes a type and returns parts that might correspond to PolkadotJS types
pub fn sanitize_ty(ty: &str) -> Option<String> {
log::trace!("sanitizing ty {}", ty);
let ty = if let Some(no_empty_gen) = remove_empty_generic(&ty) { no_empty_gen } else { ty.to_string() };
let ty = if let Some(no_empty_gen) = remove_empty_generic(ty) { no_empty_gen } else { ty.to_string() };
let ty = if let Some(no_trait) = remove_trait(&ty) { no_trait } else { ty };
let ty = if let Some(no_path) = remove_path(&ty) { no_path } else { ty };
let ty = if let Some(un_prefixed) = remove_prefix(&ty) { un_prefixed } else { ty };
Expand All @@ -206,16 +206,16 @@ pub fn sanitize_ty(ty: &str) -> Option<String> {
pub fn rust_tuple_decl() -> Regex {
Regex::new(
[
r#"^\(([\w\d><:;\[\]()\n ]+)"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*"#,
r#",? *([\w\d><:;\[\]()\n ]+)*\)$"#,
r"^\(([\w\d><:;\[\]()\n ]+)",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*,? *([\w\d><:;\[\]()\n ]+)*",
r",? *([\w\d><:;\[\]()\n ]+)*\)$",
]
.join("")
.as_str(),
Expand Down
15 changes: 4 additions & 11 deletions desub-legacy/src/substrate_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ mod remote;
use self::remote::*;
use crate::{Error, SetField};
use bitvec::order::Lsb0 as BitOrderLsb0;
use serde::Serialize;
use sp_core::crypto::{AccountId32, Ss58Codec};
use sp_runtime::MultiAddress;
use serde::Serialize;
use std::{convert::TryFrom, fmt};

pub use self::data::Data;
Expand All @@ -37,8 +37,8 @@ pub type Address = MultiAddress<AccountId32, u32>;
/// Stripped down version of https://docs.substrate.io/rustdocs/latest/pallet_democracy
/// Remove when/if the real pallet_democracy is published.
pub mod pallet_democracy {
use sp_runtime::RuntimeDebug;
use parity_scale_codec::{Decode, Input};
use sp_runtime::RuntimeDebug;
/// Static copy of https://docs.substrate.io/rustdocs/latest/pallet_democracy/struct.Vote.html
#[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug)]
pub struct Vote {
Expand All @@ -58,9 +58,10 @@ pub mod pallet_democracy {
}

/// Static copy of https://docs.substrate.io/rustdocs/latest/pallet_democracy/enum.Conviction.html
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug, Default)]
pub enum Conviction {
/// 0.1x votes, unlocked.
#[default]
None,
/// 1x votes, locked for an enactment period following a successful vote.
Locked1x,
Expand All @@ -76,12 +77,6 @@ pub mod pallet_democracy {
Locked6x,
}

impl Default for Conviction {
fn default() -> Self {
Conviction::None
}
}

impl Conviction {
/// The amount of time (in number of periods) that our conviction implies a successful voter's
/// balance should be locked for.
Expand Down Expand Up @@ -115,8 +110,6 @@ pub mod pallet_democracy {
}
}



/// A 'stateful' version of [RustTypeMarker](enum.RustTypeMarker.html).
/// 'Std' variant is not here like in RustTypeMarker.
/// Instead common types are just apart of the enum
Expand Down
2 changes: 1 addition & 1 deletion desub-legacy/src/substrate_types/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl Encode for Data {
Data::Raw(ref x) => {
let l = x.len().min(32);
let mut r = vec![l as u8 + 1; l + 1];
r[1..].copy_from_slice(&x[..l as usize]);
r[1..].copy_from_slice(&x[..l]);
r
}
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
Expand Down
2 changes: 1 addition & 1 deletion desub-legacy/src/test_suite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ pub fn mock_runtime(num: u32) -> RuntimeVersion {
impl_version: num,
apis: Cow::from(Vec::new()),
transaction_version: 24,
state_version: 0
state_version: 0,
}
}
2 changes: 1 addition & 1 deletion desub-legacy/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
// along with substrate-desub. If not, see <http://www.gnu.org/licenses/>.

use crate::{Error, SubstrateType};
use sp_core::crypto::Ss58Codec;
use serde::{
ser::{self, SerializeSeq},
Serializer,
};
use sp_core::crypto::Ss58Codec;
use std::convert::TryFrom;

// Utility function to serialize from slice/vec to hex
Expand Down
Loading

0 comments on commit 6bcba67

Please sign in to comment.