Skip to content

Commit

Permalink
fix: use index override when decoding enums in events
Browse files Browse the repository at this point in the history
  • Loading branch information
sander2 committed Jan 12, 2022
1 parent ea8c4dd commit 8276999
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 deletions.
46 changes: 39 additions & 7 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,13 +187,13 @@ where
TypeDef::Variant(variant) => {
let variant_index = u8::decode(input)?;
variant_index.encode_to(output);
let variant =
variant
.variants()
.get(variant_index as usize)
.ok_or_else(|| {
Error::Other(format!("Variant {} not found", variant_index))
})?;
let variant = variant
.variants()
.iter()
.find(|v| v.index() == variant_index)
.ok_or_else(|| {
Error::Other(format!("Variant {} not found", variant_index))
})?;
for field in variant.fields() {
self.decode_type(field.ty().id(), input, output)?;
}
Expand Down Expand Up @@ -522,4 +522,36 @@ mod tests {
assert_eq!(events[0].1.variant_index, encoded_event[0]);
assert_eq!(events[0].1.data.0, encoded_event[1..]);
}

#[test]
fn event_containing_explicit_index() {
#[derive(Clone, Encode, TypeInfo)]
#[repr(u8)]
#[allow(trivial_numeric_casts)] // required because the Encode derive produces a warning otherwise
pub enum MyType {
B = 10,
}

#[derive(Clone, Encode, TypeInfo)]
enum Event {
A(MyType),
}

let pallet_index = 0;
let pallet = pallet_metadata::<Event>(pallet_index);
let decoder = init_decoder(vec![pallet]);

let event = Event::A(MyType::B);
let encoded_event = event.encode();
let event_records = vec![event_record(pallet_index, event)];

let mut input = Vec::new();
event_records.encode_to(&mut input);

// this would panic if the explicit enum item index were not correctly used
let events = decoder.decode_events(&mut &input[..]).unwrap();

assert_eq!(events[0].1.variant_index, encoded_event[0]);
assert_eq!(events[0].1.data.0, encoded_event[1..]);
}
}
5 changes: 3 additions & 2 deletions test-runtime/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ async fn main() {

async fn run() {
// Select substrate binary to run based on env var.
let substrate_bin =
env::var(SUBSTRATE_BIN_ENV_VAR).unwrap_or_else(|_| "substrate".to_owned());
let substrate_bin = env::var(SUBSTRATE_BIN_ENV_VAR).unwrap_or_else(|_| {
"/home/sander/workspace/interlay/substrate-subxt/substrate".to_owned()
});

// Run binary.
let port = next_open_port()
Expand Down

0 comments on commit 8276999

Please sign in to comment.