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

Zero sized types #121

Merged
merged 6 commits into from
Jun 8, 2020
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
10 changes: 4 additions & 6 deletions proc-macro/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,8 @@ pub fn call(s: Structure) -> TokenStream {
const FUNCTION: &'static str = #call_name;
fn events_decoder(
decoder: &mut #subxt::EventsDecoder<T>,
) -> Result<(), #subxt::EventsError> {
decoder.#with_module()?;
Ok(())
) {
decoder.#with_module();
}
}

Expand Down Expand Up @@ -125,9 +124,8 @@ mod tests {
const FUNCTION: &'static str = "transfer";
fn events_decoder(
decoder: &mut substrate_subxt::EventsDecoder<T>,
) -> Result<(), substrate_subxt::EventsError> {
decoder.with_balances()?;
Ok(())
) {
decoder.with_balances();
}
}

Expand Down
18 changes: 8 additions & 10 deletions proc-macro/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub fn module(_args: TokenStream, tokens: TokenStream) -> TokenStream {
let module = utils::path_to_ident(path);
let with_module = with_module_ident(module);
Some(quote! {
self.#with_module()?;
self.#with_module();
})
} else {
None
Expand All @@ -99,7 +99,7 @@ pub fn module(_args: TokenStream, tokens: TokenStream) -> TokenStream {
let ident = &ty.ident;
let ident_str = ident.to_string();
Some(quote! {
self.register_type_size::<T::#ident>(#ident_str)?;
self.register_type_size::<T::#ident>(#ident_str);
})
} else {
None
Expand All @@ -114,16 +114,15 @@ pub fn module(_args: TokenStream, tokens: TokenStream) -> TokenStream {
/// `EventsDecoder` extension trait.
pub trait #module_events_decoder {
/// Registers this modules types.
fn #with_module(&mut self) -> Result<(), #subxt::EventsError>;
fn #with_module(&mut self);
}

impl<T: #module> #module_events_decoder for
#subxt::EventsDecoder<T>
{
fn #with_module(&mut self) -> Result<(), #subxt::EventsError> {
fn #with_module(&mut self) {
#(#bounds)*
#(#types)*
Ok(())
}
}
}
Expand Down Expand Up @@ -167,16 +166,15 @@ mod tests {
/// `EventsDecoder` extension trait.
pub trait BalancesEventsDecoder {
/// Registers this modules types.
fn with_balances(&mut self) -> Result<(), substrate_subxt::EventsError>;
fn with_balances(&mut self);
}

impl<T: Balances> BalancesEventsDecoder for
substrate_subxt::EventsDecoder<T>
{
fn with_balances(&mut self) -> Result<(), substrate_subxt::EventsError> {
self.with_system()?;
self.register_type_size::<T::Balance>("Balance")?;
Ok(())
fn with_balances(&mut self) {
self.with_system();
self.register_type_size::<T::Balance>("Balance");
}
}
};
Expand Down
59 changes: 25 additions & 34 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ use std::{
HashMap,
HashSet,
},
convert::TryFrom,
marker::{
PhantomData,
Send,
Expand Down Expand Up @@ -87,51 +86,43 @@ pub struct EventsDecoder<T> {
marker: PhantomData<fn() -> T>,
}

impl<T: System> TryFrom<Metadata> for EventsDecoder<T> {
type Error = EventsError;

fn try_from(metadata: Metadata) -> Result<Self, Self::Error> {
impl<T: System> EventsDecoder<T> {
/// Creates a new `EventsDecoder`.
pub fn new(metadata: Metadata) -> Self {
let mut decoder = Self {
metadata,
type_sizes: HashMap::new(),
marker: PhantomData,
};
// register default event arg type sizes for dynamic decoding of events
decoder.register_type_size::<bool>("bool")?;
decoder.register_type_size::<u32>("ReferendumIndex")?;
decoder.register_type_size::<[u8; 16]>("Kind")?;
decoder.register_type_size::<[u8; 32]>("AuthorityId")?;
decoder.register_type_size::<u8>("u8")?;
decoder.register_type_size::<u32>("u32")?;
decoder.register_type_size::<u32>("AccountIndex")?;
decoder.register_type_size::<u32>("SessionIndex")?;
decoder.register_type_size::<u32>("PropIndex")?;
decoder.register_type_size::<u32>("ProposalIndex")?;
decoder.register_type_size::<u32>("AuthorityIndex")?;
decoder.register_type_size::<u64>("AuthorityWeight")?;
decoder.register_type_size::<u32>("MemberCount")?;
decoder.register_type_size::<T::AccountId>("AccountId")?;
decoder.register_type_size::<T::BlockNumber>("BlockNumber")?;
decoder.register_type_size::<T::Hash>("Hash")?;
decoder.register_type_size::<u8>("VoteThreshold")?;
dvc94ch marked this conversation as resolved.
Show resolved Hide resolved

Ok(decoder)
decoder.register_type_size::<bool>("bool");
decoder.register_type_size::<u32>("ReferendumIndex");
decoder.register_type_size::<[u8; 16]>("Kind");
decoder.register_type_size::<[u8; 32]>("AuthorityId");
decoder.register_type_size::<u8>("u8");
decoder.register_type_size::<u32>("u32");
decoder.register_type_size::<u32>("AccountIndex");
decoder.register_type_size::<u32>("SessionIndex");
decoder.register_type_size::<u32>("PropIndex");
decoder.register_type_size::<u32>("ProposalIndex");
decoder.register_type_size::<u32>("AuthorityIndex");
decoder.register_type_size::<u64>("AuthorityWeight");
decoder.register_type_size::<u32>("MemberCount");
decoder.register_type_size::<T::AccountId>("AccountId");
decoder.register_type_size::<T::BlockNumber>("BlockNumber");
decoder.register_type_size::<T::Hash>("Hash");
decoder.register_type_size::<u8>("VoteThreshold");
decoder
}
}

impl<T: System> EventsDecoder<T> {
/// Register a type.
pub fn register_type_size<U>(&mut self, name: &str) -> Result<usize, EventsError>
pub fn register_type_size<U>(&mut self, name: &str) -> usize
where
U: Default + Codec + Send + 'static,
{
let size = U::default().encode().len();
if size > 0 {
self.type_sizes.insert(name.to_string(), size);
Ok(size)
} else {
Err(EventsError::TypeSizeUnavailable(name.to_owned()))
}
self.type_sizes.insert(name.to_string(), size);
size
}

/// Check missing type sizes.
Expand All @@ -156,7 +147,7 @@ impl<T: System> EventsDecoder<T> {
}
}
}
if missing.len() > 0 {
if !missing.is_empty() {
log::warn!(
"The following primitive types do not have registered sizes: {:?} \
If any of these events are received, an error will occur since we cannot decode them",
Expand Down
9 changes: 2 additions & 7 deletions src/frame/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
//! Implements support for built-in runtime modules.

use crate::{
events::{
EventsDecoder,
EventsError,
},
events::EventsDecoder,
metadata::{
Metadata,
MetadataError,
Expand Down Expand Up @@ -62,9 +59,7 @@ pub trait Call<T>: Encode {
/// Function name.
const FUNCTION: &'static str;
/// Load event decoder.
fn events_decoder(_decoder: &mut EventsDecoder<T>) -> Result<(), EventsError> {
Ok(())
}
fn events_decoder(_decoder: &mut EventsDecoder<T>) {}
}

/// Event trait.
Expand Down
26 changes: 12 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,7 @@ use sp_runtime::{
MultiSignature,
};
use sp_version::RuntimeVersion;
use std::{
convert::TryFrom,
marker::PhantomData,
};
use std::marker::PhantomData;

mod error;
mod events;
Expand Down Expand Up @@ -148,11 +145,7 @@ impl<T: System + Send + Sync, S, E> ClientBuilder<T, S, E> {
let client = if let Some(client) = self.client {
client
} else {
let url = self
.url
.as_ref()
.map(|s| &**s)
.unwrap_or("ws://127.0.0.1:9944");
let url = self.url.as_deref().unwrap_or("ws://127.0.0.1:9944");
if url.starts_with("ws://") || url.starts_with("wss://") {
jsonrpsee::ws_client(url).await?
} else {
Expand Down Expand Up @@ -198,6 +191,11 @@ impl<T: System, S, E> Clone for Client<T, S, E> {
}

impl<T: System, S, E> Client<T, S, E> {
/// Returns the genesis hash.
pub fn genesis(&self) -> &T::Hash {
&self.genesis_hash
}

/// Returns the chain metadata.
pub fn metadata(&self) -> &Metadata {
&self.metadata
Expand Down Expand Up @@ -362,11 +360,11 @@ where
}

/// Returns an events decoder for a call.
pub fn events_decoder<C: Call<T>>(&self) -> Result<EventsDecoder<T>, Error> {
pub fn events_decoder<C: Call<T>>(&self) -> EventsDecoder<T> {
let metadata = self.metadata().clone();
let mut decoder = EventsDecoder::try_from(metadata)?;
C::events_decoder(&mut decoder)?;
Ok(decoder)
let mut decoder = EventsDecoder::new(metadata);
C::events_decoder(&mut decoder);
decoder
}

/// Create and submit an extrinsic and return corresponding Hash if successful
Expand Down Expand Up @@ -421,7 +419,7 @@ where
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
{
let extrinsic = self.create_signed(call, signer).await?;
let decoder = self.events_decoder::<C>()?;
let decoder = self.events_decoder::<C>();
self.submit_and_watch_extrinsic(extrinsic, decoder).await
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,7 @@ impl StorageMetadata {
}

pub fn default<V: Decode>(&self) -> Result<V, MetadataError> {
Decode::decode(&mut &self.default[..])
.map_err(|err| MetadataError::DefaultError(err))
Decode::decode(&mut &self.default[..]).map_err(MetadataError::DefaultError)
}

pub fn hash(hasher: &StorageHasher, bytes: &[u8]) -> Vec<u8> {
Expand Down
4 changes: 2 additions & 2 deletions src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ impl<T: System> Rpc<T> {
&self,
block_number: Option<BlockNumber<T>>,
) -> Result<Option<T::Hash>, Error> {
let block_number = block_number.map(|bn| ListOrValue::Value(bn));
let block_number = block_number.map(ListOrValue::Value);
let params = Params::Array(vec![to_json_value(block_number)?]);
let list_or_value = self.client.request("chain_getBlockHash", params).await?;
match list_or_value {
Expand Down Expand Up @@ -490,7 +490,7 @@ pub async fn wait_for_block_events<T: System>(
}
}
}
return if events.len() > 0 {
return if !events.is_empty() {
Ok(ExtrinsicSuccess {
block: block_hash,
extrinsic: ext_hash,
Expand Down