From 9ff4dd955fd6dca36eb15cfe7e46bb522d2e943b Mon Sep 17 00:00:00 2001 From: Kevin Ingersoll Date: Thu, 14 Sep 2023 13:01:03 +0100 Subject: [PATCH] feat(protoocl-parser): add valueSchemaToFieldLayoutHex (#1476) --- .changeset/silent-rice-argue.md | 5 +++++ .../protocol-parser/src/fieldLayoutToHex.ts | 1 + .../src/valueSchemaToFieldLayoutHex.ts | 21 +++++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 .changeset/silent-rice-argue.md create mode 100644 packages/protocol-parser/src/valueSchemaToFieldLayoutHex.ts diff --git a/.changeset/silent-rice-argue.md b/.changeset/silent-rice-argue.md new file mode 100644 index 0000000000..dfa242b1d2 --- /dev/null +++ b/.changeset/silent-rice-argue.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/protocol-parser": minor +--- + +Adds `valueSchemaToFieldLayoutHex` helper diff --git a/packages/protocol-parser/src/fieldLayoutToHex.ts b/packages/protocol-parser/src/fieldLayoutToHex.ts index 25432a52e7..de52c1504d 100644 --- a/packages/protocol-parser/src/fieldLayoutToHex.ts +++ b/packages/protocol-parser/src/fieldLayoutToHex.ts @@ -1,6 +1,7 @@ import { Hex } from "viem"; import { FieldLayout } from "./common"; +/** @deprecated use `valueSchemaToFieldLayoutHex` instead */ export function fieldLayoutToHex(fieldLayout: FieldLayout): Hex { const staticDataLength = fieldLayout.staticFieldLengths.reduce((totalLength, length) => totalLength + length, 0); return `0x${[ diff --git a/packages/protocol-parser/src/valueSchemaToFieldLayoutHex.ts b/packages/protocol-parser/src/valueSchemaToFieldLayoutHex.ts new file mode 100644 index 0000000000..dc10d95944 --- /dev/null +++ b/packages/protocol-parser/src/valueSchemaToFieldLayoutHex.ts @@ -0,0 +1,21 @@ +import { Hex } from "viem"; +import { ValueSchema } from "./common"; +import { isDynamicAbiType, isStaticAbiType, staticAbiTypeToByteLength } from "@latticexyz/schema-type"; + +// TODO: add tests once we have corresponding tests for FieldLayout.sol (bytes32 -> FieldLayout and vice versa) +export function valueSchemaToFieldLayoutHex(valueSchema: ValueSchema): Hex { + const staticFields = Object.values(valueSchema).filter(isStaticAbiType); + const dynamicFields = Object.values(valueSchema).filter(isDynamicAbiType); + + const staticFieldLengths = staticFields.map((fieldType) => staticAbiTypeToByteLength[fieldType]); + const staticDataLength = staticFieldLengths.reduce((dataLength, fieldLength) => dataLength + fieldLength, 0); + + return `0x${[ + staticDataLength.toString(16).padStart(4, "0"), + staticFields.length.toString(16).padStart(2, "0"), + dynamicFields.length.toString(16).padStart(2, "0"), + ...staticFieldLengths.map((fieldLength) => fieldLength.toString(16).padStart(2, "0")), + ] + .join("") + .padEnd(64, "0")}`; +}