Skip to content

Commit

Permalink
feat: support full uint64 range on simpleserialize.com
Browse files Browse the repository at this point in the history
  • Loading branch information
nflaig committed Jul 7, 2023
1 parent 424b426 commit 1ad8f58
Showing 1 changed file with 59 additions and 2 deletions.
61 changes: 59 additions & 2 deletions packages/simpleserialize.com/src/util/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import {Type} from "@chainsafe/ssz";
import {
Type,
UintNumberType,
UintBigintType,
ContainerType,
ListBasicType,
ListCompositeType,
VectorBasicType,
VectorCompositeType,
} from "@chainsafe/ssz";
import {ssz} from "@lodestar/types";

const {
let {
phase0,
altair,
bellatrix,
Expand All @@ -15,6 +24,12 @@ const {
...primitive
} = ssz;

phase0 = patchSszTypes(phase0);
altair = patchSszTypes(altair);
bellatrix = patchSszTypes(bellatrix);
capella = patchSszTypes(capella);
primitive = patchSszTypes(primitive);

export const forks = {
phase0: {...phase0, ...primitive} as Record<string, Type<unknown>>,
altair: {...phase0, ...altair, ...primitive} as Record<string, Type<unknown>>,
Expand All @@ -27,3 +42,45 @@ export type ForkName = keyof typeof forks;
export function typeNames<T>(types: Record<string, Type<T>>): string[] {
return Object.keys(types).sort();
}

/**
* Patch SSZ types to support the full uint64 range on the website
*/
function patchSszTypes<T extends Record<string, Type<unknown>>>(sszTypes: T): T {
const types = {...sszTypes};
for (const key of Object.keys(types) as (keyof typeof types)[]) {
types[key] = replaceUintTypeWithUintBigintType(types[key]);
}
return types;
}

function replaceUintTypeWithUintBigintType<T extends Type<unknown>>(type: T): T {
if (type instanceof UintNumberType && type.byteLength === 8) {
return new UintBigintType(type.byteLength) as unknown as T;
}

// For Container iterate and replace all sub properties
if (type instanceof ContainerType) {
const fields = {...type.fields};
for (const key of Object.keys(fields) as (keyof typeof fields)[]) {
fields[key] = replaceUintTypeWithUintBigintType(fields[key]);
}
return new ContainerType(fields, type.opts) as unknown as T;
}

// For List or vectors replace the subType
if (type instanceof ListBasicType) {
return new ListBasicType(replaceUintTypeWithUintBigintType(type.elementType), type.limit) as unknown as T;
}
if (type instanceof VectorBasicType) {
return new VectorBasicType(replaceUintTypeWithUintBigintType(type.elementType), type.length) as unknown as T;
}
if (type instanceof ListCompositeType) {
return new ListCompositeType(replaceUintTypeWithUintBigintType(type.elementType), type.limit) as unknown as T;
}
if (type instanceof VectorCompositeType) {
return new VectorCompositeType(replaceUintTypeWithUintBigintType(type.elementType), type.length) as unknown as T;
}

return type;
}

0 comments on commit 1ad8f58

Please sign in to comment.