UnionType.fromJson calls toJson on the selected type instead of fromJson
Describe the bug
UnionType.fromJson parses the selected payload with type.toJson(...) instead of type.fromJson(...).
In packages/ssz/src/type/union.ts:
return {
selector: union.selector,
value: type.toJson(union.value),
} as ValueOfTypes<Types>;
That returns a JSON form (or a corrupted string) instead of a value form. deserialize / serialize of a correctly built value work; fromJson does not.
Version
@chainsafe/[email protected]
Repro
import {UnionType, NoneType, ByteVectorType} from "@chainsafe/ssz";
const u = new UnionType([new NoneType(), new ByteVectorType(4)]);
const parsed = u.fromJson({selector: 1, value: "0x01020304"});
console.log(parsed);
// actual: { selector: 1, value: "0x00x0001000200030004" }
// expected: { selector: 1, value: Uint8Array([1, 2, 3, 4]) }
u.serialize(parsed);
// throws: offset is out of bounds
Contrast with a correct value path:
const correct = {selector: 1, value: new Uint8Array([1, 2, 3, 4])};
u.serialize(correct); // ok
u.deserialize(u.serialize(correct)); // { selector: 1, value: Uint8Array([1,2,3,4]) }
u.toJson(correct); // { selector: 1, value: "0x01020304" }
With UintNumberType the bug is quieter (7 becomes "7"), but the returned type is still JSON form, not value form.
Expected
fromJson should call type.fromJson(union.value) so the union value matches what deserialize returns and what serialize accepts.
Actual
fromJson calls type.toJson(union.value). For ByteVector / ByteList this produces a bad string and later serialize fails. For number types it leaves a stringified JSON value.