|
| 1 | +import dataclasses |
| 2 | +from dataclasses import is_dataclass |
| 3 | +import enum |
| 4 | +from typing import Type, TypeVar, Union |
| 5 | +import typing |
| 6 | +import json |
| 7 | + |
| 8 | +from scalecodec.base import ScaleTypeDef, ScaleType, ScaleBytes |
| 9 | +from scalecodec.types import Struct, Option, Vec, Enum |
| 10 | + |
| 11 | +T = TypeVar('T') |
| 12 | + |
| 13 | + |
| 14 | +class ScaleSerializable: |
| 15 | + @classmethod |
| 16 | + def scale_type_def(cls) -> ScaleTypeDef: |
| 17 | + if is_dataclass(cls): |
| 18 | + |
| 19 | + arguments = {} |
| 20 | + for field in dataclasses.fields(cls): |
| 21 | + arguments[field.name] = cls.dataclass_field_to_scale_typ_def(field) |
| 22 | + |
| 23 | + return Struct(**arguments) |
| 24 | + elif issubclass(cls, enum.Enum): |
| 25 | + variants = {status.name: None for status in cls} |
| 26 | + return Enum(**variants) |
| 27 | + |
| 28 | + raise NotImplementedError |
| 29 | + |
| 30 | + def serialize(self) -> Union[str, int, float, bool, dict, list]: |
| 31 | + scale_type = self.to_scale_type() |
| 32 | + return scale_type.serialize() |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def deserialize(cls: Type[T], data: Union[str, int, float, bool, dict, list]) -> T: |
| 36 | + scale_type = cls.scale_type_def().new() |
| 37 | + scale_type.deserialize(data) |
| 38 | + return cls.from_scale_type(scale_type) |
| 39 | + |
| 40 | + def to_scale_type(self) -> ScaleType: |
| 41 | + |
| 42 | + if not is_dataclass(self) and not issubclass(self.__class__, enum.Enum): |
| 43 | + raise NotImplementedError("Type not supported.") |
| 44 | + |
| 45 | + scale_type = self.scale_type_def().new() |
| 46 | + |
| 47 | + if issubclass(self.__class__, enum.Enum): |
| 48 | + scale_type.deserialize(self.name) |
| 49 | + elif is_dataclass(self): |
| 50 | + value = {} |
| 51 | + for field in dataclasses.fields(self): |
| 52 | + |
| 53 | + actual_type = field.type |
| 54 | + field_name = field.name[:-1] if field.name.endswith('_') else field.name |
| 55 | + |
| 56 | + if typing.get_origin(actual_type) is typing.Union: |
| 57 | + # Extract the arguments of the Union type |
| 58 | + args = typing.get_args(actual_type) |
| 59 | + if type(None) in args: |
| 60 | + # If NoneType is in the args, it's an Optional |
| 61 | + actual_type = [arg for arg in args if arg is not type(None)][0] |
| 62 | + |
| 63 | + if getattr(self, field.name) is None: |
| 64 | + value[field_name] = None |
| 65 | + else: |
| 66 | + |
| 67 | + if typing.get_origin(actual_type) is list: |
| 68 | + actual_type = typing.get_args(actual_type)[0] |
| 69 | + |
| 70 | + if issubclass(actual_type, ScaleSerializable): |
| 71 | + value[field_name] = [i.serialize() for i in getattr(self, field.name)] |
| 72 | + else: |
| 73 | + value[field_name] = getattr(self, field.name) |
| 74 | + |
| 75 | + # TODO too simplified now |
| 76 | + elif issubclass(actual_type, ScaleSerializable): |
| 77 | + |
| 78 | + value[field_name] = getattr(self, field.name).serialize() |
| 79 | + else: |
| 80 | + value[field_name] = getattr(self, field.name) |
| 81 | + |
| 82 | + scale_type.deserialize(value) |
| 83 | + |
| 84 | + return scale_type |
| 85 | + |
| 86 | + @classmethod |
| 87 | + def from_scale_type(cls: Type[T], scale_type: ScaleType) -> T: |
| 88 | + if is_dataclass(cls): |
| 89 | + |
| 90 | + fields = {} |
| 91 | + |
| 92 | + for field in dataclasses.fields(cls): |
| 93 | + |
| 94 | + scale_field_name = field.name[:-1] if field.name.endswith('_') else field.name |
| 95 | + |
| 96 | + actual_type = field.type |
| 97 | + |
| 98 | + if typing.get_origin(field.type) is typing.Union: |
| 99 | + # Extract the arguments of the Union type |
| 100 | + args = typing.get_args(field.type) |
| 101 | + if type(None) in args: |
| 102 | + # If NoneType is in the args, it's an Optional |
| 103 | + if field.name in scale_type.value: |
| 104 | + if scale_type.value[field.name] is None: |
| 105 | + fields[field.name] = None |
| 106 | + continue |
| 107 | + else: |
| 108 | + actual_type = [arg for arg in args if arg is not type(None)][0] |
| 109 | + else: |
| 110 | + # print(field.name) |
| 111 | + continue |
| 112 | + |
| 113 | + if typing.get_origin(actual_type) is list: |
| 114 | + items = [] |
| 115 | + actual_type = typing.get_args(actual_type)[0] |
| 116 | + |
| 117 | + if issubclass(type(scale_type.type_def), (Struct, Option)): |
| 118 | + list_items = scale_type.value_object[scale_field_name].value_object |
| 119 | + elif issubclass(type(scale_type.type_def), (Vec, Enum)): |
| 120 | + list_items = scale_type.value_object[1].value_object |
| 121 | + else: |
| 122 | + raise ValueError(f'Unsupported type: {type(scale_type.type_def)}') |
| 123 | + |
| 124 | + for item in list_items: |
| 125 | + if actual_type in [str, int, float, bool]: |
| 126 | + items.append(item.value) |
| 127 | + elif actual_type is bytes: |
| 128 | + items.append(item.to_bytes()) |
| 129 | + elif is_dataclass(actual_type): |
| 130 | + items.append(actual_type.from_scale_type(item)) |
| 131 | + |
| 132 | + fields[field.name] = items |
| 133 | + |
| 134 | + elif actual_type in [str, int, float, bool]: |
| 135 | + fields[field.name] = scale_type.value[scale_field_name] |
| 136 | + elif actual_type is bytes: |
| 137 | + fields[field.name] = scale_type.value_object[scale_field_name].to_bytes() |
| 138 | + elif is_dataclass(actual_type): |
| 139 | + try: |
| 140 | + |
| 141 | + # TODO unwrap Option |
| 142 | + if issubclass(type(scale_type.type_def), (Struct, Option)): |
| 143 | + |
| 144 | + field_scale_type = scale_type.value_object[scale_field_name] |
| 145 | + elif issubclass(type(scale_type.type_def), Enum): |
| 146 | + field_scale_type = scale_type.value_object[1] |
| 147 | + else: |
| 148 | + raise ValueError(f"Unexpected type {type(scale_type.type_def)}") |
| 149 | + |
| 150 | + fields[field.name] = actual_type.from_scale_type(field_scale_type) |
| 151 | + except (KeyError, TypeError) as e: |
| 152 | + print('oeps', str(e)) |
| 153 | + elif issubclass(actual_type, enum.Enum): |
| 154 | + fields[field.name] = actual_type[scale_type.value_object[1].value] |
| 155 | + return cls(**fields) |
| 156 | + raise NotImplementedError |
| 157 | + |
| 158 | + def to_scale_bytes(self) -> ScaleBytes: |
| 159 | + scale_obj = self.to_scale_type() |
| 160 | + return scale_obj.encode() |
| 161 | + |
| 162 | + @classmethod |
| 163 | + def from_scale_bytes(cls: Type[T], scale_bytes: ScaleBytes) -> T: |
| 164 | + scale_obj = cls.scale_type_def().new() |
| 165 | + scale_obj.decode(scale_bytes) |
| 166 | + return cls.from_scale_type(scale_obj) |
| 167 | + |
| 168 | + def to_json(self) -> str: |
| 169 | + return json.dumps(self.serialize(), indent=4) |
| 170 | + |
| 171 | + @classmethod |
| 172 | + def from_json(cls: Type[T], json_data: str) -> T: |
| 173 | + # data = json.loads(json_data) |
| 174 | + return cls.deserialize(json_data) |
| 175 | + |
| 176 | + @classmethod |
| 177 | + def dataclass_field_to_scale_typ_def(cls, field) -> ScaleTypeDef: |
| 178 | + |
| 179 | + if 'scale' in field.metadata: |
| 180 | + return field.metadata['scale'] |
| 181 | + |
| 182 | + # Check if the field type is an instance of Optional |
| 183 | + actual_type = field.type |
| 184 | + wrap_option = False |
| 185 | + wrap_vec = False |
| 186 | + |
| 187 | + if typing.get_origin(field.type) is typing.Union: |
| 188 | + # Extract the arguments of the Union type |
| 189 | + args = typing.get_args(field.type) |
| 190 | + if type(None) in args: |
| 191 | + # If NoneType is in the args, it's an Optional |
| 192 | + wrap_option = True |
| 193 | + actual_type = [arg for arg in args if arg is not type(None)][0] |
| 194 | + # print(f"The field '{field.name}' is Optional with inner type: {actual_type}") |
| 195 | + |
| 196 | + if typing.get_origin(actual_type) is list: |
| 197 | + wrap_vec = True |
| 198 | + actual_type = typing.get_args(actual_type)[0] |
| 199 | + |
| 200 | + if is_dataclass(actual_type): |
| 201 | + if issubclass(actual_type, ScaleSerializable): |
| 202 | + scale_def = actual_type.scale_type_def() |
| 203 | + else: |
| 204 | + raise ValueError(f"Cannot serialize dataclass {field.type.__class__}") |
| 205 | + |
| 206 | + elif actual_type is bytes: |
| 207 | + raise ValueError("bytes is ambiguous; specify SCALE type def in metadata e.g. {'scale': H256}") |
| 208 | + elif actual_type is int: |
| 209 | + raise ValueError("int is ambiguous; specify SCALE type def in metadata e.g. {'scale': U32}") |
| 210 | + |
| 211 | + elif issubclass(actual_type, enum.Enum): |
| 212 | + variants = {status.name: None for status in actual_type} |
| 213 | + scale_def = Enum(**variants) |
| 214 | + |
| 215 | + else: |
| 216 | + raise ValueError(f"Cannot convert {actual_type} to ScaleTypeDef") |
| 217 | + |
| 218 | + if wrap_vec: |
| 219 | + scale_def = Vec(scale_def) |
| 220 | + if wrap_option: |
| 221 | + scale_def = Option(scale_def) |
| 222 | + |
| 223 | + return scale_def |
0 commit comments