From 17ea07b614d7bae295a6c58e1442a6af952c6c68 Mon Sep 17 00:00:00 2001 From: Kevin Ingersoll Date: Fri, 23 Jun 2023 02:34:15 -0700 Subject: [PATCH] refactor: move some utils to common, clean up (#1068) * move some utils into common, add linter * migrate things to new TableId * clean up * ugh vscode why * missed a couple return types --- .../src/mud/contractComponents.ts | 4 +- e2e/pnpm-lock.yaml | 2 +- .../src/layers/network/contractComponents.ts | 24 --------- .../src/mud/contractComponents.ts | 8 +-- .../src/mud/contractComponents.ts | 8 +-- .../src/mud/contractComponents.ts | 8 +-- packages/cli/src/commands/trace.ts | 4 +- .../cli/src/render-ts/renderRecsV1Tables.ts | 4 +- packages/common/.eslintrc | 6 +++ packages/common/package.json | 9 +++- packages/common/src/TableId.test.ts | 35 +++++++++++++ packages/common/src/TableId.ts | 37 ++++++++++++++ .../src/codegen/render-solidity/common.ts | 35 ++++++++----- .../codegen/render-solidity/renderEnums.ts | 2 +- .../render-solidity/renderTypeHelpers.ts | 12 ++--- .../src/codegen/utils/contractToInterface.ts | 11 ++++- packages/common/src/codegen/utils/format.ts | 4 +- .../src/codegen/utils/formatAndWrite.ts | 8 ++- .../common/src/codegen/utils/posixPath.ts | 2 +- packages/common/src/foundry/index.ts | 12 ++--- packages/common/src/index.ts | 1 + packages/common/src/utils/curry.ts | 5 +- packages/common/src/utils/index.ts | 2 + .../src/v2 => common/src/utils}/isDefined.ts | 0 .../src/v2 => common/src/utils}/isNotNull.ts | 0 packages/common/tsup.config.ts | 1 + packages/dev-tools/package.json | 1 + .../src/actions/TransactionSummary.tsx | 7 +-- packages/dev-tools/src/tables/useTables.ts | 3 +- packages/network/jest.config.js | 2 + packages/network/src/dev/observables.ts | 2 +- packages/network/src/types.ts | 3 +- packages/network/src/v2/common.ts | 2 +- .../network/src/v2/decodeStoreSetField.ts | 2 +- .../network/src/v2/decodeStoreSetRecord.ts | 11 +++-- packages/network/src/v2/ecsEventFromLog.ts | 4 +- packages/network/src/v2/fetchStoreEvents.ts | 2 +- .../network/src/v2/mode/syncTablesFromMode.ts | 3 +- .../network/src/v2/schemas/tableMetadata.ts | 10 ++-- .../network/src/v2/schemas/tableSchemas.ts | 10 ++-- .../src/v2/snapSync/getSnapSyncRecords.ts | 7 +-- packages/recs/jest.config.js | 1 + packages/std-client/package.json | 1 + .../store/contractComponents.ts | 14 +++--- .../world/contractComponents.ts | 22 ++++----- .../std-client/src/setup/setupMUDV2Network.ts | 5 +- packages/std-client/src/setup/utils.ts | 3 +- packages/utils/jest.config.js | 6 ++- packages/utils/package.json | 1 + packages/utils/src/v2/TableId.ts | 49 ------------------- packages/utils/src/v2/getTableIds.ts | 2 +- packages/utils/src/v2/index.ts | 3 -- pnpm-lock.yaml | 28 ++++++++++- .../client/src/mud/contractComponents.ts | 4 +- .../client/src/mud/contractComponents.ts | 4 +- .../client/src/mud/contractComponents.ts | 4 +- .../client/src/mud/contractComponents.ts | 4 +- 57 files changed, 272 insertions(+), 192 deletions(-) delete mode 100644 examples/minimal/packages/client-phaser/src/layers/network/contractComponents.ts create mode 100644 packages/common/.eslintrc create mode 100644 packages/common/src/TableId.test.ts create mode 100644 packages/common/src/TableId.ts create mode 100644 packages/common/src/index.ts rename packages/{utils/src/v2 => common/src/utils}/isDefined.ts (100%) rename packages/{utils/src/v2 => common/src/utils}/isNotNull.ts (100%) delete mode 100644 packages/utils/src/v2/TableId.ts diff --git a/e2e/packages/client-vanilla/src/mud/contractComponents.ts b/e2e/packages/client-vanilla/src/mud/contractComponents.ts index f01ed511ae..2c9f080f51 100644 --- a/e2e/packages/client-vanilla/src/mud/contractComponents.ts +++ b/e2e/packages/client-vanilla/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/e2e/pnpm-lock.yaml b/e2e/pnpm-lock.yaml index 882378b586..7eea9524e9 100644 --- a/e2e/pnpm-lock.yaml +++ b/e2e/pnpm-lock.yaml @@ -1,4 +1,4 @@ -lockfileVersion: '6.0' +lockfileVersion: '6.1' settings: autoInstallPeers: true diff --git a/examples/minimal/packages/client-phaser/src/layers/network/contractComponents.ts b/examples/minimal/packages/client-phaser/src/layers/network/contractComponents.ts deleted file mode 100644 index e48285282c..0000000000 --- a/examples/minimal/packages/client-phaser/src/layers/network/contractComponents.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ - -import { TableId } from "@latticexyz/utils"; -import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; - -export function defineContractComponents(world: World) { - return { - CounterTable: (() => { - const tableId = new TableId("mud", "counter"); - return defineComponent( - world, - { - value: RecsType.Number, - }, - { - metadata: { - contractId: tableId.toHexString(), - tableId: tableId.toString(), - }, - } - ); - })(), - }; -} diff --git a/examples/minimal/packages/client-phaser/src/mud/contractComponents.ts b/examples/minimal/packages/client-phaser/src/mud/contractComponents.ts index bedd2556a0..d84f563b1b 100644 --- a/examples/minimal/packages/client-phaser/src/mud/contractComponents.ts +++ b/examples/minimal/packages/client-phaser/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -29,7 +29,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -44,7 +44,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/examples/minimal/packages/client-react/src/mud/contractComponents.ts b/examples/minimal/packages/client-react/src/mud/contractComponents.ts index bedd2556a0..d84f563b1b 100644 --- a/examples/minimal/packages/client-react/src/mud/contractComponents.ts +++ b/examples/minimal/packages/client-react/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -29,7 +29,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -44,7 +44,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/examples/minimal/packages/client-vanilla/src/mud/contractComponents.ts b/examples/minimal/packages/client-vanilla/src/mud/contractComponents.ts index bedd2556a0..d84f563b1b 100644 --- a/examples/minimal/packages/client-vanilla/src/mud/contractComponents.ts +++ b/examples/minimal/packages/client-vanilla/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -29,7 +29,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -44,7 +44,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/packages/cli/src/commands/trace.ts b/packages/cli/src/commands/trace.ts index 2a95d1b4ba..8d6cef9546 100644 --- a/packages/cli/src/commands/trace.ts +++ b/packages/cli/src/commands/trace.ts @@ -5,7 +5,7 @@ import { ethers } from "ethers"; import { loadConfig } from "@latticexyz/config/node"; import { MUDError } from "@latticexyz/common/errors"; import { cast, getRpcUrl, getSrcDirectory } from "@latticexyz/common/foundry"; -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { StoreConfig } from "@latticexyz/store"; import { resolveWorldConfig, WorldConfig } from "@latticexyz/world"; import { IBaseWorld } from "@latticexyz/world/types/ethers-contracts/IBaseWorld"; @@ -74,7 +74,7 @@ const commandModule: CommandModule = { for (const name of names) { const systemSelector = new TableId(namespace, name); // Get the first field of `Systems` table (the table maps system name to its address and other data) - const address = await WorldContract.getField(systemsTableId.toHexString(), [systemSelector.toHexString()], 0); + const address = await WorldContract.getField(systemsTableId.toHex(), [systemSelector.toHex()], 0); labels.push({ name, address }); } diff --git a/packages/cli/src/render-ts/renderRecsV1Tables.ts b/packages/cli/src/render-ts/renderRecsV1Tables.ts index 9d88f93b6e..7b006e0fbb 100644 --- a/packages/cli/src/render-ts/renderRecsV1Tables.ts +++ b/packages/cli/src/render-ts/renderRecsV1Tables.ts @@ -5,7 +5,7 @@ export function renderRecsV1Tables(options: RecsV1TableOptions) { return `/* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -24,7 +24,7 @@ function renderDefineComponent(table: RecsV1TableOptions["tables"][number]) { return defineComponent(world, { ${table.fields.map(({ name, recsTypeString }) => `${name}: ${recsTypeString},`).join("")} }, { - metadata: { contractId: tableId.toHexString(), tableId: tableId.toString() }, + metadata: { contractId: tableId.toHex(), tableId: tableId.toString() }, }); })() `; diff --git a/packages/common/.eslintrc b/packages/common/.eslintrc new file mode 100644 index 0000000000..6db0063ad7 --- /dev/null +++ b/packages/common/.eslintrc @@ -0,0 +1,6 @@ +{ + "extends": ["../../.eslintrc"], + "rules": { + "@typescript-eslint/explicit-function-return-type": "error" + } +} diff --git a/packages/common/package.json b/packages/common/package.json index 3c1388de11..cd8f4d257c 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -10,6 +10,7 @@ "license": "MIT", "type": "module", "exports": { + ".": "./dist/index.js", "./codegen": "./dist/codegen.js", "./foundry": "./dist/foundry.js", "./type-utils": "./dist/type-utils.js", @@ -19,6 +20,9 @@ }, "typesVersions": { "*": { + "index": [ + "./src/index.ts" + ], "codegen": [ "./src/codegen/index.ts" ], @@ -45,7 +49,7 @@ "clean": "pnpm run clean:js", "clean:js": "rimraf dist", "dev": "tsup --watch", - "test": "vitest typecheck --run --passWithNoTests" + "test": "vitest typecheck --run --passWithNoTests && vitest --run" }, "dependencies": { "@latticexyz/schema-type": "workspace:*", @@ -53,7 +57,8 @@ "chalk": "^5.2.0", "execa": "^7.0.0", "prettier": "^2.8.4", - "prettier-plugin-solidity": "^1.1.2" + "prettier-plugin-solidity": "^1.1.2", + "viem": "1.0.6" }, "devDependencies": { "@types/node": "^18.15.11", diff --git a/packages/common/src/TableId.test.ts b/packages/common/src/TableId.test.ts new file mode 100644 index 0000000000..c1426ec150 --- /dev/null +++ b/packages/common/src/TableId.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from "vitest"; +import { TableId } from "./TableId"; + +describe("TableId", () => { + it("can convert to hex string", () => { + const tableId = new TableId("namespace", "name"); + expect(tableId.toHex()).toMatchInlineSnapshot( + '"0x6e616d657370616365000000000000006e616d65000000000000000000000000"' + ); + }); + + it("throws when converting namespaces >16 bytes", () => { + const tableId = new TableId("AVeryLongNamespace", "name"); + expect(() => tableId.toHex()).toThrowErrorMatchingInlineSnapshot(` + "Size cannot exceed 16 bytes. Given size: 18 bytes. + + Version: viem@1.0.6" + `); + }); + + it("throws when converting names >16 bytes", () => { + const tableId = new TableId("namespace", "AnUnnecessarilyLongName"); + expect(() => tableId.toHex()).toThrowErrorMatchingInlineSnapshot(` + "Size cannot exceed 16 bytes. Given size: 23 bytes. + + Version: viem@1.0.6" + `); + }); + + it("can convert from hex string", () => { + const tableId = TableId.fromHex("0x6e616d657370616365000000000000006e616d65000000000000000000000000"); + expect(tableId.namespace).toMatchInlineSnapshot('"namespace"'); + expect(tableId.name).toMatchInlineSnapshot('"name"'); + }); +}); diff --git a/packages/common/src/TableId.ts b/packages/common/src/TableId.ts new file mode 100644 index 0000000000..afde342885 --- /dev/null +++ b/packages/common/src/TableId.ts @@ -0,0 +1,37 @@ +import { Hex, stringToHex, hexToString, sliceHex, concatHex } from "viem"; + +export class TableId { + namespace: string; + name: string; + + constructor(namespace: string, name: string) { + this.namespace = namespace; + this.name = name; + } + + toString(): string { + return `TableId<${this.namespace || "[empty]"}:${this.name || "[empty]"}>`; + } + + toHex(): Hex { + return TableId.toHex(this.namespace, this.name); + } + + static toHex(namespace: string, name: string): Hex { + return concatHex([stringToHex(namespace, { size: 16 }), stringToHex(name, { size: 16 })]); + } + + static fromHex(hex: Hex): TableId { + const namespace = hexToString(sliceHex(hex, 0, 16)).replace(/\0+$/, ""); + const name = hexToString(sliceHex(hex, 16, 32)).replace(/\0+$/, ""); + return new TableId(namespace, name); + } + + /** @deprecated Don't use this! This is a temporary hack for v2<>v1 compatibility until we can write v2 client libraries. This is here so it stays close to the formatting of `toString()` above. */ + static parse(tableIdString: string): TableId | null { + const match = tableIdString.match(/^TableId<(.+?):(.+?)>$/); + if (!match) return null; + const [, namespace, name] = match; + return new TableId(namespace === "[empty]" ? "" : namespace, name === "[empty]" ? "" : name); + } +} diff --git a/packages/common/src/codegen/render-solidity/common.ts b/packages/common/src/codegen/render-solidity/common.ts index 9f57c4e1a4..e453b53c2c 100644 --- a/packages/common/src/codegen/render-solidity/common.ts +++ b/packages/common/src/codegen/render-solidity/common.ts @@ -17,14 +17,14 @@ pragma solidity >=0.8.0; /** * Renders a list of lines */ -export function renderList(list: T[], renderItem: (item: T, index: number) => string) { +export function renderList(list: T[], renderItem: (item: T, index: number) => string): string { return internalRenderList("", list, renderItem); } /** * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones */ -export function renderArguments(args: (string | undefined)[]) { +export function renderArguments(args: (string | undefined)[]): string { const filteredArgs = args.filter((arg) => arg !== undefined && arg !== "") as string[]; return internalRenderList(",", filteredArgs, (arg) => arg); } @@ -35,7 +35,13 @@ export function renderCommonData({ }: { staticResourceData?: StaticResourceData; keyTuple: RenderKeyTuple[]; -}) { +}): { + _tableId: string; + _typedTableId: string; + _keyArgs: string; + _typedKeyArgs: string; + _keyTupleDefinition: string; +} { // static resource means static tableId as well, and no tableId arguments const _tableId = staticResourceData ? "" : "_tableId"; const _typedTableId = staticResourceData ? "" : "bytes32 _tableId"; @@ -58,7 +64,7 @@ export function renderCommonData({ } /** For 2 paths which are relative to a common root, create a relative import path from one to another */ -export function solidityRelativeImportPath(fromPath: string, usedInPath: string) { +export function solidityRelativeImportPath(fromPath: string, usedInPath: string): string { // 1st "./" must be added because path strips it, // but solidity expects it unless there's "../" ("./../" is fine). // 2nd and 3rd "./" forcefully avoid absolute paths (everything is relative to `src`). @@ -69,7 +75,7 @@ export function solidityRelativeImportPath(fromPath: string, usedInPath: string) * Aggregates, deduplicates and renders imports for symbols per path. * Identical symbols from different paths are NOT handled, they should be checked before rendering. */ -export function renderImports(imports: ImportDatum[]) { +export function renderImports(imports: ImportDatum[]): string { return renderAbsoluteImports( imports.map((importDatum) => { if ("path" in importDatum) { @@ -88,7 +94,7 @@ export function renderImports(imports: ImportDatum[]) { * Aggregates, deduplicates and renders imports for symbols per path. * Identical symbols from different paths are NOT handled, they should be checked before rendering. */ -export function renderRelativeImports(imports: RelativeImportDatum[]) { +export function renderRelativeImports(imports: RelativeImportDatum[]): string { return renderAbsoluteImports( imports.map(({ symbol, fromPath, usedInPath }) => ({ symbol, @@ -101,7 +107,7 @@ export function renderRelativeImports(imports: RelativeImportDatum[]) { * Aggregates, deduplicates and renders imports for symbols per path. * Identical symbols from different paths are NOT handled, they should be checked before rendering. */ -export function renderAbsoluteImports(imports: AbsoluteImportDatum[]) { +export function renderAbsoluteImports(imports: AbsoluteImportDatum[]): string { // Aggregate symbols by import path, also deduplicating them const aggregatedImports = new Map>(); for (const { symbol, path } of imports) { @@ -127,7 +133,7 @@ export function renderWithStore( _commentSuffix: string, _untypedStore: string | undefined ) => string -) { +): string { let result = ""; result += callback(undefined, "StoreSwitch", "", undefined); @@ -138,7 +144,10 @@ export function renderWithStore( return result; } -export function renderTableId(staticResourceData: StaticResourceData) { +export function renderTableId(staticResourceData: StaticResourceData): { + hardcodedTableId: string; + tableIdDefinition: string; +} { const hardcodedTableId = `bytes32(abi.encodePacked(bytes16("${staticResourceData.namespace}"), bytes16("${staticResourceData.name}")))`; const tableIdDefinition = ` @@ -151,7 +160,7 @@ export function renderTableId(staticResourceData: StaticResourceData) { }; } -export function renderValueTypeToBytes32(name: string, { typeUnwrap, internalTypeId }: RenderType) { +export function renderValueTypeToBytes32(name: string, { typeUnwrap, internalTypeId }: RenderType): string { const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name; if (internalTypeId === "bytes32") { @@ -171,7 +180,11 @@ export function renderValueTypeToBytes32(name: string, { typeUnwrap, internalTyp } } -function internalRenderList(lineTerminator: string, list: T[], renderItem: (item: T, index: number) => string) { +function internalRenderList( + lineTerminator: string, + list: T[], + renderItem: (item: T, index: number) => string +): string { return list .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? "" : lineTerminator)) .join("\n"); diff --git a/packages/common/src/codegen/render-solidity/renderEnums.ts b/packages/common/src/codegen/render-solidity/renderEnums.ts index a666ce6586..acf62e15b8 100644 --- a/packages/common/src/codegen/render-solidity/renderEnums.ts +++ b/packages/common/src/codegen/render-solidity/renderEnums.ts @@ -1,7 +1,7 @@ import { renderArguments, renderList, renderedSolidityHeader } from "./common"; import { RenderEnum } from "./types"; -export function renderEnums(enums: RenderEnum[]) { +export function renderEnums(enums: RenderEnum[]): string { let result = renderedSolidityHeader; result += renderList( diff --git a/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts b/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts index 125bf81bc0..c44d246ea8 100644 --- a/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts +++ b/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts @@ -1,6 +1,6 @@ import { RenderField, RenderKeyTuple, RenderType } from "./types"; -export function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }) { +export function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }): string { const { fields, keyTuple } = options; let result = ""; @@ -32,9 +32,9 @@ export function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: Re return result; } -function getWrappingHelpers(array: RenderType[]) { - const wrappers = new Map(); - const unwrappers = new Map(); +function getWrappingHelpers(array: RenderType[]): string[] { + const wrappers = new Map(); + const unwrappers = new Map(); for (const { typeWrappingData, typeWrap, typeUnwrap, internalTypeId } of array) { if (!typeWrappingData) continue; const { kind } = typeWrappingData; @@ -54,7 +54,7 @@ function renderWrapperStaticArray( elementType: string, staticLength: number, internalTypeId: string -) { +): string { // WARNING: ensure this still works if changing major solidity versions! // (the memory layout for static arrays may change) return ` @@ -76,7 +76,7 @@ function renderUnwrapperStaticArray( elementType: string, staticLength: number, internalTypeId: string -) { +): string { // byte length for memory copying (more efficient than a loop) const byteLength = staticLength * 32; // TODO to optimize memory usage consider generalizing TightEncoder to a render-time utility diff --git a/packages/common/src/codegen/utils/contractToInterface.ts b/packages/common/src/codegen/utils/contractToInterface.ts index 9d289aa552..6ec50f0ea3 100644 --- a/packages/common/src/codegen/utils/contractToInterface.ts +++ b/packages/common/src/codegen/utils/contractToInterface.ts @@ -26,7 +26,14 @@ interface SymbolImport { * @param contractName name of the contract * @returns interface data */ -export function contractToInterface(data: string, contractName: string) { +export function contractToInterface( + data: string, + contractName: string +): { + functions: ContractInterfaceFunction[]; + errors: ContractInterfaceError[]; + symbolImports: SymbolImport[]; +} { const ast = parse(data); let withContract = false; @@ -178,7 +185,7 @@ function typeNameToSymbols(typeName: TypeName | null): string[] { // symbols used for args/returns must always be imported from an auxiliary file. // To avoid parsing the entire project to build dependencies, // symbols must be imported with an explicit `import { symbol } from ...` -function symbolsToImports(ast: SourceUnit, symbols: string[]) { +function symbolsToImports(ast: SourceUnit, symbols: string[]): SymbolImport[] { const imports: SymbolImport[] = []; for (const symbol of symbols) { diff --git a/packages/common/src/codegen/utils/format.ts b/packages/common/src/codegen/utils/format.ts index 1070eeddb3..d987ebb71a 100644 --- a/packages/common/src/codegen/utils/format.ts +++ b/packages/common/src/codegen/utils/format.ts @@ -2,7 +2,7 @@ import chalk from "chalk"; import prettier from "prettier"; import prettierPluginSolidity from "prettier-plugin-solidity"; -export async function formatSolidity(content: string, prettierConfigPath?: string) { +export async function formatSolidity(content: string, prettierConfigPath?: string): Promise { let config; if (prettierConfigPath) { config = await prettier.resolveConfig(prettierConfigPath); @@ -32,7 +32,7 @@ export async function formatSolidity(content: string, prettierConfigPath?: strin } } -export async function formatTypescript(content: string) { +export async function formatTypescript(content: string): Promise { return prettier.format(content, { parser: "typescript", }); diff --git a/packages/common/src/codegen/utils/formatAndWrite.ts b/packages/common/src/codegen/utils/formatAndWrite.ts index fbe2ffa2a2..23786bb584 100644 --- a/packages/common/src/codegen/utils/formatAndWrite.ts +++ b/packages/common/src/codegen/utils/formatAndWrite.ts @@ -2,7 +2,7 @@ import { mkdirSync, writeFileSync } from "fs"; import { dirname } from "path"; import { formatSolidity, formatTypescript } from "./format"; -export async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string) { +export async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string): Promise { const formattedOutput = await formatSolidity(output); mkdirSync(dirname(fullOutputPath), { recursive: true }); @@ -11,7 +11,11 @@ export async function formatAndWriteSolidity(output: string, fullOutputPath: str console.log(`${logPrefix}: ${fullOutputPath}`); } -export async function formatAndWriteTypescript(output: string, fullOutputPath: string, logPrefix: string) { +export async function formatAndWriteTypescript( + output: string, + fullOutputPath: string, + logPrefix: string +): Promise { const formattedOutput = await formatTypescript(output); mkdirSync(dirname(fullOutputPath), { recursive: true }); diff --git a/packages/common/src/codegen/utils/posixPath.ts b/packages/common/src/codegen/utils/posixPath.ts index ec1b6f372c..c267fbcab4 100644 --- a/packages/common/src/codegen/utils/posixPath.ts +++ b/packages/common/src/codegen/utils/posixPath.ts @@ -3,6 +3,6 @@ * This should be used for generating Solidity files that will be consumed by solc, * because solc expects `/` as path separator, but path.join produces `\` if the user is on windows. */ -export function posixPath(path: string) { +export function posixPath(path: string): string { return path.replace(/\\/g, "/"); } diff --git a/packages/common/src/foundry/index.ts b/packages/common/src/foundry/index.ts index 2f1c3e46f0..c46dbd1aef 100644 --- a/packages/common/src/foundry/index.ts +++ b/packages/common/src/foundry/index.ts @@ -17,7 +17,7 @@ export interface ForgeConfig { /** * Get forge config as a parsed json object. */ -export async function getForgeConfig(profile?: string) { +export async function getForgeConfig(profile?: string): Promise { const { stdout } = await execa("forge", ["config", "--json"], { stdio: ["inherit", "pipe", "pipe"], env: { FOUNDRY_PROFILE: profile }, @@ -30,7 +30,7 @@ export async function getForgeConfig(profile?: string) { * Get the value of "src" from forge config. * The path to the contract sources relative to the root of the project. */ -export async function getSrcDirectory(profile?: string) { +export async function getSrcDirectory(profile?: string): Promise { return (await getForgeConfig(profile)).src; } @@ -38,7 +38,7 @@ export async function getSrcDirectory(profile?: string) { * Get the value of "script" from forge config. * The path to the contract sources relative to the root of the project. */ -export async function getScriptDirectory(profile?: string) { +export async function getScriptDirectory(profile?: string): Promise { return (await getForgeConfig(profile)).script; } @@ -46,7 +46,7 @@ export async function getScriptDirectory(profile?: string) { * Get the value of "test" from forge config. * The path to the test contract sources relative to the root of the project. */ -export async function getTestDirectory(profile?: string) { +export async function getTestDirectory(profile?: string): Promise { return (await getForgeConfig(profile)).test; } @@ -54,7 +54,7 @@ export async function getTestDirectory(profile?: string) { * Get the value of "out" from forge config. * The path to put contract artifacts in, relative to the root of the project. */ -export async function getOutDirectory(profile?: string) { +export async function getOutDirectory(profile?: string): Promise { return (await getForgeConfig(profile)).out; } @@ -63,7 +63,7 @@ export async function getOutDirectory(profile?: string) { * @param profile The foundry profile to use * @returns The rpc url */ -export async function getRpcUrl(profile?: string) { +export async function getRpcUrl(profile?: string): Promise { return (await getForgeConfig(profile)).eth_rpc_url || "http://127.0.0.1:8545"; } diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts new file mode 100644 index 0000000000..8a8f194442 --- /dev/null +++ b/packages/common/src/index.ts @@ -0,0 +1 @@ +export * from "./TableId"; diff --git a/packages/common/src/utils/curry.ts b/packages/common/src/utils/curry.ts index f799694717..daaf4a5785 100644 --- a/packages/common/src/utils/curry.ts +++ b/packages/common/src/utils/curry.ts @@ -1,4 +1,7 @@ -export function curry any, P extends any[]>(func: F, ...partialParams: P) { +export function curry any, P extends any[]>( + func: F, + ...partialParams: P +): CurryParams { return ((...args: any[]) => func(...partialParams, ...args)) as CurryParams; } diff --git a/packages/common/src/utils/index.ts b/packages/common/src/utils/index.ts index b20ab7a7a8..b2231070d3 100644 --- a/packages/common/src/utils/index.ts +++ b/packages/common/src/utils/index.ts @@ -1,2 +1,4 @@ export * from "./assertExhaustive"; export * from "./curry"; +export * from "./isDefined"; +export * from "./isNotNull"; diff --git a/packages/utils/src/v2/isDefined.ts b/packages/common/src/utils/isDefined.ts similarity index 100% rename from packages/utils/src/v2/isDefined.ts rename to packages/common/src/utils/isDefined.ts diff --git a/packages/utils/src/v2/isNotNull.ts b/packages/common/src/utils/isNotNull.ts similarity index 100% rename from packages/utils/src/v2/isNotNull.ts rename to packages/common/src/utils/isNotNull.ts diff --git a/packages/common/tsup.config.ts b/packages/common/tsup.config.ts index 1e62f1f90e..4f3c616f78 100644 --- a/packages/common/tsup.config.ts +++ b/packages/common/tsup.config.ts @@ -2,6 +2,7 @@ import { defineConfig } from "tsup"; export default defineConfig({ entry: { + index: "src/index.ts", codegen: "src/codegen/index.ts", foundry: "src/foundry/index.ts", "type-utils": "src/type-utils/index.ts", diff --git a/packages/dev-tools/package.json b/packages/dev-tools/package.json index e7c9a7699a..96192c09ba 100644 --- a/packages/dev-tools/package.json +++ b/packages/dev-tools/package.json @@ -22,6 +22,7 @@ "test": "tsc --noEmit" }, "dependencies": { + "@latticexyz/common": "workspace:*", "@latticexyz/network": "workspace:*", "@latticexyz/react": "workspace:*", "@latticexyz/std-client": "workspace:*", diff --git a/packages/dev-tools/src/actions/TransactionSummary.tsx b/packages/dev-tools/src/actions/TransactionSummary.tsx index 081cf7cca2..7e2db21319 100644 --- a/packages/dev-tools/src/actions/TransactionSummary.tsx +++ b/packages/dev-tools/src/actions/TransactionSummary.tsx @@ -1,6 +1,7 @@ -import { decodeEventLog, decodeFunctionData, toBytes, Hex, AbiEventSignatureNotFoundError } from "viem"; +import { decodeEventLog, decodeFunctionData, Hex, AbiEventSignatureNotFoundError } from "viem"; import { twMerge } from "tailwind-merge"; -import { TableId, isDefined } from "@latticexyz/utils"; +import { isDefined } from "@latticexyz/common/utils"; +import { TableId } from "@latticexyz/common"; import { keyTupleToEntityID } from "@latticexyz/network/dev"; import { useStore } from "../useStore"; import { PendingIcon } from "../icons/PendingIcon"; @@ -135,7 +136,7 @@ export function TransactionSummary({ hash }: Props) { {events.map(({ eventName, args }, i) => { - const table = TableId.fromBytes32(toBytes((args as any).table)); + const table = TableId.fromHex((args as any).table); return ( diff --git a/packages/dev-tools/src/tables/useTables.ts b/packages/dev-tools/src/tables/useTables.ts index 61ad411f48..2f3df9993e 100644 --- a/packages/dev-tools/src/tables/useTables.ts +++ b/packages/dev-tools/src/tables/useTables.ts @@ -1,4 +1,5 @@ -import { TableId, isDefined } from "@latticexyz/utils"; +import { isDefined } from "@latticexyz/common/utils"; +import { TableId } from "@latticexyz/common"; import { useStore } from "../useStore"; export function useTables() { diff --git a/packages/network/jest.config.js b/packages/network/jest.config.js index 07a2f6b31c..5f659ae21b 100644 --- a/packages/network/jest.config.js +++ b/packages/network/jest.config.js @@ -8,7 +8,9 @@ export default { // fix TS build issues "^(..?/.*).js$": "$1", // jest can't handle esm imports, so we import the typescript source instead + "^@latticexyz/common$": "/../common/src/index.ts", "^@latticexyz/common/chains$": "/../common/src/chains/index.ts", + "^@latticexyz/common/utils$": "/../common/src/utils/index.ts", "^@latticexyz/recs$": "/../recs/src/index.ts", "^@latticexyz/schema-type$": "/../schema-type/src/typescript/index.ts", "^@latticexyz/schema-type/deprecated$": "/../schema-type/src/typescript/deprecated/index.ts", diff --git a/packages/network/src/dev/observables.ts b/packages/network/src/dev/observables.ts index e61dbcc050..ba424439a7 100644 --- a/packages/network/src/dev/observables.ts +++ b/packages/network/src/dev/observables.ts @@ -1,7 +1,7 @@ import { BehaviorSubject, Subject } from "rxjs"; import type { PublicClient, WalletClient, Chain } from "viem"; import type { CacheStore } from "../workers"; -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { StoreEvent, EphemeralEvent } from "../v2/common"; // TODO: connection status? diff --git a/packages/network/src/types.ts b/packages/network/src/types.ts index b04abb7565..a256058ce3 100644 --- a/packages/network/src/types.ts +++ b/packages/network/src/types.ts @@ -2,7 +2,8 @@ import { Result } from "@ethersproject/abi"; import { ExternalProvider } from "@ethersproject/providers"; import { Components, ComponentValue, Entity, SchemaOf } from "@latticexyz/recs"; import { TxMetadata } from "@latticexyz/services/ecs-stream"; -import { Cached, TableId } from "@latticexyz/utils"; +import { Cached } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { BaseContract, BigNumber, ContractInterface } from "ethers"; import { Observable } from "rxjs"; import { SyncState } from "./workers"; diff --git a/packages/network/src/v2/common.ts b/packages/network/src/v2/common.ts index 2fe2874665..47622e274a 100644 --- a/packages/network/src/v2/common.ts +++ b/packages/network/src/v2/common.ts @@ -1,5 +1,5 @@ +import { TableId } from "@latticexyz/common"; import { SchemaType } from "@latticexyz/schema-type/deprecated"; -import { TableId } from "@latticexyz/utils"; export const schemaTableId = new TableId("mudstore", "schema"); export const metadataTableId = new TableId("mudstore", "StoreMetadata"); diff --git a/packages/network/src/v2/decodeStoreSetField.ts b/packages/network/src/v2/decodeStoreSetField.ts index 49e5b90542..8ad17dbf33 100644 --- a/packages/network/src/v2/decodeStoreSetField.ts +++ b/packages/network/src/v2/decodeStoreSetField.ts @@ -1,5 +1,5 @@ import { ComponentValue } from "@latticexyz/recs"; -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { Contract } from "ethers"; import { registerSchema } from "./schemas/tableSchemas"; import { registerMetadata } from "./schemas/tableMetadata"; diff --git a/packages/network/src/v2/decodeStoreSetRecord.ts b/packages/network/src/v2/decodeStoreSetRecord.ts index db14c3f890..8344617641 100644 --- a/packages/network/src/v2/decodeStoreSetRecord.ts +++ b/packages/network/src/v2/decodeStoreSetRecord.ts @@ -1,10 +1,11 @@ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { Contract, utils } from "ethers"; import { registerSchema } from "./schemas/tableSchemas"; import { registerMetadata } from "./schemas/tableMetadata"; import { decodeData } from "./schemas/decodeData"; import { schemaTableId, metadataTableId } from "./common"; import { decodeKeyTuple } from "./schemas/decodeKeyTuple"; +import { Hex } from "viem"; export async function decodeStoreSetRecord( contract: Contract, @@ -18,7 +19,7 @@ export async function decodeStoreSetRecord( namedKey?: Record; }> { // registerSchema event - if (table.toHexString() === schemaTableId.toHexString()) { + if (table.toHex() === schemaTableId.toHex()) { const [tableForSchema, ...otherKeys] = keyTuple; if (otherKeys.length) { console.warn( @@ -26,14 +27,14 @@ export async function decodeStoreSetRecord( { table, keyTuple } ); } - registerSchema(contract, TableId.fromBytes32(utils.arrayify(tableForSchema)), data); + registerSchema(contract, TableId.fromHex(tableForSchema as Hex), data); } const { keySchema, valueSchema } = await registerSchema(contract, table); const indexedValues = decodeData(valueSchema, data); const indexedKey = decodeKeyTuple(keySchema, keyTuple); - if (table.toHexString() === metadataTableId.toHexString()) { + if (table.toHex() === metadataTableId.toHex()) { const [tableForMetadata, ...otherKeys] = keyTuple; if (otherKeys.length) { console.warn( @@ -43,7 +44,7 @@ export async function decodeStoreSetRecord( } const tableName = indexedValues[0]; const [fieldNames] = utils.defaultAbiCoder.decode(["string[]"], indexedValues[1]); - registerMetadata(contract, TableId.fromBytes32(utils.arrayify(tableForMetadata)), { tableName, fieldNames }); + registerMetadata(contract, TableId.fromHex(tableForMetadata as Hex), { tableName, fieldNames }); } const metadata = await registerMetadata(contract, table); diff --git a/packages/network/src/v2/ecsEventFromLog.ts b/packages/network/src/v2/ecsEventFromLog.ts index 9d7e1d88dc..e650795898 100644 --- a/packages/network/src/v2/ecsEventFromLog.ts +++ b/packages/network/src/v2/ecsEventFromLog.ts @@ -1,7 +1,7 @@ import { Contract, utils } from "ethers"; import { Log } from "@ethersproject/providers"; import { LogDescription } from "@ethersproject/abi"; -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { NetworkComponentUpdate, NetworkEvents } from "../types"; import { decodeStoreSetRecord } from "./decodeStoreSetRecord"; import { decodeStoreSetField } from "./decodeStoreSetField"; @@ -20,7 +20,7 @@ export const ecsEventFromLog = async ( const { blockNumber, transactionHash, logIndex } = log; const { args, name } = parsedLog; - const tableId = TableId.fromBytes32(utils.arrayify(args.table)); + const tableId = TableId.fromHex(args.table); const component = tableId.toString(); const entity = keyTupleToEntityID(args.key); diff --git a/packages/network/src/v2/fetchStoreEvents.ts b/packages/network/src/v2/fetchStoreEvents.ts index a900a2177d..ee3d262dc0 100644 --- a/packages/network/src/v2/fetchStoreEvents.ts +++ b/packages/network/src/v2/fetchStoreEvents.ts @@ -1,7 +1,7 @@ import { Contract } from "ethers"; import { NetworkComponentUpdate } from "../types"; import orderBy from "lodash/orderBy"; -import { isDefined } from "@latticexyz/utils"; +import { isDefined } from "@latticexyz/common/utils"; import { ephemeralEvents, storeEvents } from "./common"; import { ecsEventFromLog } from "./ecsEventFromLog"; diff --git a/packages/network/src/v2/mode/syncTablesFromMode.ts b/packages/network/src/v2/mode/syncTablesFromMode.ts index a7564eecdf..a350e98b4e 100644 --- a/packages/network/src/v2/mode/syncTablesFromMode.ts +++ b/packages/network/src/v2/mode/syncTablesFromMode.ts @@ -1,7 +1,8 @@ import { ComponentValue } from "@latticexyz/recs"; import { AbiTypeToSchemaType, encodeSchema } from "@latticexyz/schema-type/deprecated"; import { QueryLayerClient } from "@latticexyz/services/mode"; -import { arrayToHex, TableId } from "@latticexyz/utils"; +import { arrayToHex } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { Contract } from "ethers"; import { NetworkEvents } from "../../types"; diff --git a/packages/network/src/v2/schemas/tableMetadata.ts b/packages/network/src/v2/schemas/tableMetadata.ts index 41e3046ff3..93c0aca671 100644 --- a/packages/network/src/v2/schemas/tableMetadata.ts +++ b/packages/network/src/v2/schemas/tableMetadata.ts @@ -1,4 +1,4 @@ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { Contract, utils } from "ethers"; import { metadataTableId, schemaTableId, TableMetadata } from "../common"; import { decodeData } from "./decodeData"; @@ -12,7 +12,7 @@ export const metadataCache: Partial | undefined { - const cacheKey = `${world.address}:${table.toHexString()}` as const; + const cacheKey = `${world.address}:${table.toHex()}` as const; return metadataCache[cacheKey]; } @@ -21,7 +21,7 @@ export function registerMetadata( table: TableId, metadata?: TableMetadata ): Promise { - const cacheKey = `${world.address}:${table.toHexString()}` as const; + const cacheKey = `${world.address}:${table.toHex()}` as const; const cachedMetadataPromise = metadataCache[cacheKey]; if (cachedMetadataPromise) { @@ -50,7 +50,7 @@ export function registerMetadata( // TODO: populate from ECS cache before fetching from RPC // Skip lazily fetching internal tables - if (table.toHexString() === schemaTableId.toHexString() || table.toHexString() === metadataTableId.toHexString()) { + if (table.toHex() === schemaTableId.toHex() || table.toHex() === metadataTableId.toHex()) { return Promise.resolve(undefined); } @@ -59,7 +59,7 @@ export function registerMetadata( registerSchema(world, metadataTableId), // TODO: figure out how to pass in rawSchema, it was giving me "incorrect length" errors before // we still have to do both calls though, and this is a getter, so this should be fine - (world as IStore)["getRecord(bytes32,bytes32[])"](metadataTableId.toHexString(), [table.toHexString()]), + (world as IStore)["getRecord(bytes32,bytes32[])"](metadataTableId.toHex(), [table.toHex()]), ]).then(([{ valueSchema }, metadataRecord]) => { if (valueSchema.isEmpty) { console.warn("Metadata schema not found", { table: metadataTableId.toString(), world: world.address }); diff --git a/packages/network/src/v2/schemas/tableSchemas.ts b/packages/network/src/v2/schemas/tableSchemas.ts index a3fc1bc4f6..f27ea908c6 100644 --- a/packages/network/src/v2/schemas/tableSchemas.ts +++ b/packages/network/src/v2/schemas/tableSchemas.ts @@ -1,5 +1,5 @@ import { Contract } from "ethers"; -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { TableSchema } from "../common"; import { decodeSchema } from "./decodeSchema"; import { IStore } from "@latticexyz/store/types/ethers-contracts/IStore.sol/IStore"; @@ -11,12 +11,12 @@ const schemaCache: Partial>> // the Contract arguments below assume that they're bound to a provider export function getSchema(world: IStore, table: TableId): Promise | undefined { - const cacheKey = `${world.address}:${table.toHexString()}` as const; + const cacheKey = `${world.address}:${table.toHex()}` as const; return schemaCache[cacheKey]; } export function registerSchema(world: Contract, table: TableId, rawSchema?: string): Promise { - const cacheKey = `${world.address}:${table.toHexString()}` as const; + const cacheKey = `${world.address}:${table.toHex()}` as const; const existingSchema = schemaCache[cacheKey]; if (existingSchema) { @@ -47,8 +47,8 @@ export function registerSchema(world: Contract, table: TableId, rawSchema?: stri console.log("fetching schema for table", { table: table.toString(), world: world.address }); const store = world as IStore; - const rawKeySchemaPromise = store.getKeySchema(table.toHexString()); - const rawValueSchemaPromise = store.getSchema(table.toHexString()); + const rawKeySchemaPromise = store.getKeySchema(table.toHex()); + const rawValueSchemaPromise = store.getSchema(table.toHex()); const rawSchemaPromise = Promise.all([rawKeySchemaPromise, rawValueSchemaPromise]).then( ([rawKeySchema, rawValueSchema]) => rawValueSchema + rawKeySchema.substring(2) ); diff --git a/packages/network/src/v2/snapSync/getSnapSyncRecords.ts b/packages/network/src/v2/snapSync/getSnapSyncRecords.ts index f16ff3d67b..9d4f003937 100644 --- a/packages/network/src/v2/snapSync/getSnapSyncRecords.ts +++ b/packages/network/src/v2/snapSync/getSnapSyncRecords.ts @@ -1,4 +1,5 @@ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; +import { Hex } from "viem"; import snapSyncSystemAbi from "./snapSyncSystemAbi"; import { Contract, Signer, providers } from "ethers"; import { RawTableRecord } from "../../types"; @@ -12,7 +13,7 @@ export async function getSnapSyncRecords( const snapSyncContract = new Contract(worldAddress, snapSyncSystemAbi, signerOrProvider); const chunkSize = 100; - const tableIds = tables.map((table) => table.toHexString()); + const tableIds = tables.map((table) => table.toHex()); const tableRecords = [] as RawTableRecord[]; for (const tableId of tableIds) { const numKeys = ( @@ -34,7 +35,7 @@ export async function getSnapSyncRecords( }); const transformedRecords = records.map((record: [string, string[], string]) => { return { - tableId: TableId.fromHexString(record[0]), + tableId: TableId.fromHex(record[0] as Hex), keyTuple: record[1], value: record[2], }; diff --git a/packages/recs/jest.config.js b/packages/recs/jest.config.js index 0ee61b37c8..9ece48b627 100644 --- a/packages/recs/jest.config.js +++ b/packages/recs/jest.config.js @@ -6,6 +6,7 @@ export default { roots: ["tests"], moduleNameMapper: { // jest can't handle esm imports, so we import the typescript source instead + "^@latticexyz/common$": "/../common/src/index.ts", "^@latticexyz/utils$": "/../utils/src/index.ts", }, }; diff --git a/packages/std-client/package.json b/packages/std-client/package.json index 1115978d19..a07553d842 100644 --- a/packages/std-client/package.json +++ b/packages/std-client/package.json @@ -37,6 +37,7 @@ "dependencies": { "@ethersproject/providers": "^5.7.2", "@latticexyz/cli": "workspace:*", + "@latticexyz/common": "workspace:*", "@latticexyz/config": "workspace:*", "@latticexyz/network": "workspace:*", "@latticexyz/recs": "workspace:*", diff --git a/packages/std-client/src/mud-definitions/store/contractComponents.ts b/packages/std-client/src/mud-definitions/store/contractComponents.ts index 12f46452ff..42001c8c29 100644 --- a/packages/std-client/src/mud-definitions/store/contractComponents.ts +++ b/packages/std-client/src/mud-definitions/store/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -29,7 +29,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -45,7 +45,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -63,7 +63,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -79,7 +79,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -94,7 +94,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/packages/std-client/src/mud-definitions/world/contractComponents.ts b/packages/std-client/src/mud-definitions/world/contractComponents.ts index 8e788fe989..84d3e5457e 100644 --- a/packages/std-client/src/mud-definitions/world/contractComponents.ts +++ b/packages/std-client/src/mud-definitions/world/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -29,7 +29,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -44,7 +44,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -60,7 +60,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -75,7 +75,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -90,7 +90,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -105,7 +105,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -122,7 +122,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -141,7 +141,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } @@ -157,7 +157,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/packages/std-client/src/setup/setupMUDV2Network.ts b/packages/std-client/src/setup/setupMUDV2Network.ts index 217b401ffd..aa666426c3 100644 --- a/packages/std-client/src/setup/setupMUDV2Network.ts +++ b/packages/std-client/src/setup/setupMUDV2Network.ts @@ -13,7 +13,8 @@ import { import { BehaviorSubject, concatMap, from, Subject } from "rxjs"; import { Components, defineComponent, Type, World } from "@latticexyz/recs"; import { computed } from "mobx"; -import { keccak256, TableId } from "@latticexyz/utils"; +import { keccak256 } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { World as WorldContract } from "@latticexyz/world/types/ethers-contracts/World"; import { IWorldKernel__factory } from "@latticexyz/world/types/ethers-contracts/factories/IWorldKernel.sol/IWorldKernel__factory"; import { defineStringComponent } from "../components"; @@ -80,7 +81,7 @@ export async function setupMUDV2Network/../common/src/index.ts", + }, }; diff --git a/packages/utils/package.json b/packages/utils/package.json index d6b96a43ab..d13e7ca55b 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -23,6 +23,7 @@ "test": "tsc --noEmit && jest" }, "dependencies": { + "@latticexyz/common": "workspace:*", "ethers": "^5.7.2", "mobx": "^6.7.0", "proxy-deep": "^3.1.1", diff --git a/packages/utils/src/v2/TableId.ts b/packages/utils/src/v2/TableId.ts deleted file mode 100644 index 4c712d6c6a..0000000000 --- a/packages/utils/src/v2/TableId.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { arrayToHex } from "./arrayToHex"; -import { bytesToString } from "./bytesToString"; -import { hexToArray } from "./hexToArray"; -import { stringToBytes16 } from "./stringToBytes"; - -export class TableId { - namespace: string; - name: string; - - constructor(namespace: string, name: string) { - this.namespace = namespace; - this.name = name; - } - - toString() { - return `TableId<${this.namespace || "[empty]"}:${this.name || "[empty]"}>`; - } - - toHexString() { - return TableId.toHexString(this.namespace, this.name); - } - - static toHexString(namespace: string, name: string) { - const tableId = new Uint8Array(32); - tableId.set(stringToBytes16(namespace), 0); - tableId.set(stringToBytes16(name), 16); - return arrayToHex(tableId); - } - - static fromHexString(tableId: string) { - return TableId.fromBytes32(hexToArray(tableId)); - } - - static fromBytes32(tableId: Uint8Array) { - const tableIdBytes = new Uint8Array(32); - tableIdBytes.set(tableId); - const namespace = bytesToString(tableIdBytes.slice(0, 16)).replace(/\0+$/, ""); - const name = bytesToString(tableIdBytes.slice(16, 32)).replace(/\0+$/, ""); - return new TableId(namespace, name); - } - - /** @deprecated Don't use this! This is a temporary hack for v2<>v1 compatibility until we can write v2 client libraries. This is here so it stays close to the formatting of `toString()` above. */ - static parse(tableIdString: string) { - const match = tableIdString.match(/^TableId<(.+?):(.+?)>$/); - if (!match) return null; - const [, namespace, name] = match; - return new TableId(namespace === "[empty]" ? "" : namespace, name === "[empty]" ? "" : name); - } -} diff --git a/packages/utils/src/v2/getTableIds.ts b/packages/utils/src/v2/getTableIds.ts index 04fc59039a..6f27957780 100644 --- a/packages/utils/src/v2/getTableIds.ts +++ b/packages/utils/src/v2/getTableIds.ts @@ -1,4 +1,4 @@ -import { TableId } from "./TableId"; +import { TableId } from "@latticexyz/common"; const STORE_SELECTOR_MAX_LENGTH = 16; diff --git a/packages/utils/src/v2/index.ts b/packages/utils/src/v2/index.ts index 89affa6b5a..990dfc62e2 100644 --- a/packages/utils/src/v2/index.ts +++ b/packages/utils/src/v2/index.ts @@ -1,9 +1,6 @@ export * from "./arrayToHex"; export * from "./bytesToString"; export * from "./hexToArray"; -export * from "./isDefined"; -export * from "./isNotNull"; export * from "./isHex"; export * from "./stringToBytes"; -export * from "./TableId"; export * from "./getTableIds"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15b0a1b6a4..175967ebb3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -210,16 +210,19 @@ importers: prettier-plugin-solidity: specifier: ^1.1.2 version: 1.1.2(prettier@2.8.4) + viem: + specifier: 1.0.6 + version: 1.0.6(typescript@5.0.4) devDependencies: '@types/node': specifier: ^18.15.11 version: 18.15.11 '@wagmi/chains': specifier: ^0.2.22 - version: 0.2.23(typescript@4.9.5) + version: 0.2.23(typescript@5.0.4) tsup: specifier: ^6.7.0 - version: 6.7.0(typescript@4.9.5) + version: 6.7.0(postcss@8.4.23)(typescript@5.0.4) vitest: specifier: 0.31.4 version: 0.31.4 @@ -273,6 +276,9 @@ importers: packages/dev-tools: dependencies: + '@latticexyz/common': + specifier: workspace:* + version: link:../common '@latticexyz/network': specifier: workspace:* version: link:../network @@ -801,6 +807,9 @@ importers: '@latticexyz/cli': specifier: workspace:* version: link:../cli + '@latticexyz/common': + specifier: workspace:* + version: link:../common '@latticexyz/config': specifier: workspace:* version: link:../config @@ -1026,6 +1035,9 @@ importers: packages/utils: dependencies: + '@latticexyz/common': + specifier: workspace:* + version: link:../common ethers: specifier: ^5.7.2 version: 5.7.2 @@ -4057,6 +4069,18 @@ packages: optional: true dependencies: typescript: 4.9.5 + dev: false + + /@wagmi/chains@0.2.23(typescript@5.0.4): + resolution: {integrity: sha512-oIc4ZpUL6bH/HdS7ROPWlFnP5U3XBujO/OiX4csRIezyLjMQ9FNXQRZShhi5ddL0Kj1RDbyVLe9K/QotEm1vig==} + peerDependencies: + typescript: '>=4.9.4' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + typescript: 5.0.4 + dev: true /@wagmi/chains@1.1.0(typescript@4.9.5): resolution: {integrity: sha512-pWZlxBk0Ql8E7DV8DwqlbBpOyUdaG9UDlQPBxJNALuEK1I0tbQ3AVvSDnlsEIt06UPmPo5o27gzs3hwPQ/A+UA==} diff --git a/templates/phaser/packages/client/src/mud/contractComponents.ts b/templates/phaser/packages/client/src/mud/contractComponents.ts index bb79501edb..3c11df6aad 100644 --- a/templates/phaser/packages/client/src/mud/contractComponents.ts +++ b/templates/phaser/packages/client/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/templates/react/packages/client/src/mud/contractComponents.ts b/templates/react/packages/client/src/mud/contractComponents.ts index bb79501edb..3c11df6aad 100644 --- a/templates/react/packages/client/src/mud/contractComponents.ts +++ b/templates/react/packages/client/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/templates/threejs/packages/client/src/mud/contractComponents.ts b/templates/threejs/packages/client/src/mud/contractComponents.ts index a50e911c8e..b851f08579 100644 --- a/templates/threejs/packages/client/src/mud/contractComponents.ts +++ b/templates/threejs/packages/client/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -16,7 +16,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, } diff --git a/templates/vanilla/packages/client/src/mud/contractComponents.ts b/templates/vanilla/packages/client/src/mud/contractComponents.ts index bb79501edb..3c11df6aad 100644 --- a/templates/vanilla/packages/client/src/mud/contractComponents.ts +++ b/templates/vanilla/packages/client/src/mud/contractComponents.ts @@ -1,6 +1,6 @@ /* Autogenerated file. Do not edit manually. */ -import { TableId } from "@latticexyz/utils"; +import { TableId } from "@latticexyz/common"; import { defineComponent, Type as RecsType, World } from "@latticexyz/recs"; export function defineContractComponents(world: World) { @@ -14,7 +14,7 @@ export function defineContractComponents(world: World) { }, { metadata: { - contractId: tableId.toHexString(), + contractId: tableId.toHex(), tableId: tableId.toString(), }, }