Skip to content

Commit

Permalink
feat(protoocl-parser): add valueSchemaToFieldLayoutHex (#1476)
Browse files Browse the repository at this point in the history
  • Loading branch information
holic authored Sep 14, 2023
1 parent bbcca44 commit 9ff4dd9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/silent-rice-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@latticexyz/protocol-parser": minor
---

Adds `valueSchemaToFieldLayoutHex` helper
1 change: 1 addition & 0 deletions packages/protocol-parser/src/fieldLayoutToHex.ts
Original file line number Diff line number Diff line change
@@ -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${[
Expand Down
21 changes: 21 additions & 0 deletions packages/protocol-parser/src/valueSchemaToFieldLayoutHex.ts
Original file line number Diff line number Diff line change
@@ -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")}`;
}

0 comments on commit 9ff4dd9

Please sign in to comment.