Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unneeded Config bounds and BlockNumber associated type #804

Merged
merged 2 commits into from
Jan 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ struct_field_align_threshold = 0
enum_discrim_align_threshold = 0
match_arm_blocks = true
force_multiline_blocks = true # changed
fn_args_layout = "Tall"
fn_params_layout = "Tall"
brace_style = "SameLineWhere"
control_brace_style = "AlwaysSameLine"
trailing_semicolon = false # changed
Expand Down
4 changes: 2 additions & 2 deletions cli/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ fn output_git_short_hash() {
Cow::from("unknown")
}
Err(err) => {
println!("cargo:warning=Failed to execute git command: {}", err);
println!("cargo:warning=Failed to execute git command: {err}");
Cow::from("unknown")
}
};

println!("cargo:rustc-env=GIT_HASH={}", git_hash);
println!("cargo:rustc-env=GIT_HASH={git_hash}");
println!("cargo:rerun-if-changed=../.git/HEAD");
println!("cargo:rerun-if-changed=../.git/refs");
println!("cargo:rerun-if-changed=build.rs");
Expand Down
2 changes: 1 addition & 1 deletion cli/src/commands/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,6 @@ fn codegen(
type_substitutes,
crate_path,
);
println!("{}", runtime_api);
println!("{runtime_api}");
Ok(())
}
4 changes: 2 additions & 2 deletions cli/src/commands/compatibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async fn handle_pallet_metadata(nodes: &[Uri], name: &str) -> color_eyre::Result
Some(pallet_metadata) => {
let hash = get_pallet_hash(&metadata.types, pallet_metadata);
let hex_hash = hex::encode(hash);
println!("Node {:?} has pallet metadata hash {:?}", node, hex_hash);
println!("Node {node:?} has pallet metadata hash {hex_hash:?}");

compatibility
.pallet_present
Expand Down Expand Up @@ -93,7 +93,7 @@ async fn handle_full_metadata(nodes: &[Uri]) -> color_eyre::Result<()> {
let metadata = fetch_runtime_metadata(node).await?;
let hash = get_metadata_hash(&metadata);
let hex_hash = hex::encode(hash);
println!("Node {:?} has metadata hash {:?}", node, hex_hash,);
println!("Node {node:?} has metadata hash {hex_hash:?}",);

compatibility_map
.entry(hex_hash)
Expand Down
4 changes: 2 additions & 2 deletions cli/src/commands/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ pub async fn run(opts: Opts) -> color_eyre::Result<()> {
let bytes = hex::decode(hex_data.trim_start_matches("0x"))?;
let metadata = <RuntimeMetadataPrefixed as Decode>::decode(&mut &bytes[..])?;
let json = serde_json::to_string_pretty(&metadata)?;
println!("{}", json);
println!("{json}");
Ok(())
}
"hex" => {
println!("{}", hex_data);
println!("{hex_data}");
Ok(())
}
"bytes" => {
Expand Down
4 changes: 2 additions & 2 deletions codegen/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,8 @@ impl RuntimeGenerator {
}

/// Return a vector of tuples of variant names and corresponding struct definitions.
pub fn generate_structs_from_variants<'a, F>(
type_gen: &'a TypeGenerator,
pub fn generate_structs_from_variants<F>(
type_gen: &TypeGenerator,
type_id: u32,
variant_to_struct_name: F,
error_message_type_name: &str,
Expand Down
7 changes: 2 additions & 5 deletions codegen/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl<'a> TypeGenerator<'a> {
pub fn resolve_type(&self, id: u32) -> Type<PortableForm> {
self.type_registry
.resolve(id)
.unwrap_or_else(|| panic!("No type with id {} found", id))
.unwrap_or_else(|| panic!("No type with id {id} found"))
.clone()
}

Expand Down Expand Up @@ -403,10 +403,7 @@ impl ToTokens for CratePath {
impl From<&str> for CratePath {
fn from(crate_path: &str) -> Self {
Self(syn::Path::from_string(crate_path).unwrap_or_else(|err| {
panic!(
"failed converting {:?} to `syn::Path`: {:?}",
crate_path, err
);
panic!("failed converting {crate_path:?} to `syn::Path`: {err:?}");
}))
}
}
Expand Down
2 changes: 1 addition & 1 deletion codegen/src/types/type_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl TypePathType {
"BTreeSet" => parse_quote!(::std::collections::BTreeSet),
"Range" => parse_quote!(::core::ops::Range),
"RangeInclusive" => parse_quote!(::core::ops::RangeInclusive),
ident => panic!("Unknown prelude type '{}'", ident),
ident => panic!("Unknown prelude type '{ident}'"),
}
}
_ => {
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/balance_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Submit the transaction with default params:
let hash = api.tx().sign_and_submit_default(&tx, &signer).await?;

println!("Balance transfer extrinsic submitted: {}", hash);
println!("Balance transfer extrinsic submitted: {hash}");

Ok(())
}
2 changes: 1 addition & 1 deletion examples/examples/balance_transfer_with_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// submit the transaction:
let hash = api.tx().sign_and_submit(&tx, &signer, tx_params).await?;

println!("Balance transfer extrinsic submitted: {}", hash);
println!("Balance transfer extrinsic submitted: {hash}");

Ok(())
}
3 changes: 1 addition & 2 deletions examples/examples/custom_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ impl Config for MyConfig {
// polkadot runtime used, so some operations will fail. Normally when using a custom `Config`
// impl types MUST match exactly those used in the actual runtime.
type Index = u64;
type BlockNumber = <SubstrateConfig as Config>::BlockNumber;
type Hash = <SubstrateConfig as Config>::Hash;
type Hasher = <SubstrateConfig as Config>::Hasher;
type Header = <SubstrateConfig as Config>::Header;
Expand Down Expand Up @@ -58,7 +57,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// submit the transaction with default params:
let hash = api.tx().sign_and_submit_default(&tx, &signer).await?;

println!("Balance transfer extrinsic submitted: {}", hash);
println!("Balance transfer extrinsic submitted: {hash}");

Ok(())
}
4 changes: 2 additions & 2 deletions examples/examples/dynamic_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

// submit the transaction with default params:
let hash = api.tx().sign_and_submit_default(&tx, &signer).await?;
println!("Balance transfer extrinsic submitted: {}", hash);
println!("Balance transfer extrinsic submitted: {hash}");

// 2. Dynamic constant access (the dynamic equivalent to the fetch_constants example).

let constant_address = subxt::dynamic::constant("Balances", "ExistentialDeposit");
let existential_deposit = api.constants().at(&constant_address)?.to_value()?;
println!("Existential Deposit: {}", existential_deposit);
println!("Existential Deposit: {existential_deposit}");

// 3. Dynamic storage access

Expand Down
2 changes: 1 addition & 1 deletion examples/examples/fetch_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Look it up:
let existential_deposit = api.constants().at(&address)?;

println!("Existential Deposit: {}", existential_deposit);
println!("Existential Deposit: {existential_deposit}");

Ok(())
}
8 changes: 4 additions & 4 deletions examples/examples/fetch_staking_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);

let alice_id = AccountKeyring::Alice.to_account_id();
println!(" Alice account id: {:?}", alice_id);
println!(" Alice account id: {alice_id:?}");

// Get Alice' Stash account ID
let alice_stash_id: AccountId32 = sr25519::Pair::from_string("//Alice//stash", None)
.expect("Could not obtain stash signer pair")
.public()
.into();
println!(" Alice//stash account id: {:?}", alice_stash_id);
println!(" Alice//stash account id: {alice_stash_id:?}");

// Map from all locked "stash" accounts to the controller account.
let controller_acc_addr = polkadot::storage().staking().bonded(&alice_stash_id);
Expand All @@ -63,7 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.fetch(&controller_acc_addr)
.await?
.unwrap();
println!(" account controlled by: {:?}", controller_acc);
println!(" account controlled by: {controller_acc:?}");

let era_reward_addr = polkadot::storage().staking().eras_reward_points(era.index);
let era_result = api
Expand All @@ -72,7 +72,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.await?
.fetch(&era_reward_addr)
.await?;
println!("Era reward points: {:?}", era_result);
println!("Era reward points: {era_result:?}");

Ok(())
}
6 changes: 3 additions & 3 deletions examples/examples/storage_iterating.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("\nExample 1. Obtained keys:");
while let Some((key, value)) = iter.next().await? {
println!("Key: 0x{}", hex::encode(key));
println!(" Value: {}", value);
println!(" Value: {value}");
}
}

Expand Down Expand Up @@ -69,7 +69,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// - polkadot.rs generated file under `version_notifiers()` fn
// - metadata in json format
let value = u64::decode(&mut &*storage_data)?;
println!(" Value: {}", value);
println!(" Value: {value}");
}
}
}
Expand Down Expand Up @@ -109,7 +109,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// - polkadot.rs generated file under `version_notifiers()` fn
// - metadata in json format
let value = u64::decode(&mut &storage_data[..])?;
println!(" Value: {}", value);
println!(" Value: {value}");
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/examples/submit_and_watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ async fn handle_transfer_events() -> Result<(), Box<dyn std::error::Error>> {
}
// Report other statuses we see.
else {
println!("Current transaction status: {:?}", ev);
println!("Current transaction status: {ev:?}");
}
}

Expand Down
2 changes: 1 addition & 1 deletion examples/examples/subscribe_runtime_updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let update_client = api.updater();
tokio::spawn(async move {
let result = update_client.perform_runtime_updates().await;
println!("Runtime update failed with result={:?}", result);
println!("Runtime update failed with result={result:?}");
});

// If this client is kept in use a while, it'll update its metadata and such
Expand Down
2 changes: 1 addition & 1 deletion subxt/src/blocks/block_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ where
}

/// Return the block number.
pub fn number(&self) -> T::BlockNumber {
pub fn number(&self) -> <T::Header as crate::config::Header>::Number {
self.header().number()
}

Expand Down
66 changes: 20 additions & 46 deletions subxt/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ pub mod polkadot;
pub mod substrate;

use codec::{
Codec,
Decode,
Encode,
EncodeLike,
};
use core::fmt::Debug;
use serde::Serialize;
use serde::{
de::DeserializeOwned,
Serialize,
};

pub use extrinsic_params::ExtrinsicParams;
pub use polkadot::PolkadotConfig;
Expand All @@ -31,66 +33,39 @@ pub use substrate::SubstrateConfig;
pub trait Config: 'static {
/// Account index (aka nonce) type. This stores the number of previous
/// transactions associated with a sender account.
type Index: Parameter
+ Member
+ serde::de::DeserializeOwned
+ Default
+ Copy
+ scale_info::TypeInfo
+ Into<u64>;

/// The block number type used by the runtime.
type BlockNumber: Parameter
+ Member
+ Default
+ Copy
+ std::hash::Hash
+ std::str::FromStr
+ Into<u64>;
type Index: Debug + Copy + DeserializeOwned + Into<u64>;

/// The output of the `Hashing` function.
type Hash: Parameter
+ Member
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Ord
+ Default
type Hash: Debug
+ Copy
+ std::hash::Hash
+ Send
+ Sync
+ Decode
+ AsRef<[u8]>
+ AsMut<[u8]>
+ scale_info::TypeInfo;
+ Serialize
+ DeserializeOwned
+ Encode
+ PartialEq;

/// The account ID type.
type AccountId: Clone + Serialize;
type AccountId: Debug + Clone + Serialize;

/// The address type.
type Address: Encode + From<Self::AccountId>;
type Address: Debug + Encode + From<Self::AccountId>;

/// The signature type.
type Signature: Encode;
type Signature: Debug + Encode;

/// The hashing system (algorithm) being used in the runtime (e.g. Blake2).
type Hasher: Hasher<Output = Self::Hash>;
type Hasher: Debug + Hasher<Output = Self::Hash>;

/// The block header.
type Header: Parameter
+ Header<Number = Self::BlockNumber, Hasher = Self::Hasher>
+ Member
+ serde::de::DeserializeOwned;
type Header: Debug + Header<Hasher = Self::Hasher> + Send + DeserializeOwned;

/// This type defines the extrinsic extra and additional parameters.
type ExtrinsicParams: extrinsic_params::ExtrinsicParams<Self::Index, Self::Hash>;
}

/// Parameter trait copied from `substrate::frame_support`.
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug {}
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug {}

/// A type that can be used in runtime structures. Copied from `sp_runtime::traits`.
pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}

/// This represents the hasher used by a node to hash things like block headers
/// and extrinsics.
pub trait Hasher {
Expand All @@ -110,7 +85,7 @@ pub trait Hasher {
/// This represents the block header type used by a node.
pub trait Header: Sized + Encode {
/// The block number type for this header.
type Number;
type Number: Into<u64>;
/// The hasher used to hash this header.
type Hasher: Hasher;

Expand Down Expand Up @@ -146,7 +121,6 @@ impl<T: Config, E: extrinsic_params::ExtrinsicParams<T::Index, T::Hash>> Config
for WithExtrinsicParams<T, E>
{
type Index = T::Index;
type BlockNumber = T::BlockNumber;
type Hash = T::Hash;
type AccountId = T::AccountId;
type Address = T::Address;
Expand Down
Loading