Skip to content

Commit

Permalink
fix: correct variant
Browse files Browse the repository at this point in the history
  • Loading branch information
S0c5 committed Apr 19, 2024
1 parent 07d0030 commit cbb8a1a
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 9 deletions.
5 changes: 4 additions & 1 deletion scales/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ license = "Apache-2.0"

[dependencies]
bytes = { version = "1.1.0", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["serde"] }
scale-info = { version = "2.10.0", default-features = false, features = ["serde"] }
serde = { version = "1.0.137", default-features = false }
serde_json = { version = "1.0.80", default-features = false, optional = true }
codec = { version = "3.1.2", package = "parity-scale-codec", default-features = false, optional = true }
hex = { version = "0.4.3", default-features = false, features = ["alloc"], optional = true }
log = "0.4.17"



[features]
default = ["std", "codec", "json", "hex", "experimental-serializer"]
Expand Down
16 changes: 11 additions & 5 deletions scales/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,15 +176,21 @@ impl SpecificType {
A: AsRef<[u8]> + PartialEq + core::fmt::Debug,
B: AsRef<[u8]> + PartialEq + core::fmt::Debug,
{


match self {
SpecificType::Variant(_, _, Some(_)) => Some(self),
SpecificType::Variant(_, ref mut variants, idx @ None) => {
let i = variants

let (vf, _) = variants
.iter()
.map(get_field)
.position(|f| f.as_ref() == selection.as_ref())? as u8;
variants.retain(|v| v.index() == i);
*idx = Some(i);
.map(|v| (v.index, get_field(&v)))
.find(|(_, f)| f.as_ref() == selection.as_ref())?;

variants.retain(|v| v.index() == vf);

*idx = Some(vf);

Some(self)
}
_ => panic!("Only for enum variants"),
Expand Down
Binary file added scales/src/registry.bin
Binary file not shown.
56 changes: 53 additions & 3 deletions scales/src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ use crate::prelude::*;
use bytes::BufMut;
use codec::Encode;
use core::fmt::{self, Debug};

use scale_info::{PortableRegistry, TypeInfo};
use serde::{ser, Serialize};


use crate::{EnumVariant, SpecificType, TupleOrArray};

type TypeId = u32;
Expand Down Expand Up @@ -385,6 +387,7 @@ where

fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
self.maybe_some()?;

if matches!(self.ty, None | Some(SpecificType::Map(_, _))) {
compact_number(len.expect("known length"), &mut self.out);
}
Expand Down Expand Up @@ -438,8 +441,9 @@ where
Some(SpecificType::Str) | None => Ok(None),
// { "foo": "Bar" } => "Bar" might be an enum variant
Some(ref mut var @ SpecificType::Variant(_, _, None)) => {

var.pick_mut(to_vec(val)?, |k| to_vec(k.name()).unwrap())
.ok_or_else(|| Error::BadInput("Invalid variant".into()))?;
.ok_or_else(|| Error::BadInput("Invalid ".into()))?;
self.out.put_u8(var.variant_id());
Ok(Some(()))
}
Expand Down Expand Up @@ -587,16 +591,22 @@ where
where
T: Serialize,
{


match self {
TypedSerializer::Enum(ser) => {
if let Some(ref mut var @ SpecificType::Variant(_, _, None)) = ser.ty {

let key_data = to_vec(key)?;

// assume the key is the name of the variant

var.pick_mut(key_data, |v| to_vec(v.name()).unwrap())
.ok_or_else(|| Error::BadInput("Invalid variant".into()))?
.ok_or_else(|| Error::BadInput("Invalid bb".into()))?
.variant_id()
.serialize(&mut **ser)?;
}

Ok(())
}
TypedSerializer::Empty(ser) => key.serialize(&mut **ser),
Expand All @@ -608,17 +618,26 @@ where
where
T: Serialize,
{

//
match self {
TypedSerializer::Composite(ser, types) => {



let mut ty = ser.resolve(types.remove(0));
// serde_json unwraps newtypes
if let SpecificType::StructNewType(ty_id) = ty {
ty = ser.resolve(ty_id)
}


ser.ty = Some(ty);
}
TypedSerializer::Enum(ser) => {

if let Some(var @ SpecificType::Variant(_, _, Some(_))) = &ser.ty {

if let EnumVariant::NewType(_, _, ty_id) = var.into() {
let ty = ser.resolve(ty_id);

Expand Down Expand Up @@ -842,7 +861,7 @@ fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
#[cfg(test)]
mod tests {
use super::*;
use codec::Encode;
use codec::{Decode, Encode};
use core::mem::size_of;
use scale_info::{meta_type, Registry, TypeInfo};
use serde_json::to_value;
Expand Down Expand Up @@ -1282,4 +1301,35 @@ mod tests {
assert_eq!(out, expected);
Ok(())
}

#[test]
fn test_extrincic_call() -> Result<()> {
let mut bytes = include_bytes!("registry.bin");
let registry = PortableRegistry::decode(&mut &bytes[..]).expect("hello");

let transfer_call = serde_json::json!({
"transfer_keep_alive": {
"dest": {
"Id": hex::decode("12840f0626ac847d41089c4e05cf0719c5698af1e3bb87b66542de70b2de4b2b").expect("expected valid address")
},
"value": 1_000_000_000_000u64
}
});


let call_data = to_vec_with_info(
&transfer_call,
(&registry, 106u32).into(),
).expect("call data");

let encooded = hex::encode(&call_data);

assert_eq!(
"0x04030012840f0626ac847d41089c4e05cf0719c5698af1e3bb87b66542de70b2de4b2b070010a5d4e8",
format!("0x04{}", encooded)
);


Ok(())
}
}
1 change: 1 addition & 0 deletions scales/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ impl<'a> Serialize for Value<'a> {
let ty = self.resolve(self.ty_id);

use SpecificType::*;

match (ty, self.registry).into() {
Bool => ser.serialize_bool(data.get_u8() != 0),
U8 => ser.serialize_u8(data.get_u8()),
Expand Down

0 comments on commit cbb8a1a

Please sign in to comment.