diff --git a/.changeset/dull-otters-smash.md b/.changeset/dull-otters-smash.md new file mode 100644 index 0000000000..d53d909197 --- /dev/null +++ b/.changeset/dull-otters-smash.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/world-modules": patch +--- + +ERC20 and ERC721 implementations now always register the token namespace, instead of checking if it has already been registered. This prevents issues with registering the namespace beforehand, namely that only the owner of a system can create a puppet for it. diff --git a/.changeset/famous-feet-suffer.md b/.changeset/famous-feet-suffer.md new file mode 100644 index 0000000000..e42174b4d9 --- /dev/null +++ b/.changeset/famous-feet-suffer.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/store": patch +--- + +Refactored `StoreCore` to import `IStoreEvents` instead of defining the events twice. diff --git a/.changeset/few-berries-tickle.md b/.changeset/few-berries-tickle.md new file mode 100644 index 0000000000..dcbf3602a1 --- /dev/null +++ b/.changeset/few-berries-tickle.md @@ -0,0 +1,21 @@ +--- +"create-mud": patch +"@latticexyz/cli": major +"@latticexyz/common": major +"@latticexyz/store": patch +"@latticexyz/world": patch +"@latticexyz/world-modules": patch +--- + +Moved table ID and field layout constants in code-generated table libraries from the file level into the library, for clearer access and cleaner imports. + +```diff +-import { SomeTable, SomeTableTableId } from "./codegen/tables/SomeTable.sol"; ++import { SomeTable } from "./codegen/tables/SomeTable.sol"; + +-console.log(SomeTableTableId); ++console.log(SomeTable._tableId); + +-console.log(SomeTable.getFieldLayout()); ++console.log(SomeTable._fieldLayout); +``` diff --git a/.changeset/heavy-shirts-dance.md b/.changeset/heavy-shirts-dance.md new file mode 100644 index 0000000000..6317deb7f4 --- /dev/null +++ b/.changeset/heavy-shirts-dance.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/store": patch +--- + +Added interfaces for all errors that are used by `StoreCore`, which includes `FieldLayout`, `PackedCounter`, `Schema`, and `Slice`. This interfaces are inherited by `IStore`, ensuring that all possible errors are included in the `IStore` ABI for proper decoding in the frontend. diff --git a/.changeset/loud-rockets-switch.md b/.changeset/loud-rockets-switch.md new file mode 100644 index 0000000000..2e80de7d69 --- /dev/null +++ b/.changeset/loud-rockets-switch.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/common": patch +--- + +Upgraded prettier version to 3.2.5 and prettier-plugin-solidity version to 1.3.1. diff --git a/.changeset/moody-shirts-carry.md b/.changeset/moody-shirts-carry.md new file mode 100644 index 0000000000..c6f1943f1b --- /dev/null +++ b/.changeset/moody-shirts-carry.md @@ -0,0 +1,25 @@ +--- +"@latticexyz/common": minor +"create-mud": minor +--- + +Added viem custom client actions that work the same as MUD's now-deprecated `getContract`, `writeContract`, and `sendTransaction` wrappers. Templates have been updated to reflect the new patterns. + +You can migrate your own code like this: + +```diff +-import { createWalletClient } from "viem"; +-import { getContract, writeContract, sendTransaction } from "@latticexyz/common"; ++import { createWalletClient, getContract } from "viem"; ++import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; + +-const walletClient = createWalletClient(...); ++const walletClient = createWalletClient(...) ++ .extend(transactionQueue()) ++ .extend(writeObserver({ onWrite }); + + const worldContract = getContract({ + client: { publicClient, walletClient }, +- onWrite, + }); +``` diff --git a/.changeset/nasty-waves-divide.md b/.changeset/nasty-waves-divide.md index f85dd96047..61ac31054c 100644 --- a/.changeset/nasty-waves-divide.md +++ b/.changeset/nasty-waves-divide.md @@ -22,7 +22,7 @@ const latestBlock$ = await createBlockStream({ publicClient, blockTag: "latest" const latestBlockNumber$ = latestBlock$.pipe( filter(isNonPendingBlock), - map((block) => block.number) + map((block) => block.number), ); latestBlockNumber$ @@ -38,7 +38,7 @@ latestBlockNumber$ "event StoreEphemeralRecord(bytes32 table, bytes32[] key, bytes data)", ]), }), - mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))) + mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))), ) .subscribe((block) => { console.log("got events for block", block); diff --git a/.changeset/spicy-waves-wait.md b/.changeset/spicy-waves-wait.md new file mode 100644 index 0000000000..9c070fdd64 --- /dev/null +++ b/.changeset/spicy-waves-wait.md @@ -0,0 +1,5 @@ +--- +"@latticexyz/store": patch +--- + +Moved the `HelloStore` to `IStoreEvents` so all Store events are defined in the same interface. diff --git a/.changeset/tame-lemons-play.md b/.changeset/tame-lemons-play.md index e20f0bcd55..17de0f9339 100644 --- a/.changeset/tame-lemons-play.md +++ b/.changeset/tame-lemons-play.md @@ -172,7 +172,7 @@ As you migrate, you may find some features replaced, removed, or not included by .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/.changeset/tough-pumpkins-reply.md b/.changeset/tough-pumpkins-reply.md new file mode 100644 index 0000000000..559c3ef6d5 --- /dev/null +++ b/.changeset/tough-pumpkins-reply.md @@ -0,0 +1,16 @@ +--- +"create-mud": patch +"@latticexyz/store": minor +"@latticexyz/world": minor +"@latticexyz/world-modules": minor +--- + +Moved key schema and value schema methods to constants in code-generated table libraries for less bytecode and less gas in register/install methods. + +```diff +-console.log(SomeTable.getKeySchema()); ++console.log(SomeTable._keySchema); + +-console.log(SomeTable.getValueSchema()); ++console.log(SomeTable._valueSchema); +``` diff --git a/.github/workflows/test-published-packages.yml b/.github/workflows/test-published-packages.yml index e9358fd8bf..d72a6162f5 100644 --- a/.github/workflows/test-published-packages.yml +++ b/.github/workflows/test-published-packages.yml @@ -15,12 +15,13 @@ on: jobs: test-create-mud-project: name: Test create-mud project - runs-on: ubuntu-latest strategy: fail-fast: false matrix: + os: [ubuntu-latest-16-cores, windows-latest] template: [vanilla, react, react-ecs, phaser, threejs] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e3efbf55d..12d6a624bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3395,7 +3395,7 @@ As you migrate, you may find some features replaced, removed, or not included by .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` @@ -3633,7 +3633,7 @@ const latestBlock$ = await createBlockStream({ publicClient, blockTag: "latest" const latestBlockNumber$ = latestBlock$.pipe( filter(isNonPendingBlock), - map((block) => block.number) + map((block) => block.number), ); latestBlockNumber$ @@ -3649,7 +3649,7 @@ latestBlockNumber$ "event StoreEphemeralRecord(bytes32 table, bytes32[] key, bytes data)", ]), }), - mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))) + mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))), ) .subscribe((block) => { console.log("got events for block", block); diff --git a/docs/app/page.tsx b/docs/app/page.tsx index 7a954b39d5..bbb7c29d8c 100644 --- a/docs/app/page.tsx +++ b/docs/app/page.tsx @@ -24,7 +24,7 @@ export default async function HomePage() { "min-h-screen flex flex-col animate-in animate-duration-500 fade-in", "gap-12 p-8", "sm:justify-between", - "md:gap-16 md:p-16" + "md:gap-16 md:p-16", )} >
diff --git a/docs/components/MUDTable.module.css b/docs/components/MUDTable.module.css index becc677b84..97b6223686 100644 --- a/docs/components/MUDTable.module.css +++ b/docs/components/MUDTable.module.css @@ -1,5 +1,13 @@ .table { - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace; + font-family: + ui-monospace, + SFMono-Regular, + Menlo, + Monaco, + Consolas, + Liberation Mono, + Courier New, + monospace; background-color: hsl(var(--nextra-primary-hue) 100% 66%/0.1); margin-top: 1em; text-align: center; diff --git a/docs/pages/changelog.mdx b/docs/pages/changelog.mdx index 9e3efbf55d..12d6a624bf 100644 --- a/docs/pages/changelog.mdx +++ b/docs/pages/changelog.mdx @@ -3395,7 +3395,7 @@ As you migrate, you may find some features replaced, removed, or not included by .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` @@ -3633,7 +3633,7 @@ const latestBlock$ = await createBlockStream({ publicClient, blockTag: "latest" const latestBlockNumber$ = latestBlock$.pipe( filter(isNonPendingBlock), - map((block) => block.number) + map((block) => block.number), ); latestBlockNumber$ @@ -3649,7 +3649,7 @@ latestBlockNumber$ "event StoreEphemeralRecord(bytes32 table, bytes32[] key, bytes data)", ]), }), - mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))) + mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))), ) .subscribe((block) => { console.log("got events for block", block); diff --git a/docs/pages/guides/emojimon/3-players-and-movement.mdx b/docs/pages/guides/emojimon/3-players-and-movement.mdx index d5eac88e95..cefe114200 100644 --- a/docs/pages/guides/emojimon/3-players-and-movement.mdx +++ b/docs/pages/guides/emojimon/3-players-and-movement.mdx @@ -255,7 +255,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { playerEntity, worldContract, waitForTransaction }: SetupNetworkResult, - { Player, Position }: ClientComponents + { Player, Position }: ClientComponents, ) { const moveBy = async (deltaX: number, deltaY: number) => { if (!playerEntity) { diff --git a/docs/pages/guides/emojimon/4-map-and-terrain.mdx b/docs/pages/guides/emojimon/4-map-and-terrain.mdx index 4e81e1584d..bbbc842494 100644 --- a/docs/pages/guides/emojimon/4-map-and-terrain.mdx +++ b/docs/pages/guides/emojimon/4-map-and-terrain.mdx @@ -445,7 +445,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { playerEntity, worldContract, waitForTransaction }: SetupNetworkResult, - { MapConfig, Obstruction, Player, Position }: ClientComponents + { MapConfig, Obstruction, Player, Position }: ClientComponents, ) { const isObstructed = (x: number, y: number) => { return runQuery([Has(Obstruction), HasValue(Position, { x, y })]).size > 0; diff --git a/docs/pages/guides/emojimon/5-a-wild-emojimon-appears.mdx b/docs/pages/guides/emojimon/5-a-wild-emojimon-appears.mdx index 7392e1f57e..b7522d7304 100644 --- a/docs/pages/guides/emojimon/5-a-wild-emojimon-appears.mdx +++ b/docs/pages/guides/emojimon/5-a-wild-emojimon-appears.mdx @@ -718,7 +718,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { playerEntity, worldContract, waitForTransaction }: SetupNetworkResult, - { Encounter, MapConfig, MonsterCatchAttempt, Obstruction, Player, Position }: ClientComponents + { Encounter, MapConfig, MonsterCatchAttempt, Obstruction, Player, Position }: ClientComponents, ) { const wrapPosition = (x: number, y: number) => { const mapConfig = getComponentValue(MapConfig, singletonEntity); @@ -890,7 +890,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { playerEntity, worldContract, waitForTransaction }: SetupNetworkResult, - { Encounter, MapConfig, MonsterCatchAttempt, Obstruction, Player, Position }: ClientComponents + { Encounter, MapConfig, MonsterCatchAttempt, Obstruction, Player, Position }: ClientComponents, ) { const wrapPosition = (x: number, y: number) => { const mapConfig = getComponentValue(MapConfig, singletonEntity); diff --git a/docs/pages/guides/hello-world/add-table.mdx b/docs/pages/guides/hello-world/add-table.mdx index 0673138767..b1fa6dc4d6 100644 --- a/docs/pages/guides/hello-world/add-table.mdx +++ b/docs/pages/guides/hello-world/add-table.mdx @@ -261,7 +261,7 @@ This exclamation point tells the compiler that it's OK, there will be a real val ```html filename="index.html" copy showLineNumbers {12-17} - + diff --git a/docs/pages/store/reference/misc.mdx b/docs/pages/store/reference/misc.mdx index 78e1f5d689..301a4846d9 100644 --- a/docs/pages/store/reference/misc.mdx +++ b/docs/pages/store/reference/misc.mdx @@ -470,50 +470,6 @@ function encode(uint256[] memory _staticFieldLengths, uint256 numDynamicFields) | -------- | ------------- | ------------------------------------------------------------ | | `` | `FieldLayout` | A FieldLayout structure containing the encoded field layout. | -### Errors - -#### FieldLayoutLib_TooManyFields - -```solidity -error FieldLayoutLib_TooManyFields(uint256 numFields, uint256 maxFields); -``` - -#### FieldLayoutLib_TooManyDynamicFields - -```solidity -error FieldLayoutLib_TooManyDynamicFields(uint256 numFields, uint256 maxFields); -``` - -#### FieldLayoutLib_Empty - -```solidity -error FieldLayoutLib_Empty(); -``` - -#### FieldLayoutLib_InvalidStaticDataLength - -```solidity -error FieldLayoutLib_InvalidStaticDataLength(uint256 staticDataLength, uint256 computedStaticDataLength); -``` - -#### FieldLayoutLib_StaticLengthIsZero - -```solidity -error FieldLayoutLib_StaticLengthIsZero(uint256 index); -``` - -#### FieldLayoutLib_StaticLengthIsNotZero - -```solidity -error FieldLayoutLib_StaticLengthIsNotZero(uint256 index); -``` - -#### FieldLayoutLib_StaticLengthDoesNotFitInAWord - -```solidity -error FieldLayoutLib_StaticLengthDoesNotFitInAWord(uint256 index); -``` - ## FieldLayout [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/FieldLayout.sol) @@ -991,24 +947,6 @@ function encode(SchemaType[] memory schemas) internal pure returns (Schema); | -------- | -------- | ------------------- | | `` | `Schema` | The encoded Schema. | -### Errors - -#### SchemaLib_InvalidLength - -_Error raised when the provided schema has an invalid length._ - -```solidity -error SchemaLib_InvalidLength(uint256 length); -``` - -#### SchemaLib_StaticTypeAfterDynamicType - -_Error raised when a static type is placed after a dynamic type in a schema._ - -```solidity -error SchemaLib_StaticTypeAfterDynamicType(); -``` - ## Schema [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/Schema.sol) @@ -1192,14 +1130,6 @@ function getSubslice(bytes memory data, uint256 start, uint256 end) internal pur | -------- | ------- | ------------------------------------- | | `` | `Slice` | A new Slice representing the subslice | -### Errors - -#### Slice_OutOfBounds - -```solidity -error Slice_OutOfBounds(bytes data, uint256 start, uint256 end); -``` - ## Slice [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/Slice.sol) @@ -1618,9 +1548,9 @@ bytes2 constant RESOURCE_OFFCHAIN_TABLE = "ot"; #### STORE_VERSION -Contains a constant representing the version of the store. +Contains a constant representing the version of the Store. -_Identifier for the current store version._ +_Identifier for the current Store version._ ```solidity bytes32 constant STORE_VERSION = "1.0.0-unaudited"; diff --git a/docs/pages/store/reference/store-core.mdx b/docs/pages/store/reference/store-core.mdx index 4d9d0f1dd8..f5888d234c 100644 --- a/docs/pages/store/reference/store-core.mdx +++ b/docs/pages/store/reference/store-core.mdx @@ -762,91 +762,6 @@ function getDynamicFieldSlice( | -------- | ------- | ------------------------------------ | | `` | `bytes` | The byte slice of the dynamic field. | -### Events - -#### Store_SetRecord - -Emitted when a new record is set in the store. - -```solidity -event Store_SetRecord( - ResourceId indexed tableId, bytes32[] keyTuple, bytes staticData, PackedCounter encodedLengths, bytes dynamicData -); -``` - -**Parameters** - -| Name | Type | Description | -| ---------------- | --------------- | ------------------------------------------------------- | -| `tableId` | `ResourceId` | The ID of the table where the record is set. | -| `keyTuple` | `bytes32[]` | An array representing the composite key for the record. | -| `staticData` | `bytes` | The static data of the record. | -| `encodedLengths` | `PackedCounter` | The encoded lengths of the dynamic data of the record. | -| `dynamicData` | `bytes` | The dynamic data of the record. | - -#### Store_SpliceStaticData - -Emitted when static data in the store is spliced. - -_In static data, data is always overwritten starting at the start position, -so the total length of the data remains the same and no data is shifted._ - -```solidity -event Store_SpliceStaticData(ResourceId indexed tableId, bytes32[] keyTuple, uint48 start, bytes data); -``` - -**Parameters** - -| Name | Type | Description | -| ---------- | ------------ | --------------------------------------------------------------------- | -| `tableId` | `ResourceId` | The ID of the table where the data is spliced. | -| `keyTuple` | `bytes32[]` | An array representing the key for the record. | -| `start` | `uint48` | The start position in bytes for the splice operation. | -| `data` | `bytes` | The data to write to the static data of the record at the start byte. | - -#### Store_SpliceDynamicData - -Emitted when dynamic data in the store is spliced. - -```solidity -event Store_SpliceDynamicData( - ResourceId indexed tableId, - bytes32[] keyTuple, - uint8 dynamicFieldIndex, - uint48 start, - uint40 deleteCount, - PackedCounter encodedLengths, - bytes data -); -``` - -**Parameters** - -| Name | Type | Description | -| ------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tableId` | `ResourceId` | The ID of the table where the data is spliced. | -| `keyTuple` | `bytes32[]` | An array representing the composite key for the record. | -| `dynamicFieldIndex` | `uint8` | The index of the dynamic field to splice data, relative to the start of the dynamic fields. (Dynamic field index = field index - number of static fields) | -| `start` | `uint48` | The start position in bytes for the splice operation. | -| `deleteCount` | `uint40` | The number of bytes to delete in the splice operation. | -| `encodedLengths` | `PackedCounter` | The encoded lengths of the dynamic data of the record. | -| `data` | `bytes` | The data to insert into the dynamic data of the record at the start byte. | - -#### Store_DeleteRecord - -Emitted when a record is deleted from the store. - -```solidity -event Store_DeleteRecord(ResourceId indexed tableId, bytes32[] keyTuple); -``` - -**Parameters** - -| Name | Type | Description | -| ---------- | ------------ | ------------------------------------------------------- | -| `tableId` | `ResourceId` | The ID of the table where the record is deleted. | -| `keyTuple` | `bytes32[]` | An array representing the composite key for the record. | - ## StoreCoreInternal [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/StoreCore.sol) diff --git a/docs/pages/store/reference/store.mdx b/docs/pages/store/reference/store.mdx index df300ce8c7..4106a722f0 100644 --- a/docs/pages/store/reference/store.mdx +++ b/docs/pages/store/reference/store.mdx @@ -5,7 +5,9 @@ [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/IStore.sol) **Inherits:** -[IStoreData](/store/reference/store#istoredata), [IStoreRegistration](/store/reference/store#istoreregistration), [IStoreErrors](/store/reference/store#istoreerrors) +[IStoreData](/store/reference/store#istoredata), [IStoreRegistration](/store/reference/store#istoreregistration), [IStoreErrors](/store/reference/store#istoreerrors), [IFieldLayoutErrors](/src/IFieldLayoutErrors.sol/interface.IFieldLayoutErrors.md), [IPackedCounterErrors](/src/IPackedCounterErrors.sol/interface.IPackedCounterErrors.md), [ISchemaErrors](/src/ISchemaErrors.sol/interface.ISchemaErrors.md), [ISliceErrors](/src/ISliceErrors.sol/interface.ISliceErrors.md) + +IStore implements the error interfaces for each library that it uses. ## IStoreEvents @@ -13,13 +15,31 @@ ### Events +#### HelloStore + +Emitted when the store is initialized. + +```solidity +event HelloStore(bytes32 indexed storeVersion); +``` + +**Parameters** + +| Name | Type | Description | +| -------------- | --------- | ---------------------------------- | +| `storeVersion` | `bytes32` | The version of the Store contract. | + #### Store_SetRecord Emitted when a new record is set in the store. ```solidity event Store_SetRecord( - ResourceId indexed tableId, bytes32[] keyTuple, bytes staticData, PackedCounter encodedLengths, bytes dynamicData + ResourceId indexed tableId, + bytes32[] keyTuple, + bytes staticData, + PackedCounter encodedLengths, + bytes dynamicData ); ``` @@ -59,13 +79,13 @@ Emitted when dynamic data in the store is spliced. ```solidity event Store_SpliceDynamicData( - ResourceId indexed tableId, - bytes32[] keyTuple, - uint8 dynamicFieldIndex, - uint48 start, - uint40 deleteCount, - PackedCounter encodedLengths, - bytes data + ResourceId indexed tableId, + bytes32[] keyTuple, + uint8 dynamicFieldIndex, + uint48 start, + uint40 deleteCount, + PackedCounter encodedLengths, + bytes data ); ``` @@ -100,6 +120,11 @@ event Store_DeleteRecord(ResourceId indexed tableId, bytes32[] keyTuple); [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/IStoreErrors.sol) +This interface includes errors for Store. + +_We bundle these errors in an interface (instead of at the file-level or in their corresponding library) so they can be inherited by IStore. +This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend._ + ### Errors #### Store_TableAlreadyExists @@ -201,22 +226,6 @@ function storeVersion() external view returns (bytes32 version); | --------- | --------- | ---------------------------------- | | `version` | `bytes32` | The version of the Store contract. | -### Events - -#### HelloStore - -Emitted when the store is initialized. - -```solidity -event HelloStore(bytes32 indexed storeVersion); -``` - -**Parameters** - -| Name | Type | Description | -| -------------- | --------- | ---------------------------------- | -| `storeVersion` | `bytes32` | The version of the Store contract. | - ## IStoreRead [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/IStoreRead.sol) @@ -482,9 +491,7 @@ function deleteRecord(ResourceId tableId, bytes32[] memory keyTuple) external; [Git Source](https://github.com/latticexyz/mud/blob/main/packages/store/src/IStoreRegistration.sol) -The IStoreRegistration interface includes methods for managing table field layouts, -metadata, and hooks, which are usually called once in the setup phase of an application, -making them less performance critical than the methods. +_This interface includes methods for managing table field layouts, metadata, and hooks, which are usually called once in the setup phase of an application, making them less performance critical than the methods._ ### Functions diff --git a/docs/pages/world/reference/internal/erc165.mdx b/docs/pages/world/reference/internal/erc165.mdx index e6595d57d6..624f36d17f 100644 --- a/docs/pages/world/reference/internal/erc165.mdx +++ b/docs/pages/world/reference/internal/erc165.mdx @@ -93,12 +93,8 @@ function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) i [Git Source](https://github.com/latticexyz/mud/blob/main/packages/world/src/requireInterface.sol) -Utility function to validate interface support on a given contract using ERC-165. - Checks if a given contract at `contractAddress` supports the interface with ID `interfaceId`. -_This function uses the ERC-165 standard's `supportsInterface` to check if a given contract supports a specific interface._ - _Uses the ERC-165 `supportsInterface` method. If the contract doesn't support the interface or doesn't implement ERC-165, the function will revert with a relevant error message._ ```solidity diff --git a/docs/pages/world/reference/misc.mdx b/docs/pages/world/reference/misc.mdx index b2ebefd27c..2fed485aec 100644 --- a/docs/pages/world/reference/misc.mdx +++ b/docs/pages/world/reference/misc.mdx @@ -79,12 +79,8 @@ ResourceId constant UNLIMITED_DELEGATION = ResourceId.wrap( [Git Source](https://github.com/latticexyz/mud/blob/main/packages/world/src/revertWithBytes.sol) -Utility function to revert transactions with raw bytes. - Reverts the transaction using the provided raw bytes as the revert reason. -_This can be especially useful when reverting with a message obtained from a low-level call or a pre-encoded error._ - _Uses assembly to perform the revert operation with the raw bytes._ ```solidity @@ -103,9 +99,9 @@ function revertWithBytes(bytes memory reason) pure; #### WORLD_VERSION -_World Version Constant -Defines the version identifier for the World contract or module. -This version identifier can be used for version checks, logging, and more._ +Contains a constant representing the version of the World. + +_Identifier for the current World version._ ```solidity bytes32 constant WORLD_VERSION = "1.0.0-unaudited"; diff --git a/docs/pages/world/reference/resource-ids.mdx b/docs/pages/world/reference/resource-ids.mdx index 5a6c7a5f0e..6b053e370c 100644 --- a/docs/pages/world/reference/resource-ids.mdx +++ b/docs/pages/world/reference/resource-ids.mdx @@ -194,11 +194,7 @@ function toTrimmedString(bytes16 paddedString) internal pure returns (string mem #### RESOURCE_NAMESPACE -_World Resource Types_ - -_Constants related to World Resource Types and Masks._ - -_These constants are used to represent various resource types within the system._ +_Constants used to work with world resource types._ ```solidity bytes2 constant RESOURCE_NAMESPACE = "ns"; diff --git a/docs/pages/world/reference/world-context-external.mdx b/docs/pages/world/reference/world-context-external.mdx index cb3469d2f7..f213c32c65 100644 --- a/docs/pages/world/reference/world-context-external.mdx +++ b/docs/pages/world/reference/world-context-external.mdx @@ -11,11 +11,6 @@ This contract is designed to extract trusted context values (like msg.sender and from the appended calldata. It provides mechanisms similar to EIP-2771 (https://eips.ethereum.org/EIPS/eip-2771), but allowing any contract to be the trusted forwarder. -_World Context Consumer Interface -This interface defines the functions a contract needs to consume the world context. -It includes helper functions to retrieve the message sender, value, and world address. -Additionally, it integrates with the ERC-165 standard for interface detection._ - _This contract should only be used for contracts without their own storage, like Systems._ ### Functions diff --git a/docs/pages/world/reference/world-context.mdx b/docs/pages/world/reference/world-context.mdx index 514178c281..512d8a7253 100644 --- a/docs/pages/world/reference/world-context.mdx +++ b/docs/pages/world/reference/world-context.mdx @@ -92,6 +92,8 @@ uint256 constant CONTEXT_BYTES = 20 + 32; [Git Source](https://github.com/latticexyz/mud/blob/main/packages/world/src/WorldContext.sol) +Helpers for working with data in the context of calling a World + ### Functions #### \_msgSender diff --git a/docs/pages/world/reference/world.mdx b/docs/pages/world/reference/world.mdx index f25400d6e3..2bed5edbe2 100644 --- a/docs/pages/world/reference/world.mdx +++ b/docs/pages/world/reference/world.mdx @@ -44,7 +44,10 @@ constructor(); #### prohibitDirectCallback -_Prevents the World contract from calling itself._ +_Prevents the World contract from calling itself. +If the World is able to call itself via `delegatecall` from a system, the system would have root access to context like internal tables, causing a potential vulnerability. +Ideally this should not happen because all operations to internal tables happen as internal library calls, and all calls to root systems happen as a `delegatecall` to the system. +However, since this is an important invariant, we make it explicit by reverting if `msg.sender` is `address(this)` in all `World` methods._ ```solidity modifier prohibitDirectCallback(); diff --git a/docs/src/tailwindcss-plugins/animate.ts b/docs/src/tailwindcss-plugins/animate.ts index f64ba44b27..1c6e3c1369 100644 --- a/docs/src/tailwindcss-plugins/animate.ts +++ b/docs/src/tailwindcss-plugins/animate.ts @@ -37,7 +37,7 @@ module.exports = plugin( "fade-in": (value) => ({ "--tw-enter-opacity": value }), "fade-out": (value) => ({ "--tw-exit-opacity": value }), }, - { values: theme("animationOpacity") } + { values: theme("animationOpacity") }, ); matchUtilities( @@ -45,7 +45,7 @@ module.exports = plugin( "zoom-in": (value) => ({ "--tw-enter-scale": value }), "zoom-out": (value) => ({ "--tw-exit-scale": value }), }, - { values: theme("animationScale") } + { values: theme("animationScale") }, ); matchUtilities( @@ -53,7 +53,7 @@ module.exports = plugin( "spin-in": (value) => ({ "--tw-enter-rotate": value }), "spin-out": (value) => ({ "--tw-exit-rotate": value }), }, - { values: theme("animationRotate") } + { values: theme("animationRotate") }, ); matchUtilities( @@ -83,19 +83,19 @@ module.exports = plugin( "--tw-exit-translate-x": value, }), }, - { values: theme("animationTranslate") } + { values: theme("animationTranslate") }, ); matchUtilities( { "animate-duration": (value: string) => ({ animationDuration: value }) }, - { values: filterDefault(theme("animationDuration")) } + { values: filterDefault(theme("animationDuration")) }, ); matchUtilities({ delay: (value) => ({ animationDelay: value }) }, { values: theme("animationDelay") }); matchUtilities( { ease: (value: string) => ({ animationTimingFunction: value }) }, - { values: filterDefault(theme("animationTimingFunction")) } + { values: filterDefault(theme("animationTimingFunction")) }, ); addUtilities({ @@ -175,5 +175,5 @@ module.exports = plugin( }, }, }, - } + }, ); diff --git a/e2e/packages/client-vanilla/src/index.ts b/e2e/packages/client-vanilla/src/index.ts index 464d986f78..7899f3c949 100644 --- a/e2e/packages/client-vanilla/src/index.ts +++ b/e2e/packages/client-vanilla/src/index.ts @@ -17,7 +17,7 @@ _window.getEntities = (componentName: keyof typeof components) => Array.from(com _window.getKeys = (componentName: keyof typeof components) => Array.from(components[componentName].entities()).map((entity) => - decodeEntity(components[componentName].metadata.keySchema, entity) + decodeEntity(components[componentName].metadata.keySchema, entity), ); // Update block number in the UI diff --git a/e2e/packages/contracts/package.json b/e2e/packages/contracts/package.json index 27a8b462a5..3f1b229fb3 100644 --- a/e2e/packages/contracts/package.json +++ b/e2e/packages/contracts/package.json @@ -19,7 +19,7 @@ "dotenv": "^16.0.3", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", + "prettier": "3.2.5", "rimraf": "^3.0.2", "typescript": "5.1.6", "vite": "^4.2.1", diff --git a/e2e/packages/contracts/src/codegen/index.sol b/e2e/packages/contracts/src/codegen/index.sol index 409d155bf2..8de689e3ae 100644 --- a/e2e/packages/contracts/src/codegen/index.sol +++ b/e2e/packages/contracts/src/codegen/index.sol @@ -3,9 +3,9 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Number, NumberTableId } from "./tables/Number.sol"; -import { Vector, VectorData, VectorTableId } from "./tables/Vector.sol"; -import { NumberList, NumberListTableId } from "./tables/NumberList.sol"; -import { Multi, MultiData, MultiTableId } from "./tables/Multi.sol"; -import { Position, PositionTableId } from "./tables/Position.sol"; -import { StaticArray, StaticArrayTableId } from "./tables/StaticArray.sol"; +import { Number } from "./tables/Number.sol"; +import { Vector, VectorData } from "./tables/Vector.sol"; +import { NumberList } from "./tables/NumberList.sol"; +import { Multi, MultiData } from "./tables/Multi.sol"; +import { Position } from "./tables/Position.sol"; +import { StaticArray } from "./tables/StaticArray.sol"; diff --git a/e2e/packages/contracts/src/codegen/tables/Multi.sol b/e2e/packages/contracts/src/codegen/tables/Multi.sol index 99a5c7d699..ae9811c45f 100644 --- a/e2e/packages/contracts/src/codegen/tables/Multi.sol +++ b/e2e/packages/contracts/src/codegen/tables/Multi.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,58 +11,27 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Multi", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004d756c74690000000000000000000000); -ResourceId constant MultiTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0021020020010000000000000000000000000000000000000000000000000000 -); - struct MultiData { int256 num; bool value; } library Multi { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Multi", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004d756c74690000000000000000000000); - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](4); - _keySchema[0] = SchemaType.UINT32; - _keySchema[1] = SchemaType.BOOL; - _keySchema[2] = SchemaType.UINT256; - _keySchema[3] = SchemaType.INT120; - - return SchemaLib.encode(_keySchema); - } - - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.INT256; - _valueSchema[1] = SchemaType.BOOL; + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0021020020010000000000000000000000000000000000000000000000000000); - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint32, bool, uint256, int120) + Schema constant _keySchema = Schema.wrap(0x0034040003601f2e000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (int256, bool) + Schema constant _valueSchema = Schema.wrap(0x002102003f600000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -93,14 +59,14 @@ library Multi { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/tables/Number.sol b/e2e/packages/contracts/src/codegen/tables/Number.sol index 39654130c2..2c2820a54a 100644 --- a/e2e/packages/contracts/src/codegen/tables/Number.sol +++ b/e2e/packages/contracts/src/codegen/tables/Number.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,49 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Number", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004e756d62657200000000000000000000); -ResourceId constant NumberTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library Number { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.UINT32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Number", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004e756d62657200000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint32) + Schema constant _keySchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -80,14 +50,14 @@ library Number { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/tables/NumberList.sol b/e2e/packages/contracts/src/codegen/tables/NumberList.sol index 426f0600cf..667191bfa2 100644 --- a/e2e/packages/contracts/src/codegen/tables/NumberList.sol +++ b/e2e/packages/contracts/src/codegen/tables/NumberList.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "NumberList", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004e756d6265724c697374000000000000); -ResourceId constant NumberListTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library NumberList { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "NumberList", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004e756d6265724c697374000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32[]) + Schema constant _valueSchema = Schema.wrap(0x0000000165000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library NumberList { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/tables/Position.sol b/e2e/packages/contracts/src/codegen/tables/Position.sol index 7a724cc2a1..2cfe47fc5b 100644 --- a/e2e/packages/contracts/src/codegen/tables/Position.sol +++ b/e2e/packages/contracts/src/codegen/tables/Position.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,51 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Position", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000506f736974696f6e0000000000000000); -ResourceId constant PositionTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library Position { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](3); - _keySchema[0] = SchemaType.BYTES32; - _keySchema[1] = SchemaType.INT32; - _keySchema[2] = SchemaType.INT32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Position", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000506f736974696f6e0000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32, int32, int32) + Schema constant _keySchema = Schema.wrap(0x002803005f232300000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -84,14 +52,14 @@ library Position { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/tables/StaticArray.sol b/e2e/packages/contracts/src/codegen/tables/StaticArray.sol index 95a942ff05..99d6b62320 100644 --- a/e2e/packages/contracts/src/codegen/tables/StaticArray.sol +++ b/e2e/packages/contracts/src/codegen/tables/StaticArray.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "StaticArray", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053746174696341727261790000000000); -ResourceId constant StaticArrayTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library StaticArray { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "StaticArray", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053746174696341727261790000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256[]) + Schema constant _valueSchema = Schema.wrap(0x0000000181000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library StaticArray { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/tables/Vector.sol b/e2e/packages/contracts/src/codegen/tables/Vector.sol index eb09153136..6d3d109d55 100644 --- a/e2e/packages/contracts/src/codegen/tables/Vector.sol +++ b/e2e/packages/contracts/src/codegen/tables/Vector.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,55 +11,27 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Vector", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000566563746f7200000000000000000000); -ResourceId constant VectorTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0008020004040000000000000000000000000000000000000000000000000000 -); - struct VectorData { int32 x; int32 y; } library Vector { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.UINT32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Vector", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000566563746f7200000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0008020004040000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.INT32; - _valueSchema[1] = SchemaType.INT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint32) + Schema constant _keySchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (int32, int32) + Schema constant _valueSchema = Schema.wrap(0x0008020023230000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -87,14 +56,14 @@ library Vector { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/e2e/packages/contracts/src/codegen/world/ICustomErrorsSystem.sol b/e2e/packages/contracts/src/codegen/world/ICustomErrorsSystem.sol index a7fb0f251f..ce3085beda 100644 --- a/e2e/packages/contracts/src/codegen/world/ICustomErrorsSystem.sol +++ b/e2e/packages/contracts/src/codegen/world/ICustomErrorsSystem.sol @@ -7,6 +7,7 @@ import { Position } from "./../../CustomTypes.sol"; /** * @title ICustomErrorsSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface ICustomErrorsSystem { diff --git a/e2e/packages/contracts/src/codegen/world/INumberListSystem.sol b/e2e/packages/contracts/src/codegen/world/INumberListSystem.sol index 318735091d..115020b005 100644 --- a/e2e/packages/contracts/src/codegen/world/INumberListSystem.sol +++ b/e2e/packages/contracts/src/codegen/world/INumberListSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title INumberListSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface INumberListSystem { diff --git a/e2e/packages/contracts/src/codegen/world/INumberSystem.sol b/e2e/packages/contracts/src/codegen/world/INumberSystem.sol index 963d1dca41..674c332050 100644 --- a/e2e/packages/contracts/src/codegen/world/INumberSystem.sol +++ b/e2e/packages/contracts/src/codegen/world/INumberSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title INumberSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface INumberSystem { diff --git a/e2e/packages/contracts/src/codegen/world/IVectorSystem.sol b/e2e/packages/contracts/src/codegen/world/IVectorSystem.sol index 6b3b91b89c..8c43954556 100644 --- a/e2e/packages/contracts/src/codegen/world/IVectorSystem.sol +++ b/e2e/packages/contracts/src/codegen/world/IVectorSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IVectorSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IVectorSystem { diff --git a/e2e/packages/contracts/src/codegen/world/IWorld.sol b/e2e/packages/contracts/src/codegen/world/IWorld.sol index 6865aa9033..62448e2b51 100644 --- a/e2e/packages/contracts/src/codegen/world/IWorld.sol +++ b/e2e/packages/contracts/src/codegen/world/IWorld.sol @@ -12,10 +12,9 @@ import { IVectorSystem } from "./IVectorSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, ICustomErrorsSystem, INumberListSystem, INumberSystem, IVectorSystem { - -} +interface IWorld is IBaseWorld, ICustomErrorsSystem, INumberListSystem, INumberSystem, IVectorSystem {} diff --git a/e2e/packages/contracts/src/systems/NumberListSystem.sol b/e2e/packages/contracts/src/systems/NumberListSystem.sol index a36fe62521..aa07345160 100644 --- a/e2e/packages/contracts/src/systems/NumberListSystem.sol +++ b/e2e/packages/contracts/src/systems/NumberListSystem.sol @@ -4,7 +4,7 @@ pragma solidity >=0.8.24; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; import { System } from "@latticexyz/world/src/System.sol"; -import { NumberList, NumberListTableId } from "../codegen/index.sol"; +import { NumberList } from "../codegen/index.sol"; contract NumberListSystem is System { function set(uint32[] memory list) public { @@ -22,7 +22,7 @@ contract NumberListSystem is System { } bytes32[] memory emptyKey; - StoreSwitch.pushToDynamicField(NumberListTableId, emptyKey, 0, EncodeArray.encode(list)); + StoreSwitch.pushToDynamicField(NumberList._tableId, emptyKey, 0, EncodeArray.encode(list)); } function pop() public { diff --git a/e2e/packages/sync-test/compare/compare.test.ts b/e2e/packages/sync-test/compare/compare.test.ts index f3bb9b5351..c6d7f0f8f7 100644 --- a/e2e/packages/sync-test/compare/compare.test.ts +++ b/e2e/packages/sync-test/compare/compare.test.ts @@ -35,7 +35,7 @@ function setRecord( address: Address, tableId: TableId, key: Key, - data: Data + data: Data, ): void { state[address.toLowerCase()] ??= {}; state[address.toLowerCase()][tableId] ??= {}; @@ -46,7 +46,7 @@ function getRecord( state: Record>>, address: Address, tableId: TableId, - key: Key + key: Key, ): Data | undefined { return state[address]?.[tableId]?.[key]; } diff --git a/e2e/packages/sync-test/data/callPageFunction.ts b/e2e/packages/sync-test/data/callPageFunction.ts index ece5b02e01..89a9c395a4 100644 --- a/e2e/packages/sync-test/data/callPageFunction.ts +++ b/e2e/packages/sync-test/data/callPageFunction.ts @@ -9,7 +9,7 @@ import { deserialize, serialize } from "./utils"; export async function callPageFunction( page: Page, functionName: string, - args: unknown[] + args: unknown[], ): Promise | undefined> { const context = [functionName, args, serialize.toString(), deserialize.toString()] as const; const serializedValue = await page.evaluate(async ([functionName, args, serializeString, deserializeString]) => { diff --git a/e2e/packages/sync-test/data/callWorld.ts b/e2e/packages/sync-test/data/callWorld.ts index c19e1d9029..c6b58c04c6 100644 --- a/e2e/packages/sync-test/data/callWorld.ts +++ b/e2e/packages/sync-test/data/callWorld.ts @@ -23,6 +23,6 @@ export function callWorld(page: Page, method: T throw new Error([`Error executing ${_method} with args:`, JSON.stringify(_args), error].join("\n\n")); }); }, - [method, args] + [method, args], ); } diff --git a/e2e/packages/sync-test/data/types.ts b/e2e/packages/sync-test/data/types.ts index b79ac3f3b6..98369a7426 100644 --- a/e2e/packages/sync-test/data/types.ts +++ b/e2e/packages/sync-test/data/types.ts @@ -2,9 +2,10 @@ import { SchemaAbiType, SchemaAbiTypeToPrimitiveType } from "@latticexyz/schema-type"; import config from "../../contracts/mud.config"; import { Hex } from "viem"; -type SchemaToPrimitive = Schema extends Record - ? { [key in keyof Schema]: SchemaAbiTypeToPrimitiveType } - : never; +type SchemaToPrimitive = + Schema extends Record + ? { [key in keyof Schema]: SchemaAbiTypeToPrimitiveType } + : never; type Key = SchemaToPrimitive< (typeof config)["tables"][Table]["keySchema"] diff --git a/e2e/packages/sync-test/indexerSync.test.ts b/e2e/packages/sync-test/indexerSync.test.ts index f23edf5f16..3585c6e4a2 100644 --- a/e2e/packages/sync-test/indexerSync.test.ts +++ b/e2e/packages/sync-test/indexerSync.test.ts @@ -143,7 +143,7 @@ describe("Sync from indexer", async () => { y: -2, zone: "0x6d61703100000000000000000000000000000000000000000000000000000000", }, - ]) + ]), ); // Should not have thrown errors diff --git a/e2e/packages/sync-test/setup/openClientWithRootAccount.ts b/e2e/packages/sync-test/setup/openClientWithRootAccount.ts index 85b88658d6..98158ca286 100644 --- a/e2e/packages/sync-test/setup/openClientWithRootAccount.ts +++ b/e2e/packages/sync-test/setup/openClientWithRootAccount.ts @@ -12,6 +12,6 @@ export async function openClientWithRootAccount(page: Page, options?: { indexerU // I wish I could pass undefined values into URLSearchParams and have them be ignored during stringify ...(process.env.PRIVATE_KEY ? { privateKey: process.env.PRIVATE_KEY } : null), ...(options?.indexerUrl ? { indexerUrl: options?.indexerUrl } : null), - }).toString()}` + }).toString()}`, ); } diff --git a/e2e/packages/sync-test/setup/startBrowserAndPage.ts b/e2e/packages/sync-test/setup/startBrowserAndPage.ts index 0f18151879..9cbced06a0 100644 --- a/e2e/packages/sync-test/setup/startBrowserAndPage.ts +++ b/e2e/packages/sync-test/setup/startBrowserAndPage.ts @@ -2,7 +2,7 @@ import { Browser, Page, chromium } from "@playwright/test"; import chalk from "chalk"; export async function startBrowserAndPage( - reportError: (error: string) => void + reportError: (error: string) => void, ): Promise<{ browser: Browser; page: Page }> { // open browser page const browser = await chromium.launch(); diff --git a/e2e/packages/test-data/generate-bench-data-bulk.ts b/e2e/packages/test-data/generate-bench-data-bulk.ts index 313ad45a7d..c69fad503f 100644 --- a/e2e/packages/test-data/generate-bench-data-bulk.ts +++ b/e2e/packages/test-data/generate-bench-data-bulk.ts @@ -34,7 +34,7 @@ for (let i = 0; i < NUM_RECORDS.length; i++) { const logsFilename = path.join( path.dirname(fileURLToPath(import.meta.url)), - `../../../test-data/world-logs-bulk-${numRecords}.json` + `../../../test-data/world-logs-bulk-${numRecords}.json`, ); console.log("writing", logs.length, "logs to", logsFilename); diff --git a/e2e/packages/test-data/generate-bench-data-query.ts b/e2e/packages/test-data/generate-bench-data-query.ts index d97a976fd4..4e34afe75c 100644 --- a/e2e/packages/test-data/generate-bench-data-query.ts +++ b/e2e/packages/test-data/generate-bench-data-query.ts @@ -30,7 +30,7 @@ const logs = await generateLogs(rpc, async (worldContract) => { const logsFilename = path.join( path.dirname(fileURLToPath(import.meta.url)), - `../../../test-data/world-logs-query.json` + `../../../test-data/world-logs-query.json`, ); console.log("writing", logs.length, "logs to", logsFilename); diff --git a/e2e/packages/test-data/generateLogs.ts b/e2e/packages/test-data/generateLogs.ts index fff5449b2f..ba855efe61 100644 --- a/e2e/packages/test-data/generateLogs.ts +++ b/e2e/packages/test-data/generateLogs.ts @@ -31,7 +31,7 @@ type WorldContract = GetContractReturnType< export async function generateLogs( rpc: string, - transactionHook: (worldContract: WorldContract) => Promise + transactionHook: (worldContract: WorldContract) => Promise, ): Promise { console.log("deploying world"); const { stdout, stderr } = await execa("pnpm", ["mud", "deploy", "--rpc", rpc, "--saveDeployment", "false"], { @@ -88,7 +88,7 @@ export async function generateLogs( encodeEventTopics({ abi: [event], eventName: event.name, - }) + }), ), ], fromBlock: numberToHex(0n), diff --git a/e2e/pnpm-lock.yaml b/e2e/pnpm-lock.yaml index 5f0ff0d145..cce221a655 100644 --- a/e2e/pnpm-lock.yaml +++ b/e2e/pnpm-lock.yaml @@ -112,8 +112,8 @@ importers: specifier: https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1 version: github.com/foundry-rs/forge-std/74cfb77e308dd188d2f58864aaf44963ae6b88b1 prettier: - specifier: ^2.6.2 - version: 2.6.2 + specifier: 3.2.5 + version: 3.2.5 rimraf: specifier: ^3.0.2 version: 3.0.2 @@ -1531,9 +1531,9 @@ packages: resolution: {integrity: sha512-+JD93VELV9gHkqpV5gdL5/70HdGtEw4/XE1S4BC8f1mcPmdib3K5XsKVbnR1XcAyC41zOnifJ+9YRKxdIsXiUw==} dev: true - /prettier@2.6.2: - resolution: {integrity: sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew==} - engines: {node: '>=10.13.0'} + /prettier@3.2.5: + resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==} + engines: {node: '>=14'} hasBin: true dev: true diff --git a/examples/minimal/packages/client-phaser/src/mud/createSystemCalls.ts b/examples/minimal/packages/client-phaser/src/mud/createSystemCalls.ts index 1e0c674320..37203654b1 100644 --- a/examples/minimal/packages/client-phaser/src/mud/createSystemCalls.ts +++ b/examples/minimal/packages/client-phaser/src/mud/createSystemCalls.ts @@ -7,7 +7,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { worldContract, waitForTransaction }: SetupNetworkResult, - { CounterTable }: ClientComponents + { CounterTable }: ClientComponents, ) { const increment = async () => { const tx = await worldContract.write.increment(); diff --git a/examples/minimal/packages/client-phaser/src/ui/App.tsx b/examples/minimal/packages/client-phaser/src/ui/App.tsx index 69529815b5..0ddd731ec7 100644 --- a/examples/minimal/packages/client-phaser/src/ui/App.tsx +++ b/examples/minimal/packages/client-phaser/src/ui/App.tsx @@ -26,7 +26,7 @@ export const App = () => { worldAbi: networkLayer.network.worldContract.abi, write$: networkLayer.network.write$, recsWorld: networkLayer.world, - }) + }), ); } }, [networkLayer]); diff --git a/examples/minimal/packages/client-phaser/src/ui/hooks/usePhaserLayer.tsx b/examples/minimal/packages/client-phaser/src/ui/hooks/usePhaserLayer.tsx index f0a4c36da7..c6292e57ff 100644 --- a/examples/minimal/packages/client-phaser/src/ui/hooks/usePhaserLayer.tsx +++ b/examples/minimal/packages/client-phaser/src/ui/hooks/usePhaserLayer.tsx @@ -79,7 +79,7 @@ export const usePhaserLayer = ({ networkLayer }: Props) => { } } }, - [container] + [container], ); return useMemo(() => ({ ref, phaserLayer }), [ref, phaserLayer]); diff --git a/examples/minimal/packages/client-react/src/index.tsx b/examples/minimal/packages/client-react/src/index.tsx index da8d70f020..1b005dc561 100644 --- a/examples/minimal/packages/client-react/src/index.tsx +++ b/examples/minimal/packages/client-react/src/index.tsx @@ -13,7 +13,7 @@ setup().then(async (result) => { root.render( - + , ); // https://vitejs.dev/guide/env-and-mode.html diff --git a/examples/minimal/packages/client-react/src/mud/createSystemCalls.ts b/examples/minimal/packages/client-react/src/mud/createSystemCalls.ts index 1e0c674320..37203654b1 100644 --- a/examples/minimal/packages/client-react/src/mud/createSystemCalls.ts +++ b/examples/minimal/packages/client-react/src/mud/createSystemCalls.ts @@ -7,7 +7,7 @@ export type SystemCalls = ReturnType; export function createSystemCalls( { worldContract, waitForTransaction }: SetupNetworkResult, - { CounterTable }: ClientComponents + { CounterTable }: ClientComponents, ) { const increment = async () => { const tx = await worldContract.write.increment(); diff --git a/examples/minimal/packages/contracts/package.json b/examples/minimal/packages/contracts/package.json index 1bd8b4276b..7d49c273a0 100644 --- a/examples/minimal/packages/contracts/package.json +++ b/examples/minimal/packages/contracts/package.json @@ -27,8 +27,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "rimraf": "^3.0.2", "solhint": "^3.4.1", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", diff --git a/examples/minimal/packages/contracts/script/PostDeploy.s.sol b/examples/minimal/packages/contracts/script/PostDeploy.s.sol index 9a760231f0..f39faa8fed 100644 --- a/examples/minimal/packages/contracts/script/PostDeploy.s.sol +++ b/examples/minimal/packages/contracts/script/PostDeploy.s.sol @@ -7,7 +7,7 @@ import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; import { ResourceId, WorldResourceIdLib, WorldResourceIdInstance } from "@latticexyz/world/src/WorldResourceId.sol"; import { RESOURCE_SYSTEM } from "@latticexyz/world/src/worldResourceTypes.sol"; -import { MessageTable, MessageTableTableId } from "../src/codegen/index.sol"; +import { MessageTable } from "../src/codegen/index.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; import { ChatNamespacedSystem } from "../src/systems/ChatNamespacedSystem.sol"; @@ -36,7 +36,7 @@ contract PostDeploy is Script { IWorld(worldAddress).registerFunctionSelector(systemId, "sendMessage(string)"); // Grant this system access to MessageTable - IWorld(worldAddress).grantAccess(MessageTableTableId, address(chatNamespacedSystem)); + IWorld(worldAddress).grantAccess(MessageTable._tableId, address(chatNamespacedSystem)); // ------------------ EXAMPLES ------------------ diff --git a/examples/minimal/packages/contracts/src/codegen/index.sol b/examples/minimal/packages/contracts/src/codegen/index.sol index ac4baf9ad1..172a4254f3 100644 --- a/examples/minimal/packages/contracts/src/codegen/index.sol +++ b/examples/minimal/packages/contracts/src/codegen/index.sol @@ -3,6 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { CounterTable, CounterTableTableId } from "./tables/CounterTable.sol"; -import { MessageTable, MessageTableTableId } from "./tables/MessageTable.sol"; -import { Inventory, InventoryTableId } from "./tables/Inventory.sol"; +import { CounterTable } from "./tables/CounterTable.sol"; +import { MessageTable } from "./tables/MessageTable.sol"; +import { Inventory } from "./tables/Inventory.sol"; diff --git a/examples/minimal/packages/contracts/src/codegen/tables/CounterTable.sol b/examples/minimal/packages/contracts/src/codegen/tables/CounterTable.sol index d3e5442de7..c9a05bc627 100644 --- a/examples/minimal/packages/contracts/src/codegen/tables/CounterTable.sol +++ b/examples/minimal/packages/contracts/src/codegen/tables/CounterTable.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "CounterTable", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e7465725461626c6500000000); -ResourceId constant CounterTableTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library CounterTable { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "CounterTable", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e7465725461626c6500000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,21 +49,21 @@ library CounterTable { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config (using the specified store). */ function register(IStore _store) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + _store.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/examples/minimal/packages/contracts/src/codegen/tables/Inventory.sol b/examples/minimal/packages/contracts/src/codegen/tables/Inventory.sol index 1b5c163695..f04fddc6e7 100644 --- a/examples/minimal/packages/contracts/src/codegen/tables/Inventory.sol +++ b/examples/minimal/packages/contracts/src/codegen/tables/Inventory.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,51 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Inventory", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000496e76656e746f727900000000000000); -ResourceId constant InventoryTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library Inventory { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](3); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.UINT32; - _keySchema[2] = SchemaType.UINT32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Inventory", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000496e76656e746f727900000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, uint32, uint32) + Schema constant _keySchema = Schema.wrap(0x001c030061030300000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -84,14 +52,14 @@ library Inventory { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/examples/minimal/packages/contracts/src/codegen/tables/MessageTable.sol b/examples/minimal/packages/contracts/src/codegen/tables/MessageTable.sol index aadbffde7c..343a9aac91 100644 --- a/examples/minimal/packages/contracts/src/codegen/tables/MessageTable.sol +++ b/examples/minimal/packages/contracts/src/codegen/tables/MessageTable.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "MessageTable", typeId: RESOURCE_OFFCHAIN_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x6f7400000000000000000000000000004d6573736167655461626c6500000000); -ResourceId constant MessageTableTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library MessageTable { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "MessageTable", typeId: RESOURCE_OFFCHAIN_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x6f7400000000000000000000000000004d6573736167655461626c6500000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (string) + Schema constant _valueSchema = Schema.wrap(0x00000001c5000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library MessageTable { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/examples/minimal/packages/contracts/src/codegen/world/IChatSystem.sol b/examples/minimal/packages/contracts/src/codegen/world/IChatSystem.sol index 48e977a1c7..9903a303cd 100644 --- a/examples/minimal/packages/contracts/src/codegen/world/IChatSystem.sol +++ b/examples/minimal/packages/contracts/src/codegen/world/IChatSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IChatSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IChatSystem { diff --git a/examples/minimal/packages/contracts/src/codegen/world/IIncrementSystem.sol b/examples/minimal/packages/contracts/src/codegen/world/IIncrementSystem.sol index 8989fe0eae..8b31683a45 100644 --- a/examples/minimal/packages/contracts/src/codegen/world/IIncrementSystem.sol +++ b/examples/minimal/packages/contracts/src/codegen/world/IIncrementSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IIncrementSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IIncrementSystem { diff --git a/examples/minimal/packages/contracts/src/codegen/world/IInventorySystem.sol b/examples/minimal/packages/contracts/src/codegen/world/IInventorySystem.sol index 2b59bb3249..98494820df 100644 --- a/examples/minimal/packages/contracts/src/codegen/world/IInventorySystem.sol +++ b/examples/minimal/packages/contracts/src/codegen/world/IInventorySystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IInventorySystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IInventorySystem { diff --git a/examples/minimal/packages/contracts/src/codegen/world/IStructSystem.sol b/examples/minimal/packages/contracts/src/codegen/world/IStructSystem.sol index 061c1bfce9..a95d9eb919 100644 --- a/examples/minimal/packages/contracts/src/codegen/world/IStructSystem.sol +++ b/examples/minimal/packages/contracts/src/codegen/world/IStructSystem.sol @@ -7,6 +7,7 @@ import { BytesStruct, StringStruct } from "./../../systems/structs.sol"; /** * @title IStructSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IStructSystem { diff --git a/examples/minimal/packages/contracts/src/codegen/world/IWorld.sol b/examples/minimal/packages/contracts/src/codegen/world/IWorld.sol index 31f6c0439b..6eb7845c59 100644 --- a/examples/minimal/packages/contracts/src/codegen/world/IWorld.sol +++ b/examples/minimal/packages/contracts/src/codegen/world/IWorld.sol @@ -12,10 +12,9 @@ import { IStructSystem } from "./IStructSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, IChatSystem, IIncrementSystem, IInventorySystem, IStructSystem { - -} +interface IWorld is IBaseWorld, IChatSystem, IIncrementSystem, IInventorySystem, IStructSystem {} diff --git a/examples/minimal/packages/contracts/test/ChatNamespaced.t.sol b/examples/minimal/packages/contracts/test/ChatNamespaced.t.sol index eaecdb806a..fe27846c43 100644 --- a/examples/minimal/packages/contracts/test/ChatNamespaced.t.sol +++ b/examples/minimal/packages/contracts/test/ChatNamespaced.t.sol @@ -4,10 +4,10 @@ pragma solidity >=0.8.24; import "forge-std/Test.sol"; import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; -import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; +import { IStoreEvents } from "@latticexyz/store/src/IStoreEvents.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { MessageTable, MessageTableTableId } from "../src/codegen/index.sol"; +import { MessageTable } from "../src/codegen/index.sol"; import { IChatNamespacedSystem } from "../src/interfaces/IChatNamespacedSystem.sol"; contract ChatNamespacedTest is MudTest { @@ -15,8 +15,8 @@ contract ChatNamespacedTest is MudTest { bytes32[] memory keyTuple; string memory value = "test"; vm.expectEmit(true, true, true, true); - emit StoreCore.Store_SetRecord( - MessageTableTableId, + emit IStoreEvents.Store_SetRecord( + MessageTable._tableId, keyTuple, new bytes(0), MessageTable.encodeLengths(value), diff --git a/examples/minimal/packages/contracts/test/CounterTest.t.sol b/examples/minimal/packages/contracts/test/CounterTest.t.sol index 81cfc6df7d..1c26465979 100644 --- a/examples/minimal/packages/contracts/test/CounterTest.t.sol +++ b/examples/minimal/packages/contracts/test/CounterTest.t.sol @@ -6,7 +6,7 @@ import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { CounterTable, CounterTableTableId } from "../src/codegen/index.sol"; +import { CounterTable } from "../src/codegen/index.sol"; contract CounterTest is MudTest { function testWorldExists() public { @@ -32,7 +32,7 @@ contract CounterTest is MudTest { // TODO: re-enable the KeysWithValueModule in mud.config.ts once it supports singleton keys // function testKeysWithValue() public { // uint32 counter = CounterTable.get(); - // bytes32[] memory keysWithValue = getKeysWithValue(CounterTableTableId, CounterTable.encode(counter)); + // bytes32[] memory keysWithValue = getKeysWithValue(CounterTable._tableId, CounterTable.encode(counter)); // assertEq(keysWithValue.length, 1); // } } diff --git a/examples/minimal/packages/contracts/test/StructTest.t.sol b/examples/minimal/packages/contracts/test/StructTest.t.sol index a6789628ef..b57273ff28 100644 --- a/examples/minimal/packages/contracts/test/StructTest.t.sol +++ b/examples/minimal/packages/contracts/test/StructTest.t.sol @@ -6,7 +6,7 @@ import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { CounterTable, CounterTableTableId } from "../src/codegen/index.sol"; +import { CounterTable } from "../src/codegen/index.sol"; import { BytesStruct, StringStruct } from "../src/systems/structs.sol"; contract StructTest is MudTest { diff --git a/examples/minimal/pnpm-lock.yaml b/examples/minimal/pnpm-lock.yaml index 932aaf3a72..f14ec12a18 100644 --- a/examples/minimal/pnpm-lock.yaml +++ b/examples/minimal/pnpm-lock.yaml @@ -339,11 +339,11 @@ importers: specifier: https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1 version: github.com/foundry-rs/forge-std/74cfb77e308dd188d2f58864aaf44963ae6b88b1 prettier: - specifier: ^2.6.2 - version: 2.6.2 + specifier: 3.2.5 + version: 3.2.5 prettier-plugin-solidity: - specifier: 1.1.3 - version: 1.1.3(prettier@2.6.2) + specifier: 1.3.1 + version: 1.3.1(prettier@3.2.5) rimraf: specifier: ^3.0.2 version: 3.0.2 @@ -1032,6 +1032,10 @@ packages: antlr4ts: 0.5.0-alpha.4 dev: true + /@solidity-parser/parser@0.17.0: + resolution: {integrity: sha512-Nko8R0/kUo391jsEHHxrGM07QFdnPGvlmox4rmH0kNiNAashItAilhy4Mv4pK5gQmW5f4sXAF58fwJbmlkGcVw==} + dev: true + /@solidstate/contracts@0.0.52: resolution: {integrity: sha512-xSBn5oLnfYtgNYrsRq/COlWHt0NxK26PFQ3FvI2DDMAFpZKFsffGLzUl8umezj2gVKpN7EZ+EVLdPKjqx6eUOw==} dev: true @@ -2885,22 +2889,16 @@ packages: engines: {node: '>= 0.8.0'} dev: true - /prettier-plugin-solidity@1.1.3(prettier@2.6.2): - resolution: {integrity: sha512-fQ9yucPi2sBbA2U2Xjh6m4isUTJ7S7QLc/XDDsktqqxYfTwdYKJ0EnnywXHwCGAaYbQNK+HIYPL1OemxuMsgeg==} - engines: {node: '>=12'} + /prettier-plugin-solidity@1.3.1(prettier@3.2.5): + resolution: {integrity: sha512-MN4OP5I2gHAzHZG1wcuJl0FsLS3c4Cc5494bbg+6oQWBPuEamjwDvmGfFMZ6NFzsh3Efd9UUxeT7ImgjNH4ozA==} + engines: {node: '>=16'} peerDependencies: - prettier: '>=2.3.0 || >=3.0.0-alpha.0' + prettier: '>=2.3.0' dependencies: - '@solidity-parser/parser': 0.16.0 - prettier: 2.6.2 - semver: 7.5.0 - solidity-comments-extractor: 0.0.7 - dev: true - - /prettier@2.6.2: - resolution: {integrity: sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew==} - engines: {node: '>=10.13.0'} - hasBin: true + '@solidity-parser/parser': 0.17.0 + prettier: 3.2.5 + semver: 7.6.0 + solidity-comments-extractor: 0.0.8 dev: true /prettier@2.8.8: @@ -2911,6 +2909,12 @@ packages: dev: true optional: true + /prettier@3.2.5: + resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==} + engines: {node: '>=14'} + hasBin: true + dev: true + /prop-types@15.8.1: resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} dependencies: @@ -3096,6 +3100,14 @@ packages: lru-cache: 6.0.0 dev: true + /semver@7.6.0: + resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} + engines: {node: '>=10'} + hasBin: true + dependencies: + lru-cache: 6.0.0 + dev: true + /shallowequal@1.1.0: resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==} dev: false @@ -3167,8 +3179,8 @@ packages: prettier: 2.8.8 dev: true - /solidity-comments-extractor@0.0.7: - resolution: {integrity: sha512-wciNMLg/Irp8OKGrh3S2tfvZiZ0NEyILfcRCXCD4mp7SgK/i9gzLfhY2hY7VMCQJ3kH9UB9BzNdibIVMchzyYw==} + /solidity-comments-extractor@0.0.8: + resolution: {integrity: sha512-htM7Vn6LhHreR+EglVMd2s+sZhcXAirB1Zlyrv5zBuTxieCvjfnRpd7iZk75m/u6NOlEyQ94C6TWbBn2cY7w8g==} dev: true /source-map-js@1.0.2: diff --git a/examples/multiple-accounts/package.json b/examples/multiple-accounts/package.json index 16893bf7de..9e94423c4d 100644 --- a/examples/multiple-accounts/package.json +++ b/examples/multiple-accounts/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/examples/multiple-accounts/packages/client/src/index.tsx b/examples/multiple-accounts/packages/client/src/index.tsx index 3ba2a44052..c9b662c9f0 100644 --- a/examples/multiple-accounts/packages/client/src/index.tsx +++ b/examples/multiple-accounts/packages/client/src/index.tsx @@ -13,7 +13,7 @@ setup().then(async (result) => { root.render( - + , ); // https://vitejs.dev/guide/env-and-mode.html diff --git a/examples/multiple-accounts/packages/contracts/package.json b/examples/multiple-accounts/packages/contracts/package.json index 6b71970f9e..461ceb6001 100644 --- a/examples/multiple-accounts/packages/contracts/package.json +++ b/examples/multiple-accounts/packages/contracts/package.json @@ -25,8 +25,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "2.0.0-next.15", "solhint-plugin-mud": "2.0.0-next.15" diff --git a/examples/multiple-accounts/packages/contracts/src/codegen/index.sol b/examples/multiple-accounts/packages/contracts/src/codegen/index.sol index 0746454b44..5813f4d78d 100644 --- a/examples/multiple-accounts/packages/contracts/src/codegen/index.sol +++ b/examples/multiple-accounts/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { LastCall, LastCallData, LastCallTableId } from "./tables/LastCall.sol"; +import { LastCall, LastCallData } from "./tables/LastCall.sol"; diff --git a/examples/multiple-accounts/packages/contracts/src/codegen/tables/LastCall.sol b/examples/multiple-accounts/packages/contracts/src/codegen/tables/LastCall.sol index 63fc9b3fb1..6ae2f1ad37 100644 --- a/examples/multiple-accounts/packages/contracts/src/codegen/tables/LastCall.sol +++ b/examples/multiple-accounts/packages/contracts/src/codegen/tables/LastCall.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,55 +11,27 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "LastCall", name: "LastCall", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74624c61737443616c6c0000000000004c61737443616c6c0000000000000000); -ResourceId constant LastCallTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0034020020140000000000000000000000000000000000000000000000000000 -); - struct LastCallData { uint256 callTime; address sender; } library LastCall { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.ADDRESS; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "LastCall", name: "LastCall", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74624c61737443616c6c0000000000004c61737443616c6c0000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0034020020140000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.UINT256; - _valueSchema[1] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address) + Schema constant _keySchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256, address) + Schema constant _valueSchema = Schema.wrap(0x003402001f610000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -87,14 +56,14 @@ library LastCall { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/examples/multiple-accounts/packages/contracts/src/codegen/world/ILastCallSystem.sol b/examples/multiple-accounts/packages/contracts/src/codegen/world/ILastCallSystem.sol index 85bccbafea..69c45f210c 100644 --- a/examples/multiple-accounts/packages/contracts/src/codegen/world/ILastCallSystem.sol +++ b/examples/multiple-accounts/packages/contracts/src/codegen/world/ILastCallSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title ILastCallSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface ILastCallSystem { diff --git a/examples/multiple-accounts/packages/contracts/src/codegen/world/ITasksSystem.sol b/examples/multiple-accounts/packages/contracts/src/codegen/world/ITasksSystem.sol index 81127a78eb..4a18791ccf 100644 --- a/examples/multiple-accounts/packages/contracts/src/codegen/world/ITasksSystem.sol +++ b/examples/multiple-accounts/packages/contracts/src/codegen/world/ITasksSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title ITasksSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface ITasksSystem { diff --git a/examples/multiple-accounts/packages/contracts/src/codegen/world/IWorld.sol b/examples/multiple-accounts/packages/contracts/src/codegen/world/IWorld.sol index a6f78a1166..2c909e6f4f 100644 --- a/examples/multiple-accounts/packages/contracts/src/codegen/world/IWorld.sol +++ b/examples/multiple-accounts/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { ILastCallSystem } from "./ILastCallSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, ILastCallSystem { - -} +interface IWorld is IBaseWorld, ILastCallSystem {} diff --git a/examples/multiple-accounts/pnpm-lock.yaml b/examples/multiple-accounts/pnpm-lock.yaml index 7015942044..878afde32c 100644 --- a/examples/multiple-accounts/pnpm-lock.yaml +++ b/examples/multiple-accounts/pnpm-lock.yaml @@ -14,9 +14,6 @@ importers: '@types/debug': specifier: 4.1.7 version: 4.1.7 - '@types/prettier': - specifier: 2.7.2 - version: 2.7.2 '@typescript-eslint/eslint-plugin': specifier: 5.46.1 version: 5.46.1(@typescript-eslint/parser@5.46.1)(eslint@8.29.0)(typescript@5.1.6) @@ -128,11 +125,11 @@ importers: specifier: https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1 version: github.com/foundry-rs/forge-std/74cfb77e308dd188d2f58864aaf44963ae6b88b1 prettier: - specifier: ^2.6.2 - version: 2.8.8 + specifier: 3.2.5 + version: 3.2.5 prettier-plugin-solidity: - specifier: 1.1.3 - version: 1.1.3(prettier@2.8.8) + specifier: 1.3.1 + version: 1.3.1(prettier@3.2.5) solhint: specifier: ^3.3.7 version: 3.6.2(typescript@5.1.6) @@ -700,6 +697,10 @@ packages: antlr4ts: 0.5.0-alpha.4 dev: true + /@solidity-parser/parser@0.17.0: + resolution: {integrity: sha512-Nko8R0/kUo391jsEHHxrGM07QFdnPGvlmox4rmH0kNiNAashItAilhy4Mv4pK5gQmW5f4sXAF58fwJbmlkGcVw==} + dev: true + /@types/debug@4.1.7: resolution: {integrity: sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==} dependencies: @@ -720,10 +721,6 @@ packages: undici-types: 5.26.5 dev: true - /@types/prettier@2.7.2: - resolution: {integrity: sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==} - dev: true - /@types/prop-types@15.7.11: resolution: {integrity: sha512-ga8y9v9uyeiLdpKddhxYQkxNDrfvuPrlFb0N1qnZZByvcElJaXthF1UhvCh9TLWJBEHeNtdnbysW7Y6Uq8CVng==} dev: true @@ -2285,22 +2282,30 @@ packages: engines: {node: '>= 0.8.0'} dev: true - /prettier-plugin-solidity@1.1.3(prettier@2.8.8): - resolution: {integrity: sha512-fQ9yucPi2sBbA2U2Xjh6m4isUTJ7S7QLc/XDDsktqqxYfTwdYKJ0EnnywXHwCGAaYbQNK+HIYPL1OemxuMsgeg==} - engines: {node: '>=12'} + /prettier-plugin-solidity@1.3.1(prettier@3.2.5): + resolution: {integrity: sha512-MN4OP5I2gHAzHZG1wcuJl0FsLS3c4Cc5494bbg+6oQWBPuEamjwDvmGfFMZ6NFzsh3Efd9UUxeT7ImgjNH4ozA==} + engines: {node: '>=16'} peerDependencies: - prettier: '>=2.3.0 || >=3.0.0-alpha.0' + prettier: '>=2.3.0' dependencies: - '@solidity-parser/parser': 0.16.2 - prettier: 2.8.8 + '@solidity-parser/parser': 0.17.0 + prettier: 3.2.5 semver: 7.5.4 - solidity-comments-extractor: 0.0.7 + solidity-comments-extractor: 0.0.8 dev: true /prettier@2.8.8: resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} engines: {node: '>=10.13.0'} hasBin: true + requiresBuild: true + dev: true + optional: true + + /prettier@3.2.5: + resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==} + engines: {node: '>=14'} + hasBin: true dev: true /prop-types@15.8.1: @@ -2539,8 +2544,8 @@ packages: - typescript dev: true - /solidity-comments-extractor@0.0.7: - resolution: {integrity: sha512-wciNMLg/Irp8OKGrh3S2tfvZiZ0NEyILfcRCXCD4mp7SgK/i9gzLfhY2hY7VMCQJ3kH9UB9BzNdibIVMchzyYw==} + /solidity-comments-extractor@0.0.8: + resolution: {integrity: sha512-htM7Vn6LhHreR+EglVMd2s+sZhcXAirB1Zlyrv5zBuTxieCvjfnRpd7iZk75m/u6NOlEyQ94C6TWbBn2cY7w8g==} dev: true /source-map-js@1.0.2: diff --git a/package.json b/package.json index 17c7bc3c33..b9abb3e9e1 100644 --- a/package.json +++ b/package.json @@ -45,8 +45,8 @@ "execa": "^7.0.0", "husky": ">=6", "lint-staged": ">=10", - "prettier": "^2.8.4", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "rimraf": "^3.0.2", "turbo": "^1.9.3", "typescript": "5.1.6" diff --git a/packages/abi-ts/src/abi-ts.ts b/packages/abi-ts/src/abi-ts.ts index 8d12d0ee0a..a6093d52ec 100755 --- a/packages/abi-ts/src/abi-ts.ts +++ b/packages/abi-ts/src/abi-ts.ts @@ -21,7 +21,7 @@ yargs(hideBin(process.argv)) console.error(chalk.red(msg)); if (msg.includes("Missing required argument")) { console.log( - chalk.yellow(`Run 'pnpm abi-ts ${process.argv[2]} --help' for a list of available and required arguments.`) + chalk.yellow(`Run 'pnpm abi-ts ${process.argv[2]} --help' for a list of available and required arguments.`), ); } diff --git a/packages/block-logs-stream/CHANGELOG.md b/packages/block-logs-stream/CHANGELOG.md index 545ea08a88..7e9de47863 100644 --- a/packages/block-logs-stream/CHANGELOG.md +++ b/packages/block-logs-stream/CHANGELOG.md @@ -418,7 +418,7 @@ const latestBlockNumber$ = latestBlock$.pipe( filter(isNonPendingBlock), - map((block) => block.number) + map((block) => block.number), ); latestBlockNumber$ @@ -434,7 +434,7 @@ "event StoreEphemeralRecord(bytes32 table, bytes32[] key, bytes data)", ]), }), - mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))) + mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))), ) .subscribe((block) => { console.log("got events for block", block); diff --git a/packages/block-logs-stream/README.md b/packages/block-logs-stream/README.md index a76e15825f..0d7ccc924f 100644 --- a/packages/block-logs-stream/README.md +++ b/packages/block-logs-stream/README.md @@ -32,7 +32,7 @@ latestBlockNumber$ "event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)", ]), }), - mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))) + mergeMap(({ logs }) => from(groupLogsByBlockNumber(logs))), ) .subscribe((block) => { console.log("got events for block", block); diff --git a/packages/block-logs-stream/src/blockRangeToLogs.test.ts b/packages/block-logs-stream/src/blockRangeToLogs.test.ts index a0474841b8..607a8dea77 100644 --- a/packages/block-logs-stream/src/blockRangeToLogs.test.ts +++ b/packages/block-logs-stream/src/blockRangeToLogs.test.ts @@ -41,7 +41,7 @@ describe("blockRangeToLogs", () => { publicClient, address: "0x", events: [], - }) + }), ); (async (): Promise => { diff --git a/packages/block-logs-stream/src/blockRangeToLogs.ts b/packages/block-logs-stream/src/blockRangeToLogs.ts index 825320f14d..9a87da6242 100644 --- a/packages/block-logs-stream/src/blockRangeToLogs.ts +++ b/packages/block-logs-stream/src/blockRangeToLogs.ts @@ -65,12 +65,12 @@ export function blockRangeToLogs({ fromBlock, toBlock, maxBlockRange, - }) + }), ).pipe( tap(({ toBlock }) => { fromBlock = toBlock + 1n; - }) + }), ); - }) + }), ); } diff --git a/packages/block-logs-stream/src/fetchLogs.test.ts b/packages/block-logs-stream/src/fetchLogs.test.ts index 7f95f507b9..4bd28cb1c2 100644 --- a/packages/block-logs-stream/src/fetchLogs.test.ts +++ b/packages/block-logs-stream/src/fetchLogs.test.ts @@ -150,7 +150,7 @@ describe("fetchLogs", () => { code: -32005, message: "block range exceeded", }, - }) + }), ); } @@ -374,7 +374,7 @@ describe("fetchLogs", () => { code: -32005, message: "rate limit exceeded", }, - }) + }), ); } diff --git a/packages/block-logs-stream/src/groupLogsByBlockNumber.ts b/packages/block-logs-stream/src/groupLogsByBlockNumber.ts index b0656acfbc..37fd614d35 100644 --- a/packages/block-logs-stream/src/groupLogsByBlockNumber.ts +++ b/packages/block-logs-stream/src/groupLogsByBlockNumber.ts @@ -24,7 +24,7 @@ export type GroupLogsByBlockNumberResult = { */ export function groupLogsByBlockNumber( logs: readonly TLog[], - toBlock?: BlockNumber + toBlock?: BlockNumber, ): GroupLogsByBlockNumberResult { const blockNumbers = Array.from(new Set(logs.map((log) => log.blockNumber))); blockNumbers.sort(bigIntSort); diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 0bec448c15..705083a33e 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1135,7 +1135,7 @@ .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/packages/cli/contracts/src/codegen/index.sol b/packages/cli/contracts/src/codegen/index.sol index 80f2b14a6f..a785c0c5bd 100644 --- a/packages/cli/contracts/src/codegen/index.sol +++ b/packages/cli/contracts/src/codegen/index.sol @@ -3,9 +3,9 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Statics, StaticsData, StaticsTableId } from "./tables/Statics.sol"; -import { Dynamics1, Dynamics1Data, Dynamics1TableId } from "./tables/Dynamics1.sol"; -import { Dynamics2, Dynamics2Data, Dynamics2TableId } from "./tables/Dynamics2.sol"; -import { Singleton, SingletonTableId } from "./tables/Singleton.sol"; -import { Offchain, OffchainTableId } from "./tables/Offchain.sol"; -import { UserTyped, UserTypedData, UserTypedTableId } from "./tables/UserTyped.sol"; +import { Statics, StaticsData } from "./tables/Statics.sol"; +import { Dynamics1, Dynamics1Data } from "./tables/Dynamics1.sol"; +import { Dynamics2, Dynamics2Data } from "./tables/Dynamics2.sol"; +import { Singleton } from "./tables/Singleton.sol"; +import { Offchain } from "./tables/Offchain.sol"; +import { UserTyped, UserTypedData } from "./tables/UserTyped.sol"; diff --git a/packages/cli/contracts/src/codegen/tables/Dynamics1.sol b/packages/cli/contracts/src/codegen/tables/Dynamics1.sol index 7267718a35..c9f147afdd 100644 --- a/packages/cli/contracts/src/codegen/tables/Dynamics1.sol +++ b/packages/cli/contracts/src/codegen/tables/Dynamics1.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,19 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Dynamics1", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000044796e616d6963733100000000000000); -ResourceId constant Dynamics1TableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000500000000000000000000000000000000000000000000000000000000 -); - struct Dynamics1Data { bytes32[1] staticB32; int32[2] staticI32; @@ -36,39 +25,16 @@ struct Dynamics1Data { } library Dynamics1 { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Dynamics1", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000044796e616d6963733100000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000500000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](5); - _valueSchema[0] = SchemaType.BYTES32_ARRAY; - _valueSchema[1] = SchemaType.INT32_ARRAY; - _valueSchema[2] = SchemaType.UINT128_ARRAY; - _valueSchema[3] = SchemaType.ADDRESS_ARRAY; - _valueSchema[4] = SchemaType.BOOL_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32[], int32[], uint128[], address[], bool[]) + Schema constant _valueSchema = Schema.wrap(0x00000005c18571c3c20000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -96,14 +62,14 @@ library Dynamics1 { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/contracts/src/codegen/tables/Dynamics2.sol b/packages/cli/contracts/src/codegen/tables/Dynamics2.sol index 4c877d16a6..07bc193055 100644 --- a/packages/cli/contracts/src/codegen/tables/Dynamics2.sol +++ b/packages/cli/contracts/src/codegen/tables/Dynamics2.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,19 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Dynamics2", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000044796e616d6963733200000000000000); -ResourceId constant Dynamics2TableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000300000000000000000000000000000000000000000000000000000000 -); - struct Dynamics2Data { uint64[] u64; string str; @@ -34,37 +23,16 @@ struct Dynamics2Data { } library Dynamics2 { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Dynamics2", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000044796e616d6963733200000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000300000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](3); - _valueSchema[0] = SchemaType.UINT64_ARRAY; - _valueSchema[1] = SchemaType.STRING; - _valueSchema[2] = SchemaType.BYTES; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint64[], string, bytes) + Schema constant _valueSchema = Schema.wrap(0x0000000369c5c400000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -90,14 +58,14 @@ library Dynamics2 { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/contracts/src/codegen/tables/Offchain.sol b/packages/cli/contracts/src/codegen/tables/Offchain.sol index 7d83afabc0..16732168f8 100644 --- a/packages/cli/contracts/src/codegen/tables/Offchain.sol +++ b/packages/cli/contracts/src/codegen/tables/Offchain.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,49 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Offchain", typeId: RESOURCE_OFFCHAIN_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x6f7400000000000000000000000000004f6666636861696e0000000000000000); -ResourceId constant OffchainTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library Offchain { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Offchain", typeId: RESOURCE_OFFCHAIN_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x6f7400000000000000000000000000004f6666636861696e0000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -80,14 +50,14 @@ library Offchain { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/contracts/src/codegen/tables/Singleton.sol b/packages/cli/contracts/src/codegen/tables/Singleton.sol index af76be1d8a..ac7955f7e7 100644 --- a/packages/cli/contracts/src/codegen/tables/Singleton.sol +++ b/packages/cli/contracts/src/codegen/tables/Singleton.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,51 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Singleton", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053696e676c65746f6e00000000000000); -ResourceId constant SingletonTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010320000000000000000000000000000000000000000000000000000000 -); - library Singleton { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Singleton", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053696e676c65746f6e00000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010320000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](4); - _valueSchema[0] = SchemaType.INT256; - _valueSchema[1] = SchemaType.UINT32_ARRAY; - _valueSchema[2] = SchemaType.UINT32_ARRAY; - _valueSchema[3] = SchemaType.UINT32_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (int256, uint32[], uint32[], uint32[]) + Schema constant _valueSchema = Schema.wrap(0x002001033f656565000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -84,14 +52,14 @@ library Singleton { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/contracts/src/codegen/tables/Statics.sol b/packages/cli/contracts/src/codegen/tables/Statics.sol index ef1fcffa55..86453360fe 100644 --- a/packages/cli/contracts/src/codegen/tables/Statics.sol +++ b/packages/cli/contracts/src/codegen/tables/Statics.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,22 +11,14 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { Enum2, Enum1 } from "./../common.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Statics", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053746174696373000000000000000000); -ResourceId constant StaticsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x004a060020041014010100000000000000000000000000000000000000000000 -); - struct StaticsData { uint256 v1; int32 v2; @@ -40,45 +29,16 @@ struct StaticsData { } library Statics { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](6); - _keySchema[0] = SchemaType.UINT256; - _keySchema[1] = SchemaType.INT32; - _keySchema[2] = SchemaType.BYTES16; - _keySchema[3] = SchemaType.ADDRESS; - _keySchema[4] = SchemaType.BOOL; - _keySchema[5] = SchemaType.UINT8; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Statics", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053746174696373000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x004a060020041014010100000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](6); - _valueSchema[0] = SchemaType.UINT256; - _valueSchema[1] = SchemaType.INT32; - _valueSchema[2] = SchemaType.BYTES16; - _valueSchema[3] = SchemaType.ADDRESS; - _valueSchema[4] = SchemaType.BOOL; - _valueSchema[5] = SchemaType.UINT8; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint256, int32, bytes16, address, bool, uint8) + Schema constant _keySchema = Schema.wrap(0x004a06001f234f61600000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256, int32, bytes16, address, bool, uint8) + Schema constant _valueSchema = Schema.wrap(0x004a06001f234f61600000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -112,14 +72,14 @@ library Statics { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/contracts/src/codegen/tables/UserTyped.sol b/packages/cli/contracts/src/codegen/tables/UserTyped.sol index ccb63dbdca..fc3fcf29c8 100644 --- a/packages/cli/contracts/src/codegen/tables/UserTyped.sol +++ b/packages/cli/contracts/src/codegen/tables/UserTyped.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,8 +11,8 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; @@ -23,14 +20,6 @@ import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; import { TestTypeAddress, TestTypeInt64, TestTypeLibrary } from "./../../types.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "UserTyped", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000055736572547970656400000000000000); -ResourceId constant UserTypedTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x004d050014080110200000000000000000000000000000000000000000000000 -); - struct UserTypedData { TestTypeAddress v1; TestTypeInt64 v2; @@ -40,43 +29,16 @@ struct UserTypedData { } library UserTyped { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](5); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.INT64; - _keySchema[2] = SchemaType.BOOL; - _keySchema[3] = SchemaType.UINT128; - _keySchema[4] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "UserTyped", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000055736572547970656400000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x004d050014080110200000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](5); - _valueSchema[0] = SchemaType.ADDRESS; - _valueSchema[1] = SchemaType.INT64; - _valueSchema[2] = SchemaType.BOOL; - _valueSchema[3] = SchemaType.UINT128; - _valueSchema[4] = SchemaType.BYTES32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, int64, bool, uint128, bytes32) + Schema constant _keySchema = Schema.wrap(0x004d05006127600f5f0000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address, int64, bool, uint128, bytes32) + Schema constant _valueSchema = Schema.wrap(0x004d05006127600f5f0000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -108,14 +70,14 @@ library UserTyped { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/cli/src/commands/dev-contracts.ts b/packages/cli/src/commands/dev-contracts.ts index 084c271275..23b7b1d03c 100644 --- a/packages/cli/src/commands/dev-contracts.ts +++ b/packages/cli/src/commands/dev-contracts.ts @@ -106,7 +106,7 @@ const commandModule: CommandModule = { const mutuallyExclusiveOptions = ["mudVersion", "link", "tag", "commit", "restore"]; const numMutuallyExclusiveOptions = mutuallyExclusiveOptions.reduce( (acc, opt) => (options[opt] ? acc + 1 : acc), - 0 + 0, ); if (numMutuallyExclusiveOptions === 0) { diff --git a/packages/cli/src/commands/trace.ts b/packages/cli/src/commands/trace.ts index e6d55a9ece..e8659eb089 100644 --- a/packages/cli/src/commands/trace.ts +++ b/packages/cli/src/commands/trace.ts @@ -63,7 +63,7 @@ const commandModule: CommandModule = { const resolvedConfig = resolveWorldConfig( mudConfig, - existingContracts.map(({ basename }) => basename) + existingContracts.map(({ basename }) => basename), ); // Get worldAddress either from args or from worldsFile diff --git a/packages/cli/src/deploy/configToTables.ts b/packages/cli/src/deploy/configToTables.ts index 4c07a81bb3..3e9b0e5729 100644 --- a/packages/cli/src/deploy/configToTables.ts +++ b/packages/cli/src/deploy/configToTables.ts @@ -14,12 +14,12 @@ type UserTypes = config["userTypes"]; export type TableKey< config extends StoreConfig = StoreConfig, - table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]] + table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]], > = `${config["namespace"]}_${table["name"]}`; export type Table< config extends StoreConfig = StoreConfig, - table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]] + table extends config["tables"][keyof config["tables"]] = config["tables"][keyof config["tables"]], > = { readonly namespace: config["namespace"]; readonly name: table["name"]; @@ -63,6 +63,6 @@ export function configToTables(config: config): Tabl keySchema: resolveUserTypes(table.keySchema, userTypes) as any, valueSchema: resolveUserTypes(table.valueSchema, userTypes) as any, } satisfies Table, - ]) + ]), ) as Tables; } diff --git a/packages/cli/src/deploy/deployWorld.ts b/packages/cli/src/deploy/deployWorld.ts index 16c4c7bc75..7f5bf4ba04 100644 --- a/packages/cli/src/deploy/deployWorld.ts +++ b/packages/cli/src/deploy/deployWorld.ts @@ -10,7 +10,7 @@ import { WorldDeploy } from "./common"; export async function deployWorld( client: Client, deployerAddress: Hex, - salt: Hex + salt: Hex, ): Promise { const worldFactory = await ensureWorldFactory(client, deployerAddress); diff --git a/packages/cli/src/deploy/ensureContract.ts b/packages/cli/src/deploy/ensureContract.ts index b7110bcb1d..d86269ee54 100644 --- a/packages/cli/src/deploy/ensureContract.ts +++ b/packages/cli/src/deploy/ensureContract.ts @@ -32,11 +32,11 @@ export async function ensureContract({ if (deployedBytecodeSize > contractSizeLimit) { console.warn( - `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n` + `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`, ); } else if (deployedBytecodeSize > contractSizeLimit * 0.95) { console.warn( - `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n` + `\nBytecode for ${label} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \`forge build --sizes\` for more info.\n`, ); } @@ -56,7 +56,7 @@ export async function ensureContract({ debug(`failed to deploy ${label}, retrying in ${delay}ms...`); await wait(delay); }, - } + }, ), ]; } diff --git a/packages/cli/src/deploy/ensureDeployer.ts b/packages/cli/src/deploy/ensureDeployer.ts index 709f27d6f3..92c7c136b0 100644 --- a/packages/cli/src/deploy/ensureDeployer.ts +++ b/packages/cli/src/deploy/ensureDeployer.ts @@ -12,7 +12,7 @@ export async function ensureDeployer(client: Client func.signature).join(", ") + wrongSystem.map((func) => func.signature).join(", "), ); } } @@ -59,7 +59,7 @@ export async function ensureFunctions({ debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`); await wait(delay); }, - } + }, ); } return pRetry( @@ -79,8 +79,8 @@ export async function ensureFunctions({ debug(`failed to register function ${func.signature}, retrying in ${delay}ms...`); await wait(delay); }, - } + }, ); - }) + }), ); } diff --git a/packages/cli/src/deploy/ensureModules.ts b/packages/cli/src/deploy/ensureModules.ts index dddef29a09..5a658a85c2 100644 --- a/packages/cli/src/deploy/ensureModules.ts +++ b/packages/cli/src/deploy/ensureModules.ts @@ -68,9 +68,9 @@ export async function ensureModules({ debug(`failed to install module ${mod.name}, retrying in ${delay}ms...`); await wait(delay); }, - } - ) - ) + }, + ), + ), ) ).filter(isDefined); } diff --git a/packages/cli/src/deploy/ensureNamespaceOwner.ts b/packages/cli/src/deploy/ensureNamespaceOwner.ts index 65384d2de3..0771951e90 100644 --- a/packages/cli/src/deploy/ensureNamespaceOwner.ts +++ b/packages/cli/src/deploy/ensureNamespaceOwner.ts @@ -24,7 +24,7 @@ export async function ensureNamespaceOwner({ "existing namespaces:", Array.from(existingNamespaces) .map((namespace) => (namespace === "" ? "" : namespace)) - .join(", ") + .join(", "), ); } @@ -39,7 +39,7 @@ export async function ensureNamespaceOwner({ key: { namespaceId: resourceToHex({ type: "namespace", namespace, name: "" }) }, }); return [namespace, owner]; - }) + }), ); const unauthorizedNamespaces = namespaceOwners @@ -63,8 +63,8 @@ export async function ensureNamespaceOwner({ abi: worldAbi, functionName: "registerNamespace", args: [resourceToHex({ namespace, type: "namespace", name: "" })], - }) - ) + }), + ), ); return registrationTxs; diff --git a/packages/cli/src/deploy/ensureSystems.ts b/packages/cli/src/deploy/ensureSystems.ts index 51bac4ae5b..dc1661a8c2 100644 --- a/packages/cli/src/deploy/ensureSystems.ts +++ b/packages/cli/src/deploy/ensureSystems.ts @@ -32,8 +32,8 @@ export async function ensureSystems({ worldSystems.some( (worldSystem) => worldSystem.systemId === system.systemId && - getAddress(worldSystem.address) === getAddress(system.getAddress(deployerAddress)) - ) + getAddress(worldSystem.address) === getAddress(system.getAddress(deployerAddress)), + ), ); if (existingSystems.length) { debug("existing systems", existingSystems.map(resourceToLabel).join(", ")); @@ -47,15 +47,15 @@ export async function ensureSystems({ worldSystems.some( (worldSystem) => worldSystem.systemId === system.systemId && - getAddress(worldSystem.address) !== getAddress(system.getAddress(deployerAddress)) - ) + getAddress(worldSystem.address) !== getAddress(system.getAddress(deployerAddress)), + ), ); if (systemsToUpgrade.length) { debug("upgrading systems", systemsToUpgrade.map(resourceToLabel).join(", ")); } const systemsToAdd = missingSystems.filter( - (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId) + (system) => !worldSystems.some((worldSystem) => worldSystem.systemId === system.systemId), ); if (systemsToAdd.length) { debug("registering new systems", systemsToAdd.map(resourceToLabel).join(", ")); @@ -90,9 +90,9 @@ export async function ensureSystems({ debug(`failed to register system ${resourceToLabel(system)}, retrying in ${delay}ms...`); await wait(delay); }, - } - ) - ) + }, + ), + ), ); // Adjust system access @@ -101,7 +101,7 @@ export async function ensureSystems({ const currentAccess = worldAccess.filter(({ resourceId }) => systemIds.includes(resourceId)); const desiredAccess = [ ...systems.flatMap((system) => - system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address })) + system.allowedAddresses.map((address) => ({ resourceId: system.systemId, address })), ), ...systems.flatMap((system) => system.allowedSystemIds @@ -111,7 +111,7 @@ export async function ensureSystems({ worldSystems.find((s) => s.systemId === systemId)?.address ?? systems.find((s) => s.systemId === systemId)?.getAddress(deployerAddress), })) - .filter((access): access is typeof access & { address: Address } => access.address != null) + .filter((access): access is typeof access & { address: Address } => access.address != null), ), ]; @@ -119,16 +119,16 @@ export async function ensureSystems({ (access) => !currentAccess.some( ({ resourceId, address }) => - resourceId === access.resourceId && getAddress(address) === getAddress(access.address) - ) + resourceId === access.resourceId && getAddress(address) === getAddress(access.address), + ), ); const accessToRemove = currentAccess.filter( (access) => !desiredAccess.some( ({ resourceId, address }) => - resourceId === access.resourceId && getAddress(address) === getAddress(access.address) - ) + resourceId === access.resourceId && getAddress(address) === getAddress(access.address), + ), ); if (accessToRemove.length) { @@ -156,8 +156,8 @@ export async function ensureSystems({ debug(`failed to revoke access, retrying in ${delay}ms...`); await wait(delay); }, - } - ) + }, + ), ), ...accessToAdd.map((access) => pRetry( @@ -176,8 +176,8 @@ export async function ensureSystems({ debug(`failed to grant access, retrying in ${delay}ms...`); await wait(delay); }, - } - ) + }, + ), ), ]); diff --git a/packages/cli/src/deploy/ensureTables.ts b/packages/cli/src/deploy/ensureTables.ts index 31beddba46..0ab65681bd 100644 --- a/packages/cli/src/deploy/ensureTables.ts +++ b/packages/cli/src/deploy/ensureTables.ts @@ -54,9 +54,9 @@ export async function ensureTables({ debug(`failed to register table ${resourceToLabel(table)}, retrying in ${delay}ms...`); await wait(delay); }, - } - ) - ) + }, + ), + ), ); } diff --git a/packages/cli/src/deploy/ensureWorldFactory.ts b/packages/cli/src/deploy/ensureWorldFactory.ts index 0df1c21508..0c241f7669 100644 --- a/packages/cli/src/deploy/ensureWorldFactory.ts +++ b/packages/cli/src/deploy/ensureWorldFactory.ts @@ -13,7 +13,7 @@ import { Contract } from "./ensureContract"; export async function ensureWorldFactory( client: Client, - deployerAddress: Hex + deployerAddress: Hex, ): Promise
{ const accessManagementSystemDeployedBytecodeSize = size(accessManagementSystemBuild.deployedBytecode.object as Hex); const accessManagementSystemBytecode = accessManagementSystemBuild.bytecode.object as Hex; diff --git a/packages/cli/src/deploy/getFunctions.ts b/packages/cli/src/deploy/getFunctions.ts index 39b7955486..834dd2cecb 100644 --- a/packages/cli/src/deploy/getFunctions.ts +++ b/packages/cli/src/deploy/getFunctions.ts @@ -51,7 +51,7 @@ export async function getFunctions({ systemFunctionSignature, systemFunctionSelector, }; - }) + }), ); return functions; diff --git a/packages/cli/src/deploy/getResourceAccess.ts b/packages/cli/src/deploy/getResourceAccess.ts index e38a2b2cfd..a9642085be 100644 --- a/packages/cli/src/deploy/getResourceAccess.ts +++ b/packages/cli/src/deploy/getResourceAccess.ts @@ -35,8 +35,8 @@ export async function getResourceAccess({ await Promise.all( keys.map( async (key) => - [key, await getTableValue({ client, worldDeploy, table: worldTables.world_ResourceAccess, key })] as const - ) + [key, await getTableValue({ client, worldDeploy, table: worldTables.world_ResourceAccess, key })] as const, + ), ) ) .filter(([, value]) => value.access) diff --git a/packages/cli/src/deploy/getSystems.ts b/packages/cli/src/deploy/getSystems.ts index c87145efc1..b3cfa98eb6 100644 --- a/packages/cli/src/deploy/getSystems.ts +++ b/packages/cli/src/deploy/getSystems.ts @@ -42,6 +42,6 @@ export async function getSystems({ .map(({ address }) => address), functions: systemFunctions, }; - }) + }), ); } diff --git a/packages/cli/src/deploy/getTables.ts b/packages/cli/src/deploy/getTables.ts index 4154f38199..3342c7b9db 100644 --- a/packages/cli/src/deploy/getTables.ts +++ b/packages/cli/src/deploy/getTables.ts @@ -45,7 +45,7 @@ export async function getTables({ const valueAbiTypes = [...valueSchemaFields.staticFields, ...valueSchemaFields.dynamicFields]; const keySchema = Object.fromEntries( - keySchemaFields.staticFields.map((abiType, i) => [keyNames[i], abiType]) + keySchemaFields.staticFields.map((abiType, i) => [keyNames[i], abiType]), ) as KeySchema; const valueSchema = Object.fromEntries(valueAbiTypes.map((abiType, i) => [fieldNames[i], abiType])) as ValueSchema; diff --git a/packages/cli/src/deploy/logsToWorldDeploy.ts b/packages/cli/src/deploy/logsToWorldDeploy.ts index 81091270fd..a6f078766f 100644 --- a/packages/cli/src/deploy/logsToWorldDeploy.ts +++ b/packages/cli/src/deploy/logsToWorldDeploy.ts @@ -37,7 +37,7 @@ export function logsToWorldDeploy(logs: readonly Log[]): ? { storeVersion: hexToString(trim(log.args.storeVersion, { dir: "right" })) } : null), }), - {} + {}, ); if (address == null) throw new Error("could not find world address"); diff --git a/packages/cli/src/deploy/resolveConfig.ts b/packages/cli/src/deploy/resolveConfig.ts index bc56ad8dc2..2cde8cfc1f 100644 --- a/packages/cli/src/deploy/resolveConfig.ts +++ b/packages/cli/src/deploy/resolveConfig.ts @@ -61,7 +61,7 @@ export function resolveConfig({ allowAll: system.openAccess, allowedAddresses: system.accessListAddresses as Hex[], allowedSystemIds: system.accessListSystems.map((name) => - resourceToHex({ type: "system", namespace, name: resolvedConfig.systems[name].name }) + resourceToHex({ type: "system", namespace, name: resolvedConfig.systems[name].name }), ), getAddress: (deployer: Address) => getCreate2Address({ from: deployer, bytecode: contractData.bytecode, salt }), bytecode: contractData.bytecode, @@ -81,8 +81,8 @@ export function resolveConfig({ const names = overlappingSystems.map((system) => system.name); throw new Error( `Found systems with overlapping system ID: ${names.join( - ", " - )}.\n\nSystem IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.` + ", ", + )}.\n\nSystem IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`, ); } @@ -96,9 +96,9 @@ export function resolveConfig({ type: table.offchainOnly ? "offchainTable" : "table", namespace: config.namespace, name: table.name, - }) + }), ), - ]) + ]), ), }; diff --git a/packages/cli/src/mud.ts b/packages/cli/src/mud.ts index b1f85a25fb..b01f04031b 100755 --- a/packages/cli/src/mud.ts +++ b/packages/cli/src/mud.ts @@ -26,7 +26,7 @@ async function run() { console.error(chalk.red(msg)); if (msg.includes("Missing required argument")) { console.log( - chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`) + chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`), ); } console.log(""); diff --git a/packages/cli/src/runDeploy.ts b/packages/cli/src/runDeploy.ts index ba668668b8..0535fe29f0 100644 --- a/packages/cli/src/runDeploy.ts +++ b/packages/cli/src/runDeploy.ts @@ -64,8 +64,8 @@ export async function runDeploy(opts: DeployOptions): Promise { const rpc = opts.rpc ?? (await getRpcUrl(profile)); console.log( chalk.bgBlue( - chalk.whiteBright(`\n Deploying MUD contracts${profile ? " with profile " + profile : ""} to RPC ${rpc} \n`) - ) + chalk.whiteBright(`\n Deploying MUD contracts${profile ? " with profile " + profile : ""} to RPC ${rpc} \n`), + ), ); // Run build @@ -78,7 +78,7 @@ export async function runDeploy(opts: DeployOptions): Promise { throw new MUDError( `Missing PRIVATE_KEY environment variable. Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env' -in your contracts directory to use the default anvil private key.` +in your contracts directory to use the default anvil private key.`, ); } @@ -126,7 +126,7 @@ in your contracts directory to use the default anvil private key.` writeFileSync(config.worldsFile, JSON.stringify(deploys, null, 2)); console.log( - chalk.bgGreen(chalk.whiteBright(`\n Deployment result (written to ${config.worldsFile} and ${deploysDir}): \n`)) + chalk.bgGreen(chalk.whiteBright(`\n Deployment result (written to ${config.worldsFile} and ${deploysDir}): \n`)), ); } diff --git a/packages/cli/src/utils/printMUD.ts b/packages/cli/src/utils/printMUD.ts index b3114e5916..5933c97d6f 100644 --- a/packages/cli/src/utils/printMUD.ts +++ b/packages/cli/src/utils/printMUD.ts @@ -9,6 +9,6 @@ export function printMUD() { | :\\/: || :\\/: || (__) | | '--'M|| '--'U|| '--'D| '------''------''------' -`) +`), ); } diff --git a/packages/cli/src/utils/utils/getContractData.ts b/packages/cli/src/utils/utils/getContractData.ts index a289b0443d..c527d2b873 100644 --- a/packages/cli/src/utils/utils/getContractData.ts +++ b/packages/cli/src/utils/utils/getContractData.ts @@ -9,7 +9,7 @@ import { Abi, Hex, size } from "viem"; */ export function getContractData( contractName: string, - forgeOutDirectory: string + forgeOutDirectory: string, ): { bytecode: Hex; abi: Abi; deployedBytecodeSize: number } { let data: any; const contractDataPath = path.join(forgeOutDirectory, contractName + ".sol", contractName + ".json"); diff --git a/packages/cli/src/utils/utils/postDeploy.ts b/packages/cli/src/utils/utils/postDeploy.ts index e30d63eaa1..a03eb1e2fa 100644 --- a/packages/cli/src/utils/utils/postDeploy.ts +++ b/packages/cli/src/utils/utils/postDeploy.ts @@ -7,7 +7,7 @@ export async function postDeploy( postDeployScript: string, worldAddress: string, rpc: string, - profile: string | undefined + profile: string | undefined, ): Promise { // Execute postDeploy forge script const postDeployPath = path.join(await getScriptDirectory(), postDeployScript + ".s.sol"); @@ -17,7 +17,7 @@ export async function postDeploy( ["script", postDeployScript, "--sig", "run(address)", worldAddress, "--broadcast", "--rpc-url", rpc, "-vvv"], { profile: profile, - } + }, ); } else { console.log(`No script at ${postDeployPath}, skipping post deploy hook`); diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts index 8e74fd917d..cc3e3ca7de 100644 --- a/packages/cli/tsup.config.ts +++ b/packages/cli/tsup.config.ts @@ -14,7 +14,7 @@ const mudPackages: MudPackages = Object.fromEntries( JSON.parse(readFileSync(filename, "utf8")), ]) .filter(([, packageJson]) => !packageJson.private) - .map(([localPath, packageJson]) => [packageJson.name, { localPath }]) + .map(([localPath, packageJson]) => [packageJson.name, { localPath }]), ); export default defineConfig({ diff --git a/packages/common/CHANGELOG.md b/packages/common/CHANGELOG.md index 042dabaa3c..3d53ad41dd 100644 --- a/packages/common/CHANGELOG.md +++ b/packages/common/CHANGELOG.md @@ -669,7 +669,7 @@ .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/packages/common/package.json b/packages/common/package.json index 216270c946..47b0beb187 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -11,6 +11,7 @@ "type": "module", "exports": { ".": "./dist/index.js", + "./actions": "./dist/actions.js", "./chains": "./dist/chains.js", "./codegen": "./dist/codegen.js", "./errors": "./dist/errors.js", @@ -23,6 +24,9 @@ "index": [ "./src/index.ts" ], + "actions": [ + "./src/actions/index.ts" + ], "chains": [ "./src/chains/index.ts" ], @@ -59,8 +63,8 @@ "execa": "^7.0.0", "p-queue": "^7.4.1", "p-retry": "^5.1.2", - "prettier": "^2.8.4", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "viem": "2.7.12" }, "devDependencies": { diff --git a/packages/common/src/actions/index.ts b/packages/common/src/actions/index.ts new file mode 100644 index 0000000000..79e6f9f176 --- /dev/null +++ b/packages/common/src/actions/index.ts @@ -0,0 +1,2 @@ +export * from "./transactionQueue"; +export * from "./writeObserver"; diff --git a/packages/common/src/actions/transactionQueue.ts b/packages/common/src/actions/transactionQueue.ts new file mode 100644 index 0000000000..dfa8adbb6a --- /dev/null +++ b/packages/common/src/actions/transactionQueue.ts @@ -0,0 +1,14 @@ +import type { Transport, Chain, Account, WalletActions, WalletClient } from "viem"; +import { writeContract as mud_writeContract } from "../writeContract"; +import { sendTransaction as mud_sendTransaction } from "../sendTransaction"; + +export function transactionQueue(): ( + client: WalletClient, +) => Pick, "writeContract" | "sendTransaction"> { + return (client) => ({ + // Applies to: `client.writeContract`, `getContract(client, ...).write` + writeContract: (args) => mud_writeContract(client, args), + // Applies to: `client.sendTransaction` + sendTransaction: (args) => mud_sendTransaction(client, args), + }); +} diff --git a/packages/common/src/actions/writeObserver.ts b/packages/common/src/actions/writeObserver.ts new file mode 100644 index 0000000000..1a1fc10cf7 --- /dev/null +++ b/packages/common/src/actions/writeObserver.ts @@ -0,0 +1,34 @@ +import type { + WriteContractParameters, + Transport, + Chain, + Account, + WalletActions, + WalletClient, + WriteContractReturnType, +} from "viem"; +import { getAction } from "viem/utils"; +import { writeContract } from "viem/actions"; +import { type ContractWrite } from "../getContract"; + +type WriteObserverParameters = { onWrite: (write: ContractWrite) => void }; + +export function writeObserver({ + onWrite, +}: WriteObserverParameters): ( + client: WalletClient, +) => Pick, "writeContract"> { + let nextWriteId = 0; + + return (client) => ({ + // Applies to: `client.writeContract`, `getContract(client, ...).write` + writeContract: (args): Promise => { + const result = getAction(client, writeContract, "writeContract")(args); + + const id = `${client.chain.id}:${client.account.address}:${nextWriteId++}`; + onWrite({ id, request: args as WriteContractParameters, result }); + + return result; + }, + }); +} diff --git a/packages/common/src/codegen/render-solidity/common.test.ts b/packages/common/src/codegen/render-solidity/common.test.ts index e51e849b4f..c249c21cec 100644 --- a/packages/common/src/codegen/render-solidity/common.test.ts +++ b/packages/common/src/codegen/render-solidity/common.test.ts @@ -22,62 +22,58 @@ describe("getLeftPaddingBits", () => { describe("renderValueTypeToBytes32", () => { it("returns Solidity code to cast native type to bytes32", () => { expect(renderValueTypeToBytes32("someField", { typeUnwrap: "", internalTypeId: "bytes32" })).toMatchInlineSnapshot( - '"someField"' + '"someField"', ); expect( - renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bytes32" }) + renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bytes32" }), ).toMatchInlineSnapshot('"SomeStruct.unwrap(someField)"'); expect(renderValueTypeToBytes32("someField", { typeUnwrap: "", internalTypeId: "bytes16" })).toMatchInlineSnapshot( - '"bytes32(someField)"' + '"bytes32(someField)"', ); expect( - renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bytes16" }) + renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bytes16" }), ).toMatchInlineSnapshot('"bytes32(SomeStruct.unwrap(someField))"'); expect(renderValueTypeToBytes32("someField", { typeUnwrap: "", internalTypeId: "uint8" })).toMatchInlineSnapshot( - '"bytes32(uint256(someField))"' + '"bytes32(uint256(someField))"', ); expect( - renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "uint8" }) + renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "uint8" }), ).toMatchInlineSnapshot('"bytes32(uint256(SomeStruct.unwrap(someField)))"'); expect(renderValueTypeToBytes32("someField", { typeUnwrap: "", internalTypeId: "bool" })).toMatchInlineSnapshot( - '"_boolToBytes32(someField)"' + '"_boolToBytes32(someField)"', ); expect( - renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bool" }) + renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "bool" }), ).toMatchInlineSnapshot('"_boolToBytes32(SomeStruct.unwrap(someField))"'); expect(renderValueTypeToBytes32("someField", { typeUnwrap: "", internalTypeId: "address" })).toMatchInlineSnapshot( - '"bytes32(uint256(uint160(someField)))"' + '"bytes32(uint256(uint160(someField)))"', ); expect( - renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "address" }) + renderValueTypeToBytes32("someField", { typeUnwrap: "SomeStruct.unwrap", internalTypeId: "address" }), ).toMatchInlineSnapshot('"bytes32(uint256(uint160(SomeStruct.unwrap(someField))))"'); }); }); describe("renderTableId", () => { it("returns Solidity code to compute table ID", () => { - expect(renderTableId({ namespace: "somewhere", name: "Player", offchainOnly: false, tableIdName: "PlayerTableId" })) - .toMatchInlineSnapshot(` + expect(renderTableId({ namespace: "somewhere", name: "Player", offchainOnly: false })).toMatchInlineSnapshot(` + " + // Hex below is the result of \`WorldResourceIdLib.encode({ namespace: \\"somewhere\\", name: \\"Player\\", typeId: RESOURCE_TABLE });\` + ResourceId constant _tableId = ResourceId.wrap(0x7462736f6d6577686572650000000000506c6179657200000000000000000000); " - // Hex below is the result of \`WorldResourceIdLib.encode({ namespace: \\"somewhere\\", name: \\"Player\\", typeId: RESOURCE_TABLE });\` - ResourceId constant _tableId = ResourceId.wrap(0x7462736f6d6577686572650000000000506c6179657200000000000000000000); - ResourceId constant PlayerTableId = _tableId; - " - `); + `); }); it("returns Solidity code to compute offchain table ID", () => { - expect(renderTableId({ namespace: "somewhere", name: "Player", offchainOnly: true, tableIdName: "PlayerTableId" })) - .toMatchInlineSnapshot(` + expect(renderTableId({ namespace: "somewhere", name: "Player", offchainOnly: true })).toMatchInlineSnapshot(` + " + // Hex below is the result of \`WorldResourceIdLib.encode({ namespace: \\"somewhere\\", name: \\"Player\\", typeId: RESOURCE_OFFCHAIN_TABLE });\` + ResourceId constant _tableId = ResourceId.wrap(0x6f74736f6d6577686572650000000000506c6179657200000000000000000000); " - // Hex below is the result of \`WorldResourceIdLib.encode({ namespace: \\"somewhere\\", name: \\"Player\\", typeId: RESOURCE_OFFCHAIN_TABLE });\` - ResourceId constant _tableId = ResourceId.wrap(0x6f74736f6d6577686572650000000000506c6179657200000000000000000000); - ResourceId constant PlayerTableId = _tableId; - " - `); + `); }); }); diff --git a/packages/common/src/codegen/render-solidity/common.ts b/packages/common/src/codegen/render-solidity/common.ts index ea985a0146..58bbdf4b99 100644 --- a/packages/common/src/codegen/render-solidity/common.ts +++ b/packages/common/src/codegen/render-solidity/common.ts @@ -94,7 +94,7 @@ export function renderImports(imports: ImportDatum[]): string { path: solidityRelativeImportPath(importDatum.fromPath, importDatum.usedInPath), }; } - }) + }), ); } @@ -107,7 +107,7 @@ export function renderRelativeImports(imports: RelativeImportDatum[]): string { imports.map(({ symbol, fromPath, usedInPath }) => ({ symbol, path: solidityRelativeImportPath(fromPath, usedInPath), - })) + })), ); } @@ -154,7 +154,7 @@ interface RenderWithStoreCallbackData { */ export function renderWithStore( storeArgument: boolean, - callback: (data: RenderWithStoreCallbackData) => string + callback: (data: RenderWithStoreCallbackData) => string, ): string { let result = ""; result += callback({ _typedStore: undefined, _store: "StoreSwitch", _commentSuffix: "", _methodNamePrefix: "" }); @@ -190,7 +190,7 @@ export function renderWithStore( export function renderWithFieldSuffix( withSuffixlessFieldMethods: boolean, fieldName: string, - callback: (_methodNameSuffix: string) => string + callback: (_methodNameSuffix: string) => string, ): string { const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`; let result = ""; @@ -204,25 +204,23 @@ export function renderWithFieldSuffix( } /** - * Renders `_tableId` variable definition and initialization, and its alias which uses the provided `tableIdName`. - * @param param0 static resource data needed to construct the table id + * Renders `_tableId` definition of the given table. + * @param param0 static resource data needed to construct the table ID */ export function renderTableId({ namespace, name, offchainOnly, - tableIdName, -}: Pick): string { +}: Pick): string { return ` // Hex below is the result of \`WorldResourceIdLib.encode({ namespace: ${JSON.stringify( - namespace + namespace, )}, name: ${JSON.stringify(name)}, typeId: ${offchainOnly ? "RESOURCE_OFFCHAIN_TABLE" : "RESOURCE_TABLE"} });\` ResourceId constant _tableId = ResourceId.wrap(${resourceToHex({ type: offchainOnly ? "offchainTable" : "table", namespace, name, })}); - ResourceId constant ${tableIdName} = _tableId; `; } @@ -233,7 +231,7 @@ export function renderTableId({ */ export function renderValueTypeToBytes32( name: string, - { typeUnwrap, internalTypeId }: Pick + { typeUnwrap, internalTypeId }: Pick, ): string { const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name; @@ -278,7 +276,7 @@ export function getLeftPaddingBits(field: Pick( lineTerminator: string, list: T[], - renderItem: (item: T, index: number) => string + renderItem: (item: T, index: number) => string, ): string { return list .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? "" : lineTerminator)) diff --git a/packages/common/src/codegen/render-solidity/renderEnums.ts b/packages/common/src/codegen/render-solidity/renderEnums.ts index 00df0b1094..74d456d81a 100644 --- a/packages/common/src/codegen/render-solidity/renderEnums.ts +++ b/packages/common/src/codegen/render-solidity/renderEnums.ts @@ -13,7 +13,7 @@ export function renderEnums(enums: RenderEnum[]): string { enum ${name} { ${renderArguments(memberNames)} } - ` + `, ); return result; diff --git a/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts b/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts index 81b39c4baa..f6182d60e0 100644 --- a/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts +++ b/packages/common/src/codegen/render-solidity/renderTypeHelpers.ts @@ -74,7 +74,7 @@ function renderWrapperStaticArray( functionName: string, elementType: string, staticLength: number, - internalTypeId: string + internalTypeId: string, ): string { // WARNING: ensure this still works if changing major solidity versions! // (the memory layout for static arrays may change) @@ -119,7 +119,7 @@ function renderUnwrapperStaticArray( functionName: string, elementType: string, staticLength: number, - internalTypeId: string + internalTypeId: string, ): string { // byte length for memory copying (more efficient than a loop) const byteLength = staticLength * 32; diff --git a/packages/common/src/codegen/render-solidity/types.ts b/packages/common/src/codegen/render-solidity/types.ts index f395edcaae..e61da22518 100644 --- a/packages/common/src/codegen/render-solidity/types.ts +++ b/packages/common/src/codegen/render-solidity/types.ts @@ -12,8 +12,6 @@ export interface RelativeImportDatum { export type ImportDatum = AbsoluteImportDatum | RelativeImportDatum; export interface StaticResourceData { - /** Name of the table id constant to render. */ - tableIdName: string; /** Table namespace string */ namespace: string; /** Table name string */ diff --git a/packages/common/src/codegen/utils/contractToInterface.ts b/packages/common/src/codegen/utils/contractToInterface.ts index 13c347290a..2e1e83e907 100644 --- a/packages/common/src/codegen/utils/contractToInterface.ts +++ b/packages/common/src/codegen/utils/contractToInterface.ts @@ -33,7 +33,7 @@ interface SymbolImport { */ export function contractToInterface( data: string, - contractName: string + contractName: string, ): { functions: ContractInterfaceFunction[]; errors: ContractInterfaceError[]; diff --git a/packages/common/src/codegen/utils/extractUserTypes.ts b/packages/common/src/codegen/utils/extractUserTypes.ts index 21f48c0ed2..8bdc960699 100644 --- a/packages/common/src/codegen/utils/extractUserTypes.ts +++ b/packages/common/src/codegen/utils/extractUserTypes.ts @@ -24,7 +24,7 @@ export interface SolidityUserDefinedType { export function extractUserTypes( data: string, userTypeNames: string[], - fromPath: string + fromPath: string, ): Record { const ast = parse(data); diff --git a/packages/common/src/codegen/utils/formatAndWrite.ts b/packages/common/src/codegen/utils/formatAndWrite.ts index f8cca27b1f..1121d58262 100644 --- a/packages/common/src/codegen/utils/formatAndWrite.ts +++ b/packages/common/src/codegen/utils/formatAndWrite.ts @@ -27,7 +27,7 @@ export async function formatAndWriteSolidity(output: string, fullOutputPath: str export async function formatAndWriteTypescript( output: string, fullOutputPath: string, - logPrefix: string + logPrefix: string, ): Promise { const formattedOutput = await formatTypescript(output); diff --git a/packages/common/src/codegen/utils/loadUserTypesFile.ts b/packages/common/src/codegen/utils/loadUserTypesFile.ts index cacbd59472..127299d92f 100644 --- a/packages/common/src/codegen/utils/loadUserTypesFile.ts +++ b/packages/common/src/codegen/utils/loadUserTypesFile.ts @@ -19,7 +19,7 @@ export type UserType = { export function loadAndExtractUserTypes( userTypes: Record, outputBaseDirectory: string, - remappings: [string, string][] + remappings: [string, string][], ): Record { const userTypesPerFile: Record = {}; for (const [userTypeName, { filePath: unresolvedFilePath }] of Object.entries(userTypes)) { @@ -37,7 +37,7 @@ export function loadAndExtractUserTypes( for (const [userTypeName, userType] of Object.entries(userTypesInFile)) { if (userType.internalTypeId !== userTypes[userTypeName].internalType) { throw new MUDError( - `User type "${userTypeName}" has internal type "${userType.internalTypeId}" but config specifies "${userTypes[userTypeName].internalType}"` + `User type "${userTypeName}" has internal type "${userType.internalTypeId}" but config specifies "${userTypes[userTypeName].internalType}"`, ); } } @@ -50,7 +50,7 @@ export function loadAndExtractUserTypes( function loadUserTypesFile( outputBaseDirectory: string, unresolvedFilePath: string, - remappings: [string, string][] + remappings: [string, string][], ): { filePath: string; data: string; diff --git a/packages/common/src/foundry/index.ts b/packages/common/src/foundry/index.ts index b7f29ee61a..83f20bff42 100644 --- a/packages/common/src/foundry/index.ts +++ b/packages/common/src/foundry/index.ts @@ -87,7 +87,7 @@ export async function getRemappings(profile?: string): Promise<[string, string][ */ export async function forge( args: string[], - options?: { profile?: string; silent?: boolean; env?: NodeJS.ProcessEnv } + options?: { profile?: string; silent?: boolean; env?: NodeJS.ProcessEnv }, ): Promise { const execOptions: Options = { env: { FOUNDRY_PROFILE: options?.profile, ...options?.env }, diff --git a/packages/common/src/getContract.ts b/packages/common/src/getContract.ts index a845359dd8..4f67ad9cae 100644 --- a/packages/common/src/getContract.ts +++ b/packages/common/src/getContract.ts @@ -42,7 +42,7 @@ export type GetContractOptions< TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient, - TWalletClient extends WalletClient + TWalletClient extends WalletClient, > = GetContractParameters< TTransport, TChain, @@ -56,6 +56,7 @@ export type GetContractOptions< // TODO: migrate away from this approach once we can hook into viem: https://github.com/wagmi-dev/viem/discussions/1230 +/** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */ export function getContract< TTransport extends Transport, TAddress extends Address, @@ -63,7 +64,7 @@ export function getContract< TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient, - TWalletClient extends WalletClient + TWalletClient extends WalletClient, >({ abi, address, @@ -99,7 +100,7 @@ export function getContract< return ( ...parameters: [ args?: readonly unknown[], - options?: UnionOmit + options?: UnionOmit, ] ) => { const { args, options } = getFunctionParameters(parameters); @@ -125,7 +126,7 @@ export function getContract< return result; }; }, - } + }, ); } diff --git a/packages/common/src/hexToResource.ts b/packages/common/src/hexToResource.ts index 1ccf25e506..f95c93d15b 100644 --- a/packages/common/src/hexToResource.ts +++ b/packages/common/src/hexToResource.ts @@ -6,7 +6,7 @@ import { ReverseMap } from "./type-utils/common"; import { resourceToLabel } from "./resourceLabel"; const resourceTypeIdToType = Object.fromEntries( - Object.entries(resourceTypeIds).map(([key, value]) => [value, key]) + Object.entries(resourceTypeIds).map(([key, value]) => [value, key]), ) as ReverseMap; function getResourceType(resourceTypeId: string): ResourceType | undefined { @@ -24,9 +24,7 @@ export function hexToResource(hex: Hex): Resource { const name = hexToString(sliceHex(hex, 16, 32)).replace(/\0+$/, ""); if (!type) { - throw new Error( - `Unknown type (${resourceTypeId}) for resource (${resourceTypeId}:${resourceToLabel({ namespace, name })})` - ); + throw new Error(`Unknown type (${resourceTypeId}) for resource (${resourceToLabel({ namespace, name })})`); } return { resourceId: hex, type, namespace, name }; diff --git a/packages/common/src/sendTransaction.ts b/packages/common/src/sendTransaction.ts index 9e64497825..b450f5c8d2 100644 --- a/packages/common/src/sendTransaction.ts +++ b/packages/common/src/sendTransaction.ts @@ -17,13 +17,14 @@ const debug = parentDebug.extend("sendTransaction"); // TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230 +/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */ export async function sendTransaction< TChain extends Chain | undefined, TAccount extends Account | undefined, - TChainOverride extends Chain | undefined + TChainOverride extends Chain | undefined, >( client: Client, - request: SendTransactionParameters + request: SendTransactionParameters, ): Promise { const rawAccount = request.account ?? client.account; if (!rawAccount) { @@ -83,8 +84,8 @@ export async function sendTransaction< // TODO: prepare again if there are gas errors? throw error; }, - } + }, ), - { throwOnTimeout: true } + { throwOnTimeout: true }, ); } diff --git a/packages/common/src/utils/groupBy.ts b/packages/common/src/utils/groupBy.ts index 5a81d49e3f..556f7a89b7 100644 --- a/packages/common/src/utils/groupBy.ts +++ b/packages/common/src/utils/groupBy.ts @@ -1,6 +1,6 @@ export function groupBy( values: readonly value[], - getKey: (value: value) => key + getKey: (value: value) => key, ): Map { const map = new Map(); for (const value of values) { diff --git a/packages/common/src/utils/mapObject.ts b/packages/common/src/utils/mapObject.ts index 189f568657..89434b19b9 100644 --- a/packages/common/src/utils/mapObject.ts +++ b/packages/common/src/utils/mapObject.ts @@ -3,9 +3,9 @@ */ export function mapObject< Source extends Record, - Target extends { [key in keyof Source]: unknown } + Target extends { [key in keyof Source]: unknown }, >(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target { return Object.fromEntries( - Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]) + Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]), ) as Target; } diff --git a/packages/common/src/writeContract.ts b/packages/common/src/writeContract.ts index 973ecfb8bb..5ce34e5c24 100644 --- a/packages/common/src/writeContract.ts +++ b/packages/common/src/writeContract.ts @@ -20,16 +20,17 @@ const debug = parentDebug.extend("writeContract"); // TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230 +/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */ export async function writeContract< chain extends Chain | undefined, account extends Account | undefined, abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, - chainOverride extends Chain | undefined + chainOverride extends Chain | undefined, >( client: Client, - request: WriteContractParameters + request: WriteContractParameters, ): Promise { const rawAccount = request.account ?? client.account; if (!rawAccount) { @@ -88,8 +89,8 @@ export async function writeContract< // TODO: prepareWrite again if there are gas errors? throw error; }, - } + }, ), - { throwOnTimeout: true } + { throwOnTimeout: true }, ); } diff --git a/packages/common/tsup.config.ts b/packages/common/tsup.config.ts index ba8ccf3917..0a6d6d0491 100644 --- a/packages/common/tsup.config.ts +++ b/packages/common/tsup.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from "tsup"; export default defineConfig({ entry: { index: "src/index.ts", + actions: "src/actions/index.ts", chains: "src/chains/index.ts", codegen: "src/codegen/index.ts", errors: "src/errors/index.ts", diff --git a/packages/config/src/library/dynamicResolution.ts b/packages/config/src/library/dynamicResolution.ts index 4fc1dbdbcc..cf6e4083eb 100644 --- a/packages/config/src/library/dynamicResolution.ts +++ b/packages/config/src/library/dynamicResolution.ts @@ -35,7 +35,7 @@ export function isDynamicResolution(value: unknown): value is DynamicResolution */ export function resolveWithContext( unresolved: any, - context: { systemAddresses?: Record>; tableIds?: Record } + context: { systemAddresses?: Record>; tableIds?: Record }, ): ValueWithType { if (!isDynamicResolution(unresolved)) return unresolved; let resolved: ValueWithType | undefined = undefined; diff --git a/packages/create-mud/CHANGELOG.md b/packages/create-mud/CHANGELOG.md index 71ccd47861..ddb24ed63f 100644 --- a/packages/create-mud/CHANGELOG.md +++ b/packages/create-mud/CHANGELOG.md @@ -636,7 +636,7 @@ .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/packages/dev-tools/src/App.tsx b/packages/dev-tools/src/App.tsx index 08f1fd7ccb..0d74c3fcae 100644 --- a/packages/dev-tools/src/App.tsx +++ b/packages/dev-tools/src/App.tsx @@ -29,7 +29,7 @@ export function App() { className={twMerge( "pointer-events-auto w-full max-w-screen-sm h-full absolute right-0", "transition duration-500", - shown ? "translate-x-0" : "translate-x-full" + shown ? "translate-x-0" : "translate-x-full", )} >
@@ -49,7 +49,7 @@ export function App() { className={twMerge( "w-full h-full bg-slate-800 text-white/80 text-sm flex flex-col", "transition duration-500", - shown ? "opacity-100" : "opacity-0" + shown ? "opacity-100" : "opacity-0", )} > diff --git a/packages/dev-tools/src/actions/WriteSummary.tsx b/packages/dev-tools/src/actions/WriteSummary.tsx index 5ac4232835..8221805752 100644 --- a/packages/dev-tools/src/actions/WriteSummary.tsx +++ b/packages/dev-tools/src/actions/WriteSummary.tsx @@ -80,7 +80,7 @@ export function WriteSummary({ write }: Props) {
@@ -97,7 +97,7 @@ export function WriteSummary({ write }: Props) { target="_blank" className={twMerge( "flex-none font-mono text-xs text-white/40", - blockExplorer ? "hover:text-white/60 hover:underline" : null + blockExplorer ? "hover:text-white/60 hover:underline" : null, )} title={transactionReceipt.value.blockNumber.toString()} > @@ -110,7 +110,7 @@ export function WriteSummary({ write }: Props) { target="_blank" className={twMerge( "flex-none font-mono text-xs text-white/40", - blockExplorer ? "hover:text-white/60 hover:underline" : null + blockExplorer ? "hover:text-white/60 hover:underline" : null, )} title={hash.value} > diff --git a/packages/dev-tools/src/actions/getTransaction.ts b/packages/dev-tools/src/actions/getTransaction.ts index eba0191ee4..50763582b1 100644 --- a/packages/dev-tools/src/actions/getTransaction.ts +++ b/packages/dev-tools/src/actions/getTransaction.ts @@ -10,7 +10,7 @@ const cache: Record> = {}; export function getTransaction( publicClient: PublicClient, - write: ContractWrite + write: ContractWrite, ): Promise { if (!cache[write.id]) { cache[write.id] = write.result.then((hash) => publicClient.getTransaction({ hash })); diff --git a/packages/dev-tools/src/actions/getTransactionReceipt.ts b/packages/dev-tools/src/actions/getTransactionReceipt.ts index 531dcb06d3..425f840e74 100644 --- a/packages/dev-tools/src/actions/getTransactionReceipt.ts +++ b/packages/dev-tools/src/actions/getTransactionReceipt.ts @@ -7,7 +7,7 @@ const cache: Record> = {}; export function getTransactionReceipt( publicClient: PublicClient, - write: ContractWrite + write: ContractWrite, ): Promise { if (!cache[write.id]) { cache[write.id] = write.result.then((hash) => publicClient.waitForTransactionReceipt({ hash })); diff --git a/packages/dev-tools/src/actions/getTransactionResult.ts b/packages/dev-tools/src/actions/getTransactionResult.ts index e2c3f70d65..380f027b36 100644 --- a/packages/dev-tools/src/actions/getTransactionResult.ts +++ b/packages/dev-tools/src/actions/getTransactionResult.ts @@ -13,7 +13,7 @@ const cache: Record> = {}; export function getTransactionResult( publicClient: PublicClient, worldAbi: Abi, - write: ContractWrite + write: ContractWrite, ): Promise { if (!cache[write.id]) { const transaction = getTransaction(publicClient, write); diff --git a/packages/dev-tools/src/mount.tsx b/packages/dev-tools/src/mount.tsx index bfaff6c910..c54976211d 100644 --- a/packages/dev-tools/src/mount.tsx +++ b/packages/dev-tools/src/mount.tsx @@ -5,7 +5,7 @@ const containerId = "mud-dev-tools"; // TODO: rework to always return a unmount function (not a promise or possibly undefined) export async function mount( - opts: DevToolsOptions + opts: DevToolsOptions, ): Promise<(() => void) | undefined> { if (typeof window === "undefined") { console.warn("MUD dev-tools should only be used in browser bundles"); @@ -39,7 +39,7 @@ export async function mount( - + , ); document.body.appendChild(rootElement); diff --git a/packages/dev-tools/src/recs/ComponentDataTable.tsx b/packages/dev-tools/src/recs/ComponentDataTable.tsx index 5323d9af3f..6dce6eb87f 100644 --- a/packages/dev-tools/src/recs/ComponentDataTable.tsx +++ b/packages/dev-tools/src/recs/ComponentDataTable.tsx @@ -38,8 +38,8 @@ export function ComponentDataTable({ component }: Props) { {component.schema[name] === Type.T ? serialize(fieldValue) : Array.isArray(fieldValue) - ? fieldValue.map(String).join(", ") - : String(fieldValue)} + ? fieldValue.map(String).join(", ") + : String(fieldValue)} ); })} diff --git a/packages/dev-tools/src/recs/ComponentsPage.tsx b/packages/dev-tools/src/recs/ComponentsPage.tsx index ef95a1bb5b..9abc66bb9e 100644 --- a/packages/dev-tools/src/recs/ComponentsPage.tsx +++ b/packages/dev-tools/src/recs/ComponentsPage.tsx @@ -63,7 +63,7 @@ export function ComponentsPage() { }> } /> - - ) + , + ), ); diff --git a/packages/dev-tools/src/summary/SummaryPage.tsx b/packages/dev-tools/src/summary/SummaryPage.tsx index 230e18fa40..516aac5b16 100644 --- a/packages/dev-tools/src/summary/SummaryPage.tsx +++ b/packages/dev-tools/src/summary/SummaryPage.tsx @@ -8,7 +8,7 @@ import packageJson from "../../package.json"; import { useDevToolsContext } from "../DevToolsContext"; const isLinked = Object.entries(packageJson.dependencies).some( - ([name, version]) => name.startsWith("@latticexyz/") && version.startsWith("link:") + ([name, version]) => name.startsWith("@latticexyz/") && version.startsWith("link:"), ); export function SummaryPage() { diff --git a/packages/dev-tools/src/zustand/TablesPage.tsx b/packages/dev-tools/src/zustand/TablesPage.tsx index cd27b25dbc..4c28750e89 100644 --- a/packages/dev-tools/src/zustand/TablesPage.tsx +++ b/packages/dev-tools/src/zustand/TablesPage.tsx @@ -57,7 +57,7 @@ export function TablesPage() { (table: table): TableRecord
}>( - useStore.getState().getRecords(table) + useStore.getState().getRecords(table), ); useEffect(() => { return useStore.subscribe((state) => { diff --git a/packages/faucet/bin/parseEnv.ts b/packages/faucet/bin/parseEnv.ts index dd739618c9..7d17e6da78 100644 --- a/packages/faucet/bin/parseEnv.ts +++ b/packages/faucet/bin/parseEnv.ts @@ -13,7 +13,7 @@ const commonSchema = z.object({ }); export function parseEnv( - schema?: TSchema + schema?: TSchema, ): z.infer : typeof commonSchema> { const envSchema = schema !== undefined ? z.intersection(commonSchema, schema) : commonSchema; try { diff --git a/packages/faucet/src/createAppRouter.ts b/packages/faucet/src/createAppRouter.ts index c30c417911..ab8285c286 100644 --- a/packages/faucet/src/createAppRouter.ts +++ b/packages/faucet/src/createAppRouter.ts @@ -19,7 +19,7 @@ export function createAppRouter() { .input( z.object({ address: z.string().refine(isHex), - }) + }), ) .mutation(async (opts): Promise => { const { client, faucetAccount, dripAmount } = opts.ctx; diff --git a/packages/gas-report/ts/gas-report.ts b/packages/gas-report/ts/gas-report.ts index aac2397f12..2391c2f101 100755 --- a/packages/gas-report/ts/gas-report.ts +++ b/packages/gas-report/ts/gas-report.ts @@ -25,7 +25,7 @@ yargs(hideBin(process.argv)) console.error(chalk.red(msg)); if (msg.includes("Missing required argument")) { console.log( - chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`) + chalk.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`), ); } diff --git a/packages/phaserx/src/createCamera.ts b/packages/phaserx/src/createCamera.ts index d7df7d9c91..4c131a15f5 100644 --- a/packages/phaserx/src/createCamera.ts +++ b/packages/phaserx/src/createCamera.ts @@ -20,7 +20,7 @@ export function createCamera(phaserCamera: Phaser.Cameras.Scene2D.Camera, option onPinch: (state) => pinchStream$.next(state), onWheel: (state) => wheelStream$.next(state), }, - {} + {}, ); // function getNearestLevel(currentZoom: number): number { @@ -51,7 +51,7 @@ export function createCamera(phaserCamera: Phaser.Cameras.Scene2D.Camera, option return zoom + scaledDelta; }), // Compute pinch speed map((zoom) => Math.min(Math.max(zoom, options.minZoom), options.maxZoom)), // Limit zoom values - scan((acc, curr) => [acc[1], curr], [1, 1]) // keep track of the last value to offset the map position (not implemented yet) + scan((acc, curr) => [acc[1], curr], [1, 1]), // keep track of the last value to offset the map position (not implemented yet) ) .subscribe(([, zoom]) => { // Set the gesture zoom state to the current zoom value to avoid zooming beyond the max values @@ -67,7 +67,7 @@ export function createCamera(phaserCamera: Phaser.Cameras.Scene2D.Camera, option // @ts-ignore map((state) => state.delta.map((x) => x * options.wheelSpeed)), // Compute wheel speed map((movement) => movement.map((m: number) => m / phaserCamera.zoom)), // Adjust for current zoom value - map((movement) => [phaserCamera.scrollX + movement[0], phaserCamera.scrollY + movement[1]]) // Compute new pinch + map((movement) => [phaserCamera.scrollX + movement[0], phaserCamera.scrollY + movement[1]]), // Compute new pinch ) .subscribe(([x, y]) => { phaserCamera.setScroll(x, y); diff --git a/packages/phaserx/src/createChunks.ts b/packages/phaserx/src/createChunks.ts index a300c50f9d..f940574344 100644 --- a/packages/phaserx/src/createChunks.ts +++ b/packages/phaserx/src/createChunks.ts @@ -19,9 +19,9 @@ export function createChunks(worldView$: Observable, chunkSize: number, pa width: width + 2 * padding, height: height + 2 * padding, }, - chunkSize - ) - ) + chunkSize, + ), + ), ); visibleChunkStream.subscribe((newVisibleChunks) => { diff --git a/packages/phaserx/src/createCulling.ts b/packages/phaserx/src/createCulling.ts index 7df01f83e9..e17419422f 100644 --- a/packages/phaserx/src/createCulling.ts +++ b/packages/phaserx/src/createCulling.ts @@ -50,7 +50,7 @@ export function createCulling(objectPool: ObjectPool, camera: Camera, chunks: Ch map((chunk: ChunkCoord) => from(chunkRegistry.get(chunk))), // Map to streams of entityIds mergeMap((entities) => entities), // Flatten the stream of entities map((entityId) => objectPool.get(entityId, "Existing")), // Map entityId to embodiedEntity - filterNullish() + filterNullish(), ); // Spawn entities when their chunk appears in the viewport @@ -77,7 +77,7 @@ export function createCulling(objectPool: ObjectPool, camera: Camera, chunks: Ch entity.despawn(); } }, - { fireImmediately: true } + { fireImmediately: true }, ); disposer.set(entity.id, dispose); } diff --git a/packages/phaserx/src/createDebugger.ts b/packages/phaserx/src/createDebugger.ts index e33bba3cf0..7cbddf3ea8 100644 --- a/packages/phaserx/src/createDebugger.ts +++ b/packages/phaserx/src/createDebugger.ts @@ -15,7 +15,7 @@ export function createDebugger( chunks: Chunks, scene: Phaser.Scene, objectPool: ObjectPool, - map: AnimatedTilemap + map: AnimatedTilemap, ) { const options = { logViewport: false, @@ -47,8 +47,8 @@ export function createDebugger( console.log( `Entities: ${objectPool.objects.size} / Pool size: ${Object.values(objectPool.groups).reduce( (acc, curr) => acc + curr.getChildren().length, - 0 - )} / Pool active: ${Object.values(objectPool.groups).reduce((acc, curr) => acc + curr.countActive(), 0)}` + 0, + )} / Pool active: ${Object.values(objectPool.groups).reduce((acc, curr) => acc + curr.countActive(), 0)}`, ); } @@ -66,7 +66,7 @@ export function createDebugger( chunks.chunkSize, chunks.chunkSize, getRandomColor(), - 0.5 + 0.5, ); visualChunk.setInteractive(); visualChunk.on("pointerup", () => { diff --git a/packages/phaserx/src/createEmbodiedEntity.ts b/packages/phaserx/src/createEmbodiedEntity.ts index faf53312cb..765243607b 100644 --- a/packages/phaserx/src/createEmbodiedEntity.ts +++ b/packages/phaserx/src/createEmbodiedEntity.ts @@ -14,7 +14,7 @@ export function createEmbodiedEntity( id: string, group: Phaser.GameObjects.Group, type: Type, - currentCameraFilter = 0 + currentCameraFilter = 0, ): EmbodiedEntity { const position: PixelCoord = observable({ x: 0, y: 0 }); const onOnce = new Map>(); @@ -136,7 +136,7 @@ export function createEmbodiedEntity( function executeGameObjectFunctions( gameObject: GameObject, - functions: Iterable> + functions: Iterable>, ) { if (!gameObject) return; for (const func of functions) { @@ -145,7 +145,7 @@ function executeGameObjectFunctions( } function modifiesPosition( - func: GameObjectFunction + func: GameObjectFunction, ): Partial | undefined { let newPosition: Partial | undefined = undefined; const gameObjectProxy = new Proxy( @@ -162,7 +162,7 @@ function modifiesPosition( if (prop === "y") newPosition = newPosition ? { ...newPosition, y: value } : { y: value }; return true; }, - } + }, ); func(gameObjectProxy as GameObject); return newPosition; diff --git a/packages/phaserx/src/createInput.ts b/packages/phaserx/src/createInput.ts index f1569d9147..7f38908b6a 100644 --- a/packages/phaserx/src/createInput.ts +++ b/packages/phaserx/src/createInput.ts @@ -42,25 +42,25 @@ export function createInput(inputPlugin: Phaser.Input.InputPlugin) { map(() => { return { pointer: inputPlugin.manager?.activePointer }; }), - filterNullish() + filterNullish(), ); const pointerdown$: Observable<{ pointer: Phaser.Input.Pointer; event: MouseEvent }> = fromEvent( document, - "mousedown" + "mousedown", ).pipe( filter(() => enabled.current), map((event) => ({ pointer: inputPlugin.manager?.activePointer, event: event as MouseEvent })), - filterNullish() + filterNullish(), ); const pointerup$: Observable<{ pointer: Phaser.Input.Pointer; event: MouseEvent }> = fromEvent( document, - "mouseup" + "mouseup", ).pipe( filter(() => enabled.current), map((event) => ({ pointer: inputPlugin.manager?.activePointer, event: event as MouseEvent })), - filterNullish() + filterNullish(), ); // Click stream @@ -73,7 +73,7 @@ export function createInput(inputPlugin: Phaser.Input.InputPlugin) { bufferCount(2, 1), // Store the last two timestamps filter(([prev, now]) => prev[0] && !now[0] && now[1] - prev[1] < 250), // Only care if button was pressed before and is not anymore and it happened within 500ms map(() => inputPlugin.manager?.activePointer), // Return the current pointer - filterNullish() + filterNullish(), ); // Double click stream @@ -84,14 +84,14 @@ export function createInput(inputPlugin: Phaser.Input.InputPlugin) { filter(([prev, now]) => now - prev < 500), // Filter clicks with more than 500ms distance throttleTime(500), // A third click within 500ms is not counted as another double click map(() => inputPlugin.manager?.activePointer), // Return the current pointer - filterNullish() + filterNullish(), ); // Right click stream const rightClick$ = merge(pointerdown$, pointerup$).pipe( filter(({ pointer }) => enabled.current && pointer.rightButtonDown()), map(() => inputPlugin.manager?.activePointer), // Return the current pointer - filterNullish() + filterNullish(), ); // Drag stream @@ -106,14 +106,14 @@ export function createInput(inputPlugin: Phaser.Input.InputPlugin) { ? { ...acc, width: curr.worldX - acc.x, height: curr.worldY - acc.y } // Update the width/height : { x: curr.worldX, y: curr.worldY, width: 0, height: 0 } // Else start the drag : undefined, - undefined + undefined, ), filterNullish(), - filter((area) => Math.abs(area.width) > 10 && Math.abs(area.height) > 10) // Prevent clicking to be mistaken as a drag - ) + filter((area) => Math.abs(area.width) > 10 && Math.abs(area.height) > 10), // Prevent clicking to be mistaken as a drag + ), ).pipe( filter(() => enabled.current), - distinctUntilChanged() // Prevent same value to be emitted in a row + distinctUntilChanged(), // Prevent same value to be emitted in a row ); const pressedKeys = observable(new Set()); @@ -170,7 +170,7 @@ export function createInput(inputPlugin: Phaser.Input.InputPlugin) { (passes) => { if (passes) callback(); }, - { fireImmediately: true } + { fireImmediately: true }, ); disposers.add(disposer); } diff --git a/packages/phaserx/src/createObjectPool.ts b/packages/phaserx/src/createObjectPool.ts index 654be498e8..e3535487cc 100644 --- a/packages/phaserx/src/createObjectPool.ts +++ b/packages/phaserx/src/createObjectPool.ts @@ -22,7 +22,7 @@ export function createObjectPool(scene: Phaser.Scene) { function get( entity: number | string, - type: Type + type: Type, ): ObjectPoolReturnType { if (typeof entity === "number") entity = String(entity); let embodiedEntity = objects.get(entity); diff --git a/packages/phaserx/src/guards.ts b/packages/phaserx/src/guards.ts index 96681af748..e6e83b8510 100644 --- a/packages/phaserx/src/guards.ts +++ b/packages/phaserx/src/guards.ts @@ -19,7 +19,7 @@ export function defineAssetsConfig(assets: A) { } export function defineMapConfig, L extends LayerConfig>( - config: MapConfig + config: MapConfig, ) { return config; } @@ -29,7 +29,7 @@ export function defineSceneConfig< S extends { [key: string]: Sprite }, T extends TilesetConfig, M extends MapsConfig, - Ans extends Animation[] + Ans extends Animation[], >(config: SceneConfig) { return config; } @@ -44,14 +44,14 @@ export function defineCameraConfig(config: CameraConfig) { export function isSprite( gameObject: Phaser.GameObjects.GameObject, - type: keyof GameObjectTypes + type: keyof GameObjectTypes, ): gameObject is GameObject<"Sprite"> { return type === "Sprite"; } export function isRectangle( gameObject: Phaser.GameObjects.GameObject, - type: keyof GameObjectTypes + type: keyof GameObjectTypes, ): gameObject is GameObject<"Rectangle"> { return type === "Rectangle"; } diff --git a/packages/phaserx/src/tilemap/createAnimatedTilemap.ts b/packages/phaserx/src/tilemap/createAnimatedTilemap.ts index cf01db3e70..449f30ecff 100644 --- a/packages/phaserx/src/tilemap/createAnimatedTilemap.ts +++ b/packages/phaserx/src/tilemap/createAnimatedTilemap.ts @@ -7,7 +7,7 @@ import { createVirtualTilemap } from "./createVirtualTilemap"; import { TileAnimation } from "./types"; export function createAnimatedTilemap( - config: Omit, "tiles"> & { animationInterval: number } + config: Omit, "tiles"> & { animationInterval: number }, ): AnimatedTilemap { const { layerConfig: { layers, defaultLayer }, diff --git a/packages/phaserx/src/tilemap/createChunkedTilemap.ts b/packages/phaserx/src/tilemap/createChunkedTilemap.ts index 2f4b92187b..360a27248e 100644 --- a/packages/phaserx/src/tilemap/createChunkedTilemap.ts +++ b/packages/phaserx/src/tilemap/createChunkedTilemap.ts @@ -20,7 +20,7 @@ export type ChunkedTilemapConfig( - params: ChunkedTilemapConfig + params: ChunkedTilemapConfig, ): ChunkedTilemap { const { scene, tilesets, layerConfig, chunks, backgroundTile, tiles, tileWidth, tileHeight } = params; const relevantTilesets = Object.keys(layerConfig.layers) @@ -68,7 +68,7 @@ export function createChunkedTilemap( - config: Omit, "tiles"> + config: Omit, "tiles">, ): VirtualTilemap { const { chunks, diff --git a/packages/phaserx/src/types.ts b/packages/phaserx/src/types.ts index c059ebbf49..031de7a11e 100644 --- a/packages/phaserx/src/types.ts +++ b/packages/phaserx/src/types.ts @@ -26,7 +26,7 @@ export type GameObjectTypes = typeof GameObjectClasses; export type GameObject = InstanceType; export type GameObjectFunction = ( - gameObject: GameObject + gameObject: GameObject, ) => Promise | void; export type GameScene = ReturnType; @@ -135,7 +135,7 @@ export type SceneConfig< S extends { [key: string]: Sprite }, T extends TilesetConfig, M extends MapsConfig, - Ans extends Animation[] + Ans extends Animation[], > = { preload?: (scene: Phaser.Scene) => void; create?: (scene: Phaser.Scene) => void; diff --git a/packages/phaserx/src/utils/chunks.ts b/packages/phaserx/src/utils/chunks.ts index 587d4f50d8..b6e47c2a44 100644 --- a/packages/phaserx/src/utils/chunks.ts +++ b/packages/phaserx/src/utils/chunks.ts @@ -21,7 +21,7 @@ export function getChunksInArea(area: Area, chunkSize: number) { x: topLeftChunk.x + x, y: topLeftChunk.y + y, }, - true + true, ); } } diff --git a/packages/phaserx/src/utils/coords.ts b/packages/phaserx/src/utils/coords.ts index fcd197f74c..4d20821360 100644 --- a/packages/phaserx/src/utils/coords.ts +++ b/packages/phaserx/src/utils/coords.ts @@ -64,7 +64,7 @@ export function tileCoordToChunkCoord( tileCoord: WorldCoord, tileWidth: number, tileHeight: number, - chunkSize: number + chunkSize: number, ): ChunkCoord { const pixelCoord = tileCoordToPixelCoord(tileCoord, tileWidth, tileHeight); return pixelToChunkCoord(pixelCoord, chunkSize); @@ -74,7 +74,7 @@ export function chunkCoordToTileCoord( chunkCoord: ChunkCoord, tileWidth: number, tileHeight: number, - chunkSize: number + chunkSize: number, ): WorldCoord { const pixelCoord = chunkToPixelCoord(chunkCoord, chunkSize); return pixelCoordToTileCoord(pixelCoord, tileWidth, tileHeight); diff --git a/packages/phaserx/src/utils/generateFrames.ts b/packages/phaserx/src/utils/generateFrames.ts index ef9ad74aec..99fa4a8ab6 100644 --- a/packages/phaserx/src/utils/generateFrames.ts +++ b/packages/phaserx/src/utils/generateFrames.ts @@ -2,7 +2,7 @@ import { Animation, Assets } from "../types"; export function generateFrames( anims: Phaser.Animations.AnimationManager, - animation: Animation + animation: Animation, ): Phaser.Types.Animations.AnimationFrame[] { if (animation.prefix && animation.suffix) { return anims.generateFrameNames(animation.assetKey, { diff --git a/packages/protocol-parser/src/decodeDynamicField.test.ts b/packages/protocol-parser/src/decodeDynamicField.test.ts index 4ad3b8236f..1120adac5f 100644 --- a/packages/protocol-parser/src/decodeDynamicField.test.ts +++ b/packages/protocol-parser/src/decodeDynamicField.test.ts @@ -22,28 +22,28 @@ describe("decodeDynamicField", () => { it("can decode uint256[]", () => { expect( - decodeDynamicField("uint256[]", "0x0000000000000000000000000000000000000000000000000000000000000000") + decodeDynamicField("uint256[]", "0x0000000000000000000000000000000000000000000000000000000000000000"), ).toStrictEqual([0n]); expect( - decodeDynamicField("uint256[]", "0x0000000000000000000000000000000000000000000000000000000000000001") + decodeDynamicField("uint256[]", "0x0000000000000000000000000000000000000000000000000000000000000001"), ).toStrictEqual([1n]); expect( - decodeDynamicField("uint256[]", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") + decodeDynamicField("uint256[]", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), ).toStrictEqual([115792089237316195423570985008687907853269984665640564039457584007913129639935n]); expect( - decodeDynamicField("uint256[]", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe") + decodeDynamicField("uint256[]", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"), ).toStrictEqual([115792089237316195423570985008687907853269984665640564039457584007913129639934n]); expect( decodeDynamicField( "uint256[]", - "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001" - ) + "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001", + ), ).toStrictEqual([1n, 1n]); expect( decodeDynamicField( "uint256[]", - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - ) + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ), ).toStrictEqual([ 115792089237316195423570985008687907853269984665640564039457584007913129639935n, 115792089237316195423570985008687907853269984665640564039457584007913129639935n, @@ -68,41 +68,41 @@ describe("decodeDynamicField", () => { it("can decode int256[]", () => { expect( - decodeDynamicField("int256[]", "0x0000000000000000000000000000000000000000000000000000000000000000") + decodeDynamicField("int256[]", "0x0000000000000000000000000000000000000000000000000000000000000000"), ).toStrictEqual([0n]); expect( - decodeDynamicField("int256[]", "0x0000000000000000000000000000000000000000000000000000000000000001") + decodeDynamicField("int256[]", "0x0000000000000000000000000000000000000000000000000000000000000001"), ).toStrictEqual([1n]); expect( - decodeDynamicField("int256[]", "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") + decodeDynamicField("int256[]", "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), ).toStrictEqual([57896044618658097711785492504343953926634992332820282019728792003956564819967n]); expect( - decodeDynamicField("int256[]", "0x8000000000000000000000000000000000000000000000000000000000000000") + decodeDynamicField("int256[]", "0x8000000000000000000000000000000000000000000000000000000000000000"), ).toStrictEqual([-57896044618658097711785492504343953926634992332820282019728792003956564819968n]); expect( - decodeDynamicField("int256[]", "0x8000000000000000000000000000000000000000000000000000000000000001") + decodeDynamicField("int256[]", "0x8000000000000000000000000000000000000000000000000000000000000001"), ).toStrictEqual([-57896044618658097711785492504343953926634992332820282019728792003956564819967n]); expect( - decodeDynamicField("int256[]", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") + decodeDynamicField("int256[]", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), ).toStrictEqual([-1n]); expect( decodeDynamicField( "int256[]", - "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - ) + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ), ).toStrictEqual([57896044618658097711785492504343953926634992332820282019728792003956564819967n, -1n]); expect( decodeDynamicField( "int256[]", - "0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - ) + "0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + ), ).toStrictEqual([-57896044618658097711785492504343953926634992332820282019728792003956564819968n, 0n]); expect( decodeDynamicField( "int256[]", - "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000000000000000000000000000000000000000000000000000000000000001" - ) + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000000000000000000000000000000000000000000000000000000000000001", + ), ).toStrictEqual([-1n, -57896044618658097711785492504343953926634992332820282019728792003956564819967n]); }); @@ -129,13 +129,13 @@ describe("decodeDynamicField", () => { ]); expect(decodeDynamicField("bytes4[]", "0xff00ff00ff00ff00")).toStrictEqual(["0xff00ff00", "0xff00ff00"]); expect( - decodeDynamicField("bytes32[]", "0x0000000000000000000000000000000000000000000000000000000000000001") + decodeDynamicField("bytes32[]", "0x0000000000000000000000000000000000000000000000000000000000000001"), ).toStrictEqual(["0x0000000000000000000000000000000000000000000000000000000000000001"]); expect( decodeDynamicField( "bytes32[]", - "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" - ) + "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + ), ).toStrictEqual([ "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", @@ -151,10 +151,10 @@ describe("decodeDynamicField", () => { ]); expect(() => decodeDynamicField("address[]", "0x00")).toThrow( - 'Hex value "0x00" has length of 2, but expected a multiple of 40 for address[] type.' + 'Hex value "0x00" has length of 2, but expected a multiple of 40 for address[] type.', ); expect(() => decodeDynamicField("address[]", "0xffffffffffffffffffffffffffffffffffffffffff")).toThrow( - 'Hex value "0xffffffffffffffffffffffffffffffffffffffffff" has length of 42, but expected a multiple of 40 for address[] type.' + 'Hex value "0xffffffffffffffffffffffffffffffffffffffffff" has length of 42, but expected a multiple of 40 for address[] type.', ); }); @@ -164,7 +164,7 @@ describe("decodeDynamicField", () => { expect(decodeDynamicField("bytes", "0x0001")).toBe("0x0001"); expect(decodeDynamicField("bytes", "0xff00ff00ff00ff00")).toBe("0xff00ff00ff00ff00"); expect(decodeDynamicField("bytes", "0x0000000000000000000000000000000000000000000000000000000000000001")).toBe( - "0x0000000000000000000000000000000000000000000000000000000000000001" + "0x0000000000000000000000000000000000000000000000000000000000000001", ); }); diff --git a/packages/protocol-parser/src/decodeDynamicField.ts b/packages/protocol-parser/src/decodeDynamicField.ts index 3fcb63876c..d9eaf52b64 100644 --- a/packages/protocol-parser/src/decodeDynamicField.ts +++ b/packages/protocol-parser/src/decodeDynamicField.ts @@ -14,7 +14,7 @@ import { InvalidHexLengthError, InvalidHexLengthForArrayFieldError } from "./err export function decodeDynamicField< TAbiType extends DynamicAbiType, - TPrimitiveType extends DynamicAbiTypeToPrimitiveType + TPrimitiveType extends DynamicAbiTypeToPrimitiveType, >(abiType: TAbiType, data: Hex): TPrimitiveType { if (abiType === "bytes") { return data as TPrimitiveType; diff --git a/packages/protocol-parser/src/decodeField.ts b/packages/protocol-parser/src/decodeField.ts index b3a63059d5..e6b6d881c7 100644 --- a/packages/protocol-parser/src/decodeField.ts +++ b/packages/protocol-parser/src/decodeField.ts @@ -5,7 +5,7 @@ import { decodeStaticField } from "./decodeStaticField"; export function decodeField< TAbiType extends SchemaAbiType, - TPrimitiveType extends SchemaAbiTypeToPrimitiveType + TPrimitiveType extends SchemaAbiTypeToPrimitiveType, >(abiType: TAbiType, data: Hex): TPrimitiveType { return ( isDynamicAbiType(abiType) ? decodeDynamicField(abiType, data) : decodeStaticField(abiType, data) diff --git a/packages/protocol-parser/src/decodeKey.ts b/packages/protocol-parser/src/decodeKey.ts index 2b11552ad8..bec0695e6a 100644 --- a/packages/protocol-parser/src/decodeKey.ts +++ b/packages/protocol-parser/src/decodeKey.ts @@ -4,12 +4,12 @@ import { decodeKeyTuple } from "./decodeKeyTuple"; export function decodeKey( keySchema: TSchema, - data: readonly Hex[] + data: readonly Hex[], ): SchemaToPrimitives { // TODO: refactor and move all decodeKeyTuple logic into this method so we can delete decodeKeyTuple const keyValues = decodeKeyTuple({ staticFields: Object.values(keySchema), dynamicFields: [] }, data); return Object.fromEntries( - Object.keys(keySchema).map((name, i) => [name, keyValues[i]]) + Object.keys(keySchema).map((name, i) => [name, keyValues[i]]), ) as SchemaToPrimitives; } diff --git a/packages/protocol-parser/src/decodeKeyTuple.test.ts b/packages/protocol-parser/src/decodeKeyTuple.test.ts index 362118332d..cd1c2c14c1 100644 --- a/packages/protocol-parser/src/decodeKeyTuple.test.ts +++ b/packages/protocol-parser/src/decodeKeyTuple.test.ts @@ -6,12 +6,12 @@ describe("decodeKeyTuple", () => { expect( decodeKeyTuple({ staticFields: ["bool"], dynamicFields: [] }, [ "0x0000000000000000000000000000000000000000000000000000000000000000", - ]) + ]), ).toStrictEqual([false]); expect( decodeKeyTuple({ staticFields: ["bool"], dynamicFields: [] }, [ "0x0000000000000000000000000000000000000000000000000000000000000001", - ]) + ]), ).toStrictEqual([true]); }); @@ -24,7 +24,7 @@ describe("decodeKeyTuple", () => { "0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000003", - ]) + ]), ).toStrictEqual([ 42n, -42, diff --git a/packages/protocol-parser/src/decodeKeyTuple.ts b/packages/protocol-parser/src/decodeKeyTuple.ts index 623df1fac1..426806dd68 100644 --- a/packages/protocol-parser/src/decodeKeyTuple.ts +++ b/packages/protocol-parser/src/decodeKeyTuple.ts @@ -8,10 +8,10 @@ import { Schema } from "./common"; export function decodeKeyTuple(keySchema: Schema, keyTuple: readonly Hex[]): StaticPrimitiveType[] { if (keySchema.staticFields.length !== keyTuple.length) { throw new Error( - `key tuple length ${keyTuple.length} does not match key schema length ${keySchema.staticFields.length}` + `key tuple length ${keyTuple.length} does not match key schema length ${keySchema.staticFields.length}`, ); } return keyTuple.map( - (key, index) => decodeAbiParameters([{ type: keySchema.staticFields[index] }], key)[0] as StaticPrimitiveType + (key, index) => decodeAbiParameters([{ type: keySchema.staticFields[index] }], key)[0] as StaticPrimitiveType, ); } diff --git a/packages/protocol-parser/src/decodeRecord.test.ts b/packages/protocol-parser/src/decodeRecord.test.ts index 87e357f599..f09283c4ab 100644 --- a/packages/protocol-parser/src/decodeRecord.test.ts +++ b/packages/protocol-parser/src/decodeRecord.test.ts @@ -6,7 +6,7 @@ describe("decodeRecord", () => { const valueSchema = { staticFields: ["uint32", "uint128"], dynamicFields: ["uint32[]", "string"] } as const; const values = decodeRecord( valueSchema, - "0x0000000100000000000000000000000000000002000000000000000000000000000000000000000b0000000008000000000000130000000300000004736f6d6520737472696e67" + "0x0000000100000000000000000000000000000002000000000000000000000000000000000000000b0000000008000000000000130000000300000004736f6d6520737472696e67", ); expect(values).toStrictEqual([1, 2n, [3, 4], "some string"]); }); diff --git a/packages/protocol-parser/src/decodeRecord.ts b/packages/protocol-parser/src/decodeRecord.ts index 411d93327c..1ae389fbcf 100644 --- a/packages/protocol-parser/src/decodeRecord.ts +++ b/packages/protocol-parser/src/decodeRecord.ts @@ -34,7 +34,7 @@ export function decodeRecord(valueSchema: Schema, data: Hex): readonly (StaticPr expectedLength: schemaStaticDataLength, actualLength: actualStaticDataLength, bytesOffset, - } + }, ); } @@ -63,7 +63,7 @@ export function decodeRecord(valueSchema: Schema, data: Hex): readonly (StaticPr expectedLength: dataLayout.totalByteLength, actualLength: actualDynamicDataLength, bytesOffset, - } + }, ); } } diff --git a/packages/protocol-parser/src/decodeStaticField.test.ts b/packages/protocol-parser/src/decodeStaticField.test.ts index 8ad29713aa..307b324a97 100644 --- a/packages/protocol-parser/src/decodeStaticField.test.ts +++ b/packages/protocol-parser/src/decodeStaticField.test.ts @@ -7,22 +7,22 @@ describe("decodeStaticField", () => { expect(decodeStaticField("bool", "0x01")).toBe(true); expect(() => decodeStaticField("bool", "0x0")).toThrow( - 'Hex value "0x0" has length of 1, but expected length of 2 for bool type.' + 'Hex value "0x0" has length of 1, but expected length of 2 for bool type.', ); expect(() => decodeStaticField("bool", "0x1")).toThrow( - 'Hex value "0x1" has length of 1, but expected length of 2 for bool type.' + 'Hex value "0x1" has length of 1, but expected length of 2 for bool type.', ); expect(() => decodeStaticField("bool", "0x000")).toThrow( - 'Hex value "0x000" is an odd length (3). It must be an even length.' + 'Hex value "0x000" is an odd length (3). It must be an even length.', ); expect(() => decodeStaticField("bool", "0x001")).toThrow( - 'Hex value "0x001" is an odd length (3). It must be an even length.' + 'Hex value "0x001" is an odd length (3). It must be an even length.', ); expect(() => decodeStaticField("bool", "0x0000")).toThrow( - 'Hex value "0x0000" has length of 4, but expected length of 2 for bool type.' + 'Hex value "0x0000" has length of 4, but expected length of 2 for bool type.', ); expect(() => decodeStaticField("bool", "0x0001")).toThrow( - 'Hex value "0x0001" has length of 4, but expected length of 2 for bool type.' + 'Hex value "0x0001" has length of 4, but expected length of 2 for bool type.', ); }); @@ -36,10 +36,10 @@ describe("decodeStaticField", () => { expect(decodeStaticField("uint256", "0x0000000000000000000000000000000000000000000000000000000000000000")).toBe(0n); expect(decodeStaticField("uint256", "0x0000000000000000000000000000000000000000000000000000000000000001")).toBe(1n); expect(decodeStaticField("uint256", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")).toBe( - 115792089237316195423570985008687907853269984665640564039457584007913129639935n + 115792089237316195423570985008687907853269984665640564039457584007913129639935n, ); expect(decodeStaticField("uint256", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")).toBe( - 115792089237316195423570985008687907853269984665640564039457584007913129639934n + 115792089237316195423570985008687907853269984665640564039457584007913129639934n, ); }); @@ -56,13 +56,13 @@ describe("decodeStaticField", () => { expect(decodeStaticField("int256", "0x0000000000000000000000000000000000000000000000000000000000000000")).toBe(0n); expect(decodeStaticField("int256", "0x0000000000000000000000000000000000000000000000000000000000000001")).toBe(1n); expect(decodeStaticField("int256", "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")).toBe( - 57896044618658097711785492504343953926634992332820282019728792003956564819967n + 57896044618658097711785492504343953926634992332820282019728792003956564819967n, ); expect(decodeStaticField("int256", "0x8000000000000000000000000000000000000000000000000000000000000000")).toBe( - -57896044618658097711785492504343953926634992332820282019728792003956564819968n + -57896044618658097711785492504343953926634992332820282019728792003956564819968n, ); expect(decodeStaticField("int256", "0x8000000000000000000000000000000000000000000000000000000000000001")).toBe( - -57896044618658097711785492504343953926634992332820282019728792003956564819967n + -57896044618658097711785492504343953926634992332820282019728792003956564819967n, ); expect(decodeStaticField("int256", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")).toBe(-1n); }); @@ -72,23 +72,23 @@ describe("decodeStaticField", () => { expect(decodeStaticField("bytes2", "0x0001")).toBe("0x0001"); expect(decodeStaticField("bytes8", "0xff00ff00ff00ff00")).toBe("0xff00ff00ff00ff00"); expect(decodeStaticField("bytes32", "0x0000000000000000000000000000000000000000000000000000000000000001")).toBe( - "0x0000000000000000000000000000000000000000000000000000000000000001" + "0x0000000000000000000000000000000000000000000000000000000000000001", ); }); it("can decode address", () => { expect(decodeStaticField("address", "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266")).toBe( - "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" + "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", ); expect(decodeStaticField("address", "0xffffffffffffffffffffffffffffffffffffffff")).toBe( - "0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF" + "0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF", ); expect(() => decodeStaticField("address", "0x00")).toThrow( - 'Hex value "0x00" has length of 2, but expected length of 40 for address type.' + 'Hex value "0x00" has length of 2, but expected length of 40 for address type.', ); expect(() => decodeStaticField("address", "0xffffffffffffffffffffffffffffffffffffffffff")).toThrow( - 'Hex value "0xffffffffffffffffffffffffffffffffffffffffff" has length of 42, but expected length of 40 for address type.' + 'Hex value "0xffffffffffffffffffffffffffffffffffffffffff" has length of 42, but expected length of 40 for address type.', ); }); }); diff --git a/packages/protocol-parser/src/decodeStaticField.ts b/packages/protocol-parser/src/decodeStaticField.ts index e8595d8832..9d2819d307 100644 --- a/packages/protocol-parser/src/decodeStaticField.ts +++ b/packages/protocol-parser/src/decodeStaticField.ts @@ -10,7 +10,7 @@ import { InvalidHexLengthError, InvalidHexLengthForStaticFieldError } from "./er export function decodeStaticField< TAbiType extends StaticAbiType, - TPrimitiveType extends StaticAbiTypeToPrimitiveType + TPrimitiveType extends StaticAbiTypeToPrimitiveType, >(abiType: TAbiType, data: Hex): TPrimitiveType { if (data.length > 3 && data.length % 2 !== 0) { throw new InvalidHexLengthError(data); diff --git a/packages/protocol-parser/src/decodeValue.ts b/packages/protocol-parser/src/decodeValue.ts index bd96093fed..06bb1a4b4a 100644 --- a/packages/protocol-parser/src/decodeValue.ts +++ b/packages/protocol-parser/src/decodeValue.ts @@ -11,6 +11,6 @@ export function decodeValue(valueSchema: TSchema, d const valueTuple = decodeRecord({ staticFields, dynamicFields }, data); return Object.fromEntries( - Object.keys(valueSchema).map((name, i) => [name, valueTuple[i]]) + Object.keys(valueSchema).map((name, i) => [name, valueTuple[i]]), ) as SchemaToPrimitives; } diff --git a/packages/protocol-parser/src/decodeValueArgs.ts b/packages/protocol-parser/src/decodeValueArgs.ts index d9f5e5161f..62966ba93d 100644 --- a/packages/protocol-parser/src/decodeValueArgs.ts +++ b/packages/protocol-parser/src/decodeValueArgs.ts @@ -7,7 +7,7 @@ import { readHex } from "@latticexyz/common"; export function decodeValueArgs( valueSchema: TSchema, - { staticData, encodedLengths, dynamicData }: ValueArgs + { staticData, encodedLengths, dynamicData }: ValueArgs, ): SchemaToPrimitives { return decodeValue( valueSchema, @@ -15,6 +15,6 @@ export function decodeValueArgs( readHex(staticData, 0, staticDataLength(Object.values(valueSchema).filter(isStaticAbiType))), encodedLengths, dynamicData, - ]) + ]), ); } diff --git a/packages/protocol-parser/src/encodeField.ts b/packages/protocol-parser/src/encodeField.ts index 99e977a850..cacfda1caf 100644 --- a/packages/protocol-parser/src/encodeField.ts +++ b/packages/protocol-parser/src/encodeField.ts @@ -4,7 +4,7 @@ import { Hex, encodePacked } from "viem"; export function encodeField( fieldType: TSchemaAbiType, - value: AbiParameterToPrimitiveType<{ type: TSchemaAbiType }> + value: AbiParameterToPrimitiveType<{ type: TSchemaAbiType }>, ): Hex { if (isArrayAbiType(fieldType) && Array.isArray(value)) { const staticFieldType = arrayAbiTypeToStaticAbiType(fieldType); @@ -13,7 +13,7 @@ export function encodeField( ? "0x" : encodePacked( value.map(() => staticFieldType), - value + value, ); } return encodePacked([fieldType], [value]); diff --git a/packages/protocol-parser/src/encodeKeyTuple.test.ts b/packages/protocol-parser/src/encodeKeyTuple.test.ts index 048e0d2921..2d712fdfe3 100644 --- a/packages/protocol-parser/src/encodeKeyTuple.test.ts +++ b/packages/protocol-parser/src/encodeKeyTuple.test.ts @@ -12,8 +12,8 @@ describe("encodeKeyTuple", () => { staticFields: ["bool"], dynamicFields: [], }, - [true] - ) + [true], + ), ).toStrictEqual(["0x0000000000000000000000000000000000000000000000000000000000000001"]); }); @@ -26,7 +26,7 @@ describe("encodeKeyTuple", () => { "0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF", true, 3, - ]) + ]), ).toStrictEqual([ "0x000000000000000000000000000000000000000000000000000000000000002a", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd6", diff --git a/packages/protocol-parser/src/encodeLengths.test.ts b/packages/protocol-parser/src/encodeLengths.test.ts index 70d6b53187..8bd77ba7de 100644 --- a/packages/protocol-parser/src/encodeLengths.test.ts +++ b/packages/protocol-parser/src/encodeLengths.test.ts @@ -4,13 +4,13 @@ import { encodeLengths } from "./encodeLengths"; describe("encodeLengths", () => { it("can encode empty tuple", () => { expect(encodeLengths([])).toMatchInlineSnapshot( - '"0x0000000000000000000000000000000000000000000000000000000000000000"' + '"0x0000000000000000000000000000000000000000000000000000000000000000"', ); }); it("can encode bool key tuple", () => { expect(encodeLengths(["0x1234", "0x12345678"])).toMatchInlineSnapshot( - '"0x0000000000000000000000000000000000000004000000000200000000000006"' + '"0x0000000000000000000000000000000000000004000000000200000000000006"', ); }); }); diff --git a/packages/protocol-parser/src/encodeLengths.ts b/packages/protocol-parser/src/encodeLengths.ts index 5a3bbf0827..156e275f84 100644 --- a/packages/protocol-parser/src/encodeLengths.ts +++ b/packages/protocol-parser/src/encodeLengths.ts @@ -7,6 +7,6 @@ export function encodeLengths(values: Hex[]): Hex { return padHex( concatHex([...byteLengths.map((length) => encodeField("uint40", length)), encodeField("uint56", totalByteLength)]), - { size: 32, dir: "left" } + { size: 32, dir: "left" }, ); } diff --git a/packages/protocol-parser/src/encodeRecord.test.ts b/packages/protocol-parser/src/encodeRecord.test.ts index 29222756fa..33be538fd3 100644 --- a/packages/protocol-parser/src/encodeRecord.test.ts +++ b/packages/protocol-parser/src/encodeRecord.test.ts @@ -6,7 +6,7 @@ describe("encodeRecord", () => { const valueSchema = { staticFields: ["uint32", "uint128"], dynamicFields: ["uint32[]", "string"] } as const; const hex = encodeRecord(valueSchema, [1, 2n, [3, 4], "some string"]); expect(hex).toBe( - "0x0000000100000000000000000000000000000002000000000000000000000000000000000000000b0000000008000000000000130000000300000004736f6d6520737472696e67" + "0x0000000100000000000000000000000000000002000000000000000000000000000000000000000b0000000008000000000000130000000300000004736f6d6520737472696e67", ); }); diff --git a/packages/protocol-parser/src/encodeRecord.ts b/packages/protocol-parser/src/encodeRecord.ts index b92287830c..6c0e0f4daf 100644 --- a/packages/protocol-parser/src/encodeRecord.ts +++ b/packages/protocol-parser/src/encodeRecord.ts @@ -6,7 +6,7 @@ import { Schema } from "./common"; /** @deprecated use `encodeValue` instead */ export function encodeRecord( valueSchema: Schema, - values: readonly (StaticPrimitiveType | DynamicPrimitiveType)[] + values: readonly (StaticPrimitiveType | DynamicPrimitiveType)[], ): Hex { const staticValues = values.slice(0, valueSchema.staticFields.length) as readonly StaticPrimitiveType[]; const dynamicValues = values.slice(valueSchema.staticFields.length) as readonly DynamicPrimitiveType[]; @@ -18,7 +18,7 @@ export function encodeRecord( if (valueSchema.dynamicFields.length === 0) return `0x${staticData}`; const dynamicDataItems = dynamicValues.map((value, i) => - encodeField(valueSchema.dynamicFields[i], value).replace(/^0x/, "") + encodeField(valueSchema.dynamicFields[i], value).replace(/^0x/, ""), ); const dynamicFieldByteLengths = dynamicDataItems.map((value) => value.length / 2).reverse(); diff --git a/packages/protocol-parser/src/encodeValue.ts b/packages/protocol-parser/src/encodeValue.ts index df85964b65..accb91e0a1 100644 --- a/packages/protocol-parser/src/encodeValue.ts +++ b/packages/protocol-parser/src/encodeValue.ts @@ -4,7 +4,7 @@ import { encodeValueArgs } from "./encodeValueArgs"; export function encodeValue( valueSchema: TSchema, - value: SchemaToPrimitives + value: SchemaToPrimitives, ): Hex { const { staticData, encodedLengths, dynamicData } = encodeValueArgs(valueSchema, value); return concatHex([staticData, encodedLengths, dynamicData]); diff --git a/packages/protocol-parser/src/encodeValueArgs.ts b/packages/protocol-parser/src/encodeValueArgs.ts index 5100f4f753..bc0723f93f 100644 --- a/packages/protocol-parser/src/encodeValueArgs.ts +++ b/packages/protocol-parser/src/encodeValueArgs.ts @@ -13,7 +13,7 @@ import { encodeLengths } from "./encodeLengths"; export function encodeValueArgs( valueSchema: TSchema, - value: SchemaToPrimitives + value: SchemaToPrimitives, ): ValueArgs { const valueSchemaEntries = Object.entries(valueSchema); const staticFields = valueSchemaEntries.filter(([, type]) => isStaticAbiType(type)) as [string, StaticAbiType][]; @@ -23,7 +23,7 @@ export function encodeValueArgs( const encodedStaticValues = staticFields.map(([name, type]) => encodeField(type, value[name] as StaticPrimitiveType)); const encodedDynamicValues = dynamicFields.map(([name, type]) => - encodeField(type, value[name] as DynamicPrimitiveType) + encodeField(type, value[name] as DynamicPrimitiveType), ); const encodedLengths = encodeLengths(encodedDynamicValues); diff --git a/packages/protocol-parser/src/errors.ts b/packages/protocol-parser/src/errors.ts index 1071b89564..168d0eb93d 100644 --- a/packages/protocol-parser/src/errors.ts +++ b/packages/protocol-parser/src/errors.ts @@ -29,7 +29,7 @@ export class InvalidHexLengthForStaticFieldError extends MUDError { super( `Hex value "${value}" has length of ${value.length - 2}, but expected length of ${ staticAbiTypeToByteLength[abiType] * 2 - } for ${abiType} type.` + } for ${abiType} type.`, ); } } @@ -40,7 +40,7 @@ export class InvalidHexLengthForArrayFieldError extends MUDError { super( `Hex value "${value}" has length of ${value.length - 2}, but expected a multiple of ${ staticAbiTypeToByteLength[abiType] * 2 - } for ${abiType}[] type.` + } for ${abiType}[] type.`, ); } } @@ -50,7 +50,7 @@ export class SchemaStaticLengthMismatchError extends MUDError { constructor(schemaData: Hex, definedLength: number, summedLength: number) { super( `Schema "${schemaData}" static data length (${definedLength}) did not match the summed length of all static fields (${summedLength}). ` + - `Is \`staticAbiTypeToByteLength\` up to date with Solidity schema types?` + `Is \`staticAbiTypeToByteLength\` up to date with Solidity schema types?`, ); } } @@ -59,7 +59,7 @@ export class PackedCounterLengthMismatchError extends MUDError { override name = "PackedCounterLengthMismatchError"; constructor(packedCounterData: Hex, definedLength: bigint, summedLength: bigint) { super( - `PackedCounter "${packedCounterData}" total bytes length (${definedLength}) did not match the summed length of all field byte lengths (${summedLength}).` + `PackedCounter "${packedCounterData}" total bytes length (${definedLength}) did not match the summed length of all field byte lengths (${summedLength}).`, ); } } diff --git a/packages/protocol-parser/src/hexToPackedCounter.test.ts b/packages/protocol-parser/src/hexToPackedCounter.test.ts index 82537cc018..91e6a090e0 100644 --- a/packages/protocol-parser/src/hexToPackedCounter.test.ts +++ b/packages/protocol-parser/src/hexToPackedCounter.test.ts @@ -20,16 +20,16 @@ describe("hexToPackedCounter", () => { it("throws if schema hex data is not bytes32", () => { expect(() => hexToPackedCounter("0x01234")).toThrowErrorMatchingInlineSnapshot( - '"Hex value \\"0x01234\\" has length of 5, but expected length of 64 for a packed counter."' + '"Hex value \\"0x01234\\" has length of 5, but expected length of 64 for a packed counter."', ); }); it("throws if packed counter total byte length doesn't match summed byte length of fields", () => { expect(() => - hexToPackedCounter("0x0000000000000000000000000000400000000020000000002000000000000040") + hexToPackedCounter("0x0000000000000000000000000000400000000020000000002000000000000040"), ).toThrowErrorMatchingInlineSnapshot( // eslint-disable-next-line max-len - '"PackedCounter \\"0x0000000000000000000000000000400000000020000000002000000000000040\\" total bytes length (64) did not match the summed length of all field byte lengths (128)."' + '"PackedCounter \\"0x0000000000000000000000000000400000000020000000002000000000000040\\" total bytes length (64) did not match the summed length of all field byte lengths (128)."', ); }); }); diff --git a/packages/protocol-parser/src/hexToSchema.test.ts b/packages/protocol-parser/src/hexToSchema.test.ts index a73b132bbf..cbff4ee435 100644 --- a/packages/protocol-parser/src/hexToSchema.test.ts +++ b/packages/protocol-parser/src/hexToSchema.test.ts @@ -55,14 +55,14 @@ describe("hexToSchema", () => { it("throws if schema hex data is not bytes32", () => { expect(() => hexToSchema("0x002502045f2381c3c4c5")).toThrow( - 'Hex value "0x002502045f2381c3c4c5" has length of 20, but expected length of 64 for a schema.' + 'Hex value "0x002502045f2381c3c4c5" has length of 20, but expected length of 64 for a schema.', ); }); it("throws if schema static field lengths do not match", () => { expect(() => hexToSchema("0x002502045f2381c3c4c500000000000000000000000000000000000000000000")).toThrow( // eslint-disable-next-line max-len - 'Schema "0x002502045f2381c3c4c500000000000000000000000000000000000000000000" static data length (37) did not match the summed length of all static fields (36). Is `staticAbiTypeToByteLength` up to date with Solidity schema types?' + 'Schema "0x002502045f2381c3c4c500000000000000000000000000000000000000000000" static data length (37) did not match the summed length of all static fields (36). Is `staticAbiTypeToByteLength` up to date with Solidity schema types?', ); }); }); diff --git a/packages/protocol-parser/src/hexToSchema.ts b/packages/protocol-parser/src/hexToSchema.ts index ff16f1e5cc..b0b74211bb 100644 --- a/packages/protocol-parser/src/hexToSchema.ts +++ b/packages/protocol-parser/src/hexToSchema.ts @@ -28,7 +28,7 @@ export function hexToSchema(data: Hex): Schema { if (actualStaticDataLength !== staticDataLength) { console.warn( `Schema "${data}" static data length (${staticDataLength}) did not match the summed length of all static fields (${actualStaticDataLength}). ` + - `Is \`staticAbiTypeToByteLength\` up to date with Solidity schema types?` + `Is \`staticAbiTypeToByteLength\` up to date with Solidity schema types?`, ); throw new SchemaStaticLengthMismatchError(data, staticDataLength, actualStaticDataLength); } diff --git a/packages/protocol-parser/src/schemaToHex.test.ts b/packages/protocol-parser/src/schemaToHex.test.ts index 57e051e5fe..82860e7331 100644 --- a/packages/protocol-parser/src/schemaToHex.test.ts +++ b/packages/protocol-parser/src/schemaToHex.test.ts @@ -4,13 +4,13 @@ import { schemaToHex } from "./schemaToHex"; describe("schemaToHex", () => { it("converts schema to hex", () => { expect(schemaToHex({ staticFields: ["bool"], dynamicFields: [] })).toBe( - "0x0001010060000000000000000000000000000000000000000000000000000000" + "0x0001010060000000000000000000000000000000000000000000000000000000", ); expect(schemaToHex({ staticFields: ["bool"], dynamicFields: ["bool[]"] })).toBe( - "0x0001010160c20000000000000000000000000000000000000000000000000000" + "0x0001010160c20000000000000000000000000000000000000000000000000000", ); expect( - schemaToHex({ staticFields: ["bytes32", "int32"], dynamicFields: ["uint256[]", "address[]", "bytes", "string"] }) + schemaToHex({ staticFields: ["bytes32", "int32"], dynamicFields: ["uint256[]", "address[]", "bytes", "string"] }), ).toBe("0x002402045f2381c3c4c500000000000000000000000000000000000000000000"); }); }); diff --git a/packages/react/src/useComponentValue.ts b/packages/react/src/useComponentValue.ts index fecb60ede4..aa7a7bbd10 100644 --- a/packages/react/src/useComponentValue.ts +++ b/packages/react/src/useComponentValue.ts @@ -13,18 +13,18 @@ import { useEffect, useState } from "react"; export function useComponentValue( component: Component, entity: Entity | undefined, - defaultValue: ComponentValue + defaultValue: ComponentValue, ): ComponentValue; export function useComponentValue( component: Component, - entity: Entity | undefined + entity: Entity | undefined, ): ComponentValue | undefined; export function useComponentValue( component: Component, entity: Entity | undefined, - defaultValue?: ComponentValue + defaultValue?: ComponentValue, ) { const [value, setValue] = useState(entity != null ? getComponentValue(component, entity) : undefined); diff --git a/packages/react/src/useEntityQuery.test.ts b/packages/react/src/useEntityQuery.test.ts index 484a8e80a5..12811c388c 100644 --- a/packages/react/src/useEntityQuery.test.ts +++ b/packages/react/src/useEntityQuery.test.ts @@ -36,7 +36,7 @@ describe("useEntityQuery", () => { const { result } = renderHook(() => useEntityQuery([Has(Position)], { updateOnValueChange: false })); const { result: resultOnValueChange } = renderHook(() => - useEntityQuery([Has(Position)], { updateOnValueChange: true }) + useEntityQuery([Has(Position)], { updateOnValueChange: true }), ); expect(result.current.length).toBe(2); @@ -80,7 +80,7 @@ describe("useEntityQuery", () => { const { result } = renderHook(() => useEntityQuery([Has(Position)], { updateOnValueChange: false })); const { result: resultOnValueChange } = renderHook(() => - useEntityQuery([Has(Position)], { updateOnValueChange: true }) + useEntityQuery([Has(Position)], { updateOnValueChange: true }), ); expect(result.all).toHaveLength(2); diff --git a/packages/react/src/usePromise.ts b/packages/react/src/usePromise.ts index a53806d37d..2c3fbfa111 100644 --- a/packages/react/src/usePromise.ts +++ b/packages/react/src/usePromise.ts @@ -7,7 +7,7 @@ export type UsePromiseResult = PromiseSettledResult> | { status: " export function usePromise(promise: PromiseLike | null | undefined) { const promiseRef = useRef(promise); const [result, setResult] = useState>( - promise == null ? { status: "idle" } : { status: "pending" } + promise == null ? { status: "idle" } : { status: "pending" }, ); useEffect(() => { diff --git a/packages/recs/CHANGELOG.md b/packages/recs/CHANGELOG.md index 4de2c01b38..472da33f59 100644 --- a/packages/recs/CHANGELOG.md +++ b/packages/recs/CHANGELOG.md @@ -339,7 +339,7 @@ .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/packages/recs/src/Component.ts b/packages/recs/src/Component.ts index 58a56e8047..ccc5d038a5 100644 --- a/packages/recs/src/Component.ts +++ b/packages/recs/src/Component.ts @@ -55,7 +55,7 @@ function getComponentName(component: Component) { export function defineComponent( world: World, schema: S, - options?: { id?: string; metadata?: M; indexed?: boolean } + options?: { id?: string; metadata?: M; indexed?: boolean }, ) { if (Object.keys(schema).length === 0) throw new Error("Component schema must have at least one key"); const id = options?.id ?? uuid(); @@ -86,7 +86,7 @@ export function setComponent( component: Component, entity: Entity, value: ComponentValue, - options: ComponentMutationOptions = {} + options: ComponentMutationOptions = {}, ) { const entitySymbol = getEntitySymbol(entity); const prevValue = getComponentValue(component, entity); @@ -110,7 +110,7 @@ export function setComponent( "for entity", entity, ". Existing keys: ", - Object.keys(component.values) + Object.keys(component.values), ); } } @@ -141,7 +141,7 @@ export function updateComponent( entity: Entity, value: Partial>, initialValue?: ComponentValue, - options: ComponentMutationOptions = {} + options: ComponentMutationOptions = {}, ) { const currentValue = getComponentValue(component, entity); if (currentValue === undefined) { @@ -163,7 +163,7 @@ export function updateComponent( export function removeComponent( component: Component, entity: Entity, - options: ComponentMutationOptions = {} + options: ComponentMutationOptions = {}, ) { const entitySymbol = getEntitySymbol(entity); const prevValue = getComponentValue(component, entity); @@ -184,7 +184,7 @@ export function removeComponent( component: Component, - entity: Entity + entity: Entity, ): boolean { const entitySymbol = getEntitySymbol(entity); const map = Object.values(component.values)[0]; @@ -201,7 +201,7 @@ export function hasComponent( */ export function getComponentValue( component: Component, - entity: Entity + entity: Entity, ): ComponentValue | undefined { const value: Record = {}; const entitySymbol = getEntitySymbol(entity); @@ -230,7 +230,7 @@ export function getComponentValue( */ export function getComponentValueStrict( component: Component, - entity: Entity + entity: Entity, ): ComponentValue { const value = getComponentValue(component, entity); if (!value) throw new Error(`No value for component ${getComponentName(component)} on entity ${entity}`); @@ -253,7 +253,7 @@ export function getComponentValueStrict( */ export function componentValueEquals( a?: Partial>, - b?: ComponentValue + b?: ComponentValue, ): boolean { if (!a && !b) return true; if (!a || !b) return false; @@ -276,7 +276,7 @@ export function componentValueEquals( */ export function withValue( component: Component, - value: ComponentValue + value: ComponentValue, ): [Component, ComponentValue] { return [component, value]; } @@ -290,7 +290,7 @@ export function withValue( */ export function getEntitiesWithValue( component: Component | Indexer, - value: Partial> + value: Partial>, ): Set { // Shortcut for indexers if (isIndexer(component) && isFullComponentValue(component, value)) { @@ -315,7 +315,7 @@ export function getEntitiesWithValue( * @returns Set of all entities in the given component. */ export function getComponentEntities( - component: Component + component: Component, ): IterableIterator { return component.entities(); } @@ -335,7 +335,7 @@ export function getComponentEntities( * @returns overridable component */ export function overridableComponent( - component: Component + component: Component, ): OverridableComponent { let nonce = 0; @@ -457,7 +457,7 @@ export function overridableComponent !overriddenEntityValues.get(getEntitySymbol(e.entity))), - map((update) => ({ ...update, component: overriddenComponent })) + map((update) => ({ ...update, component: overriddenComponent })), ) .subscribe(update$); @@ -475,7 +475,7 @@ export function clearLocalCache(component: Component, uniqueWorldIdentifier?: st // Note: Only proof of concept for now - use this only for component that do not update frequently export function createLocalCache( component: Component, - uniqueWorldIdentifier?: string + uniqueWorldIdentifier?: string, ): Component { const { world, update$, values } = component; const cacheId = getLocalCacheId(component as Component, uniqueWorldIdentifier); @@ -509,7 +509,7 @@ export function createLocalCache { numUpdates++; const encoded = JSON.stringify( - Object.entries(mapObject(values, (m) => [...m.entries()].map((e) => [getEntityString(e[0]), e[1]]))) + Object.entries(mapObject(values, (m) => [...m.entries()].map((e) => [getEntityString(e[0]), e[1]]))), ); localStorage.setItem(cacheId, encoded); if (numUpdates > 200) { @@ -520,7 +520,7 @@ export function createLocalCache( - component: Component + component: Component, ): Indexer { const valueToEntities = new Map>(); diff --git a/packages/recs/src/Query.spec.ts b/packages/recs/src/Query.spec.ts index b75f91b474..1c200a5d34 100644 --- a/packages/recs/src/Query.spec.ts +++ b/packages/recs/src/Query.spec.ts @@ -98,27 +98,27 @@ describe("Query", () => { expect(runQuery([HasValue(OwnedByEntity, { value: Player })])).toEqual(new Set([Depth1])); expect(runQuery([ProxyExpand(OwnedByEntity, 0), HasValue(OwnedByEntity, { value: Player })])).toEqual( - new Set([Depth1]) + new Set([Depth1]), ); expect(runQuery([ProxyExpand(OwnedByEntity, 1), HasValue(OwnedByEntity, { value: Player })])).toEqual( - new Set([Depth1, Depth2]) + new Set([Depth1, Depth2]), ); expect(runQuery([ProxyExpand(OwnedByEntity, 2), HasValue(OwnedByEntity, { value: Player })])).toEqual( - new Set([Depth1, Depth2, Depth3]) + new Set([Depth1, Depth2, Depth3]), ); expect(runQuery([ProxyExpand(OwnedByEntity, 3), HasValue(OwnedByEntity, { value: Player })])).toEqual( - new Set([Depth1, Depth2, Depth3, Depth4]) + new Set([Depth1, Depth2, Depth3, Depth4]), ); expect(runQuery([ProxyExpand(OwnedByEntity, 4), HasValue(OwnedByEntity, { value: Player })])).toEqual( - new Set([Depth1, Depth2, Depth3, Depth4, Depth5]) + new Set([Depth1, Depth2, Depth3, Depth4, Depth5]), ); expect( - runQuery([ProxyExpand(OwnedByEntity, Number.MAX_SAFE_INTEGER), HasValue(OwnedByEntity, { value: Player })]) + runQuery([ProxyExpand(OwnedByEntity, Number.MAX_SAFE_INTEGER), HasValue(OwnedByEntity, { value: Player })]), ).toEqual(new Set([Depth1, Depth2, Depth3, Depth4, Depth5])); }); @@ -132,8 +132,8 @@ describe("Query", () => { expect( runQuery( [ProxyRead(OwnedByEntity, 1), HasValue(Name, { name: "Alice" })], - new Set([Depth1, Depth2, Depth3]) // Provide an initial set of entities - ) + new Set([Depth1, Depth2, Depth3]), // Provide an initial set of entities + ), ).toEqual(new Set([Depth1])); expect( @@ -142,7 +142,7 @@ describe("Query", () => { HasValue(Name, { name: "Alice" }), // Get all entities with name Alice or owned by Alice ProxyExpand(OwnedByEntity, 0), // Turn off proxy expand NotValue(Name, { name: "Alice" }), // Filter Alice, only keep entities owned by Alice - ]) + ]), ).toEqual(new Set([Depth1])); expect( @@ -151,15 +151,15 @@ describe("Query", () => { HasValue(Name, { name: "Alice" }), // Get all child entities of Alice (including alice) ProxyExpand(OwnedByEntity, 0), // Turn off proxy expand NotValue(Name, { name: "Alice" }), // Filter Alice, only keep entities owned by Alice - ]) + ]), ).toEqual(new Set([Depth1, Depth2, Depth3, Depth4])); // Get all entities from the initial set [Depth3] that have an indirect owner called Alice expect( runQuery( [ProxyRead(OwnedByEntity, Number.MAX_SAFE_INTEGER), HasValue(Name, { name: "Alice" })], - new Set([Depth3]) // Provide an initial set of entities - ) + new Set([Depth3]), // Provide an initial set of entities + ), ).toEqual(new Set([Depth3])); // Get all entities that have an indirect owner called Alice @@ -171,8 +171,8 @@ describe("Query", () => { ProxyRead(OwnedByEntity, 0), NotValue(Name, { name: "Alice" }), ], - new Set([Player, Depth1, Depth2, Depth3, Depth4]) // Provide an initial set of entities - ) + new Set([Player, Depth1, Depth2, Depth3, Depth4]), // Provide an initial set of entities + ), ).toEqual(new Set([Depth1, Depth2, Depth3, Depth4])); // Get all entities from the initial set [Depth3] that have an indirect owner called Alice and their direct child @@ -183,8 +183,8 @@ describe("Query", () => { ProxyExpand(OwnedByEntity, 1), HasValue(Name, { name: "Alice" }), ], - new Set([Depth2]) // Provide an initial set of entities - ) + new Set([Depth2]), // Provide an initial set of entities + ), ).toEqual(new Set([Depth2, Depth3])); }); @@ -204,15 +204,15 @@ describe("Query", () => { createEntity(world, [withValue(Position, { x: 1, y: 1 })]); expect(runQuery([ProxyExpand(FromPrototype, 1), Has(CanMove), Not(Prototype)])).toEqual( - new Set([instance1, instance2]) + new Set([instance1, instance2]), ); expect(runQuery([Has(Position), ProxyRead(FromPrototype, 1), Has(CanMove)])).toEqual( - new Set([instance1, instance2]) + new Set([instance1, instance2]), ); expect(runQuery([ProxyRead(FromPrototype, 1), Has(Position), Has(CanMove)])).toEqual( - new Set([instance1, instance2]) + new Set([instance1, instance2]), ); }); @@ -287,7 +287,7 @@ describe("Query", () => { Has(CanMove), // ...have the CanMove component... ProxyRead(OwnedByEntity, Number.MAX_SAFE_INTEGER), // ...and for whose owner holds... NotValue(Name, { name: "Alice" }), // ...their name is not Alice - ]) + ]), ).toEqual(new Set([Instance3, Entity8])); }); @@ -343,14 +343,14 @@ describe("Query", () => { entity: entities[0], component: CanMove, value: [{ value: true }, undefined], - }) + }), ); expect(mock).toHaveBeenCalledWith( expect.objectContaining({ entity: entities[1], component: CanMove, value: [{ value: true }, undefined], - }) + }), ); expect(mock).toBeCalledTimes(2); @@ -360,7 +360,7 @@ describe("Query", () => { entity: entities[2], component: CanMove, value: [{ value: true }, undefined], - }) + }), ); expect(mock).toHaveBeenCalledTimes(3); }); @@ -388,7 +388,7 @@ describe("Query", () => { entity: entity1, component: CanMove, value: [undefined, { value: true }], - }) + }), ); removeComponent(CanMove, entity2); @@ -398,7 +398,7 @@ describe("Query", () => { entity: entity2, component: CanMove, value: [undefined, { value: true }], - }) + }), ); }); }); @@ -617,7 +617,7 @@ describe("Query", () => { const query1 = defineQuery( [ProxyRead(OwnedByEntity, 1), HasValue(Name, { name: "Alice" })], - { initialSet: new Set([Depth1, Depth2, Depth3]) } // Provide an initial set of entities + { initialSet: new Set([Depth1, Depth2, Depth3]) }, // Provide an initial set of entities ); query1.update$.subscribe(); @@ -639,7 +639,7 @@ describe("Query", () => { const query4 = defineQuery( [ProxyRead(OwnedByEntity, Number.MAX_SAFE_INTEGER), HasValue(Name, { name: "Alice" })], - { initialSet: new Set([Depth3]) } // Provide an initial set of entities + { initialSet: new Set([Depth3]) }, // Provide an initial set of entities ); query4.update$.subscribe(); @@ -650,7 +650,7 @@ describe("Query", () => { ProxyRead(OwnedByEntity, 0), NotValue(Name, { name: "Alice" }), ], - { initialSet: new Set([Player, Depth1, Depth2, Depth3, Depth4]) } // Provide an initial set of entities + { initialSet: new Set([Player, Depth1, Depth2, Depth3, Depth4]) }, // Provide an initial set of entities ); query5.update$.subscribe(); @@ -660,7 +660,7 @@ describe("Query", () => { ProxyExpand(OwnedByEntity, 1), HasValue(Name, { name: "Alice" }), ], - { initialSet: new Set([Depth2]) } // Provide an initial set of entities + { initialSet: new Set([Depth2]) }, // Provide an initial set of entities ); query6.update$.subscribe(); diff --git a/packages/recs/src/Query.ts b/packages/recs/src/Query.ts index b32c2e2563..2ebce7fa81 100644 --- a/packages/recs/src/Query.ts +++ b/packages/recs/src/Query.ts @@ -88,7 +88,7 @@ export function Not(component: Component): NotQueryFragment */ export function HasValue( component: Component, - value: Partial> + value: Partial>, ): HasValueQueryFragment { return { type: QueryFragmentType.HasValue, component, value }; } @@ -112,7 +112,7 @@ export function HasValue( */ export function NotValue( component: Component, - value: Partial> + value: Partial>, ): NotValueQueryFragment { return { type: QueryFragmentType.NotValue, component, value }; } @@ -199,7 +199,7 @@ function passesQueryFragment(entity: Entity, fragment: EntityQ * @returns True if the query fragment is positive, else false. */ function isPositiveFragment( - fragment: QueryFragment + fragment: QueryFragment, ): fragment is HasQueryFragment | HasValueQueryFragment { return fragment.type === QueryFragmentType.Has || fragment.type == QueryFragmentType.HasValue; } @@ -211,7 +211,7 @@ function isPositiveFragment( * @returns True if the query fragment is negative, else false. */ function isNegativeFragment( - fragment: QueryFragment + fragment: QueryFragment, ): fragment is NotQueryFragment | NotValueQueryFragment { return fragment.type === QueryFragmentType.Not || fragment.type == QueryFragmentType.NotValue; } @@ -253,7 +253,7 @@ function isBreakingPassState(passes: boolean, fragment: EntityQueryFragment( entity: Entity, fragment: EntityQueryFragment, - proxyRead: ProxyReadQueryFragment + proxyRead: ProxyReadQueryFragment, ): boolean | null { let proxyEntity = entity; let passes = false; @@ -288,7 +288,7 @@ function passesQueryFragmentProxy( export function getChildEntities( entity: Entity, component: Component<{ value: Type.Entity }>, - depth: number + depth: number, ): Set { if (depth === 0) return new Set(); @@ -416,7 +416,7 @@ export function runQuery(fragments: QueryFragment[], initialSet?: Set): */ export function defineQuery( fragments: QueryFragment[], - options?: { runOnInit?: boolean; initialSet?: Set } + options?: { runOnInit?: boolean; initialSet?: Set }, ): { update$: Observable; matching: ObservableSet; @@ -503,7 +503,7 @@ export function defineQuery( return { ...update, type: UpdateType.Enter }; } }), - filterNullish() + filterNullish(), ); return { @@ -521,7 +521,7 @@ export function defineQuery( */ export function defineUpdateQuery( fragments: QueryFragment[], - options?: { runOnInit?: boolean } + options?: { runOnInit?: boolean }, ): Observable { return defineQuery(fragments, options).update$.pipe(filter((e) => e.type === UpdateType.Update)); } @@ -535,7 +535,7 @@ export function defineUpdateQuery( */ export function defineEnterQuery( fragments: QueryFragment[], - options?: { runOnInit?: boolean } + options?: { runOnInit?: boolean }, ): Observable { return defineQuery(fragments, options).update$.pipe(filter((e) => e.type === UpdateType.Enter)); } @@ -549,7 +549,7 @@ export function defineEnterQuery( */ export function defineExitQuery( fragments: QueryFragment[], - options?: { runOnInit?: boolean } + options?: { runOnInit?: boolean }, ): Observable { return defineQuery(fragments, options).update$.pipe(filter((e) => e.type === UpdateType.Exit)); } diff --git a/packages/recs/src/System.spec.ts b/packages/recs/src/System.spec.ts index 2f872323f6..4c0a6680a3 100644 --- a/packages/recs/src/System.spec.ts +++ b/packages/recs/src/System.spec.ts @@ -100,13 +100,13 @@ describe("System", () => { expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith( - expect.objectContaining({ entity: entity1, component: CanMove, value: [{ value: true }, undefined] }) + expect.objectContaining({ entity: entity1, component: CanMove, value: [{ value: true }, undefined] }), ); const entity2 = createEntity(world, [withValue(CanMove, { value: true })]); expect(mock).toHaveBeenCalledTimes(2); expect(mock).toHaveBeenCalledWith( - expect.objectContaining({ entity: entity2, component: CanMove, value: [{ value: true }, undefined] }) + expect.objectContaining({ entity: entity2, component: CanMove, value: [{ value: true }, undefined] }), ); }); @@ -126,13 +126,13 @@ describe("System", () => { expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith( - expect.objectContaining({ entity: entity1, component: CanMove, value: [undefined, { value: true }] }) + expect.objectContaining({ entity: entity1, component: CanMove, value: [undefined, { value: true }] }), ); removeComponent(CanMove, entity2); expect(mock).toHaveBeenCalledTimes(2); expect(mock).toHaveBeenCalledWith( - expect.objectContaining({ entity: entity2, component: CanMove, value: [undefined, { value: true }] }) + expect.objectContaining({ entity: entity2, component: CanMove, value: [undefined, { value: true }] }), ); }); }); diff --git a/packages/recs/src/System.ts b/packages/recs/src/System.ts index eaf8d2b2a0..6f91498bd3 100644 --- a/packages/recs/src/System.ts +++ b/packages/recs/src/System.ts @@ -36,7 +36,7 @@ export function defineUpdateSystem( world: World, query: QueryFragment[], system: (update: ComponentUpdate) => void, - options: { runOnInit?: boolean } = { runOnInit: true } + options: { runOnInit?: boolean } = { runOnInit: true }, ) { defineRxSystem(world, defineUpdateQuery(query, options), system); } @@ -56,7 +56,7 @@ export function defineEnterSystem( world: World, query: QueryFragment[], system: (update: ComponentUpdate) => void, - options: { runOnInit?: boolean } = { runOnInit: true } + options: { runOnInit?: boolean } = { runOnInit: true }, ) { defineRxSystem(world, defineEnterQuery(query, options), system); } @@ -76,7 +76,7 @@ export function defineExitSystem( world: World, query: QueryFragment[], system: (update: ComponentUpdate) => void, - options: { runOnInit?: boolean } = { runOnInit: true } + options: { runOnInit?: boolean } = { runOnInit: true }, ) { defineRxSystem(world, defineExitQuery(query, options), system); } @@ -96,7 +96,7 @@ export function defineSystem( world: World, query: QueryFragment[], system: (update: ComponentUpdate & { type: UpdateType }) => void, - options: { runOnInit?: boolean } = { runOnInit: true } + options: { runOnInit?: boolean } = { runOnInit: true }, ) { defineRxSystem(world, defineQuery(query, options).update$, system); } @@ -116,7 +116,7 @@ export function defineComponentSystem( world: World, component: Component, system: (update: ComponentUpdate) => void, - options: { runOnInit?: boolean } = { runOnInit: true } + options: { runOnInit?: boolean } = { runOnInit: true }, ) { const initial$ = options?.runOnInit ? from(getComponentEntities(component)).pipe(toUpdateStream(component)) : EMPTY; defineRxSystem(world, concat(initial$, component.update$), system); @@ -135,7 +135,7 @@ export function defineSyncSystem( query: QueryFragment[], component: (entity: Entity) => Component, value: (entity: Entity) => ComponentValue, - options: { update?: boolean; runOnInit?: boolean } = { update: false, runOnInit: true } + options: { update?: boolean; runOnInit?: boolean } = { update: false, runOnInit: true }, ) { defineSystem( world, @@ -145,6 +145,6 @@ export function defineSyncSystem( if (type === UpdateType.Exit) removeComponent(component(entity), entity); if (options?.update && type === UpdateType.Update) setComponent(component(entity), entity, value(entity)); }, - options + options, ); } diff --git a/packages/recs/src/deprecated/createActionSystem.spec.ts b/packages/recs/src/deprecated/createActionSystem.spec.ts index b1d0c0653f..ac224b2261 100644 --- a/packages/recs/src/deprecated/createActionSystem.spec.ts +++ b/packages/recs/src/deprecated/createActionSystem.spec.ts @@ -177,7 +177,7 @@ describe("ActionSystem", () => { expect(runQuery([HasValue(Action, { on: settlement1 })])).toEqual(new Set([entity1])); expect(runQuery([HasValue(Action, { on: settlement2 })])).toEqual(new Set([entity2])); expect(runQuery([HasValue(Action, { state: ActionState.Requested })])).toEqual( - new Set([entity1, entity2, entity3]) + new Set([entity1, entity2, entity3]), ); }); diff --git a/packages/recs/src/deprecated/createActionSystem.ts b/packages/recs/src/deprecated/createActionSystem.ts index 1cbe367ac1..94b245fce7 100644 --- a/packages/recs/src/deprecated/createActionSystem.ts +++ b/packages/recs/src/deprecated/createActionSystem.ts @@ -15,7 +15,7 @@ export type ActionSystem = ReturnType; export function createActionSystem( world: World, txReduced$: Observable, - waitForTransaction?: (tx: string) => Promise + waitForTransaction?: (tx: string) => Promise, ) { // Action component const Action = defineActionComponent(world); @@ -40,7 +40,7 @@ export function createActionSystem( * @returns Components including pending updates */ function withOptimisticUpdates( - component: Component + component: Component, ): OverridableComponent { const optimisticComponent = componentsWithOptimisticUpdates[component.id] || overridableComponent(component); @@ -99,7 +99,7 @@ export function createActionSystem( // This subscriotion makes sure the action requirement is checked again every time // one of the referenced components changes or the pending updates map changes const subscription = merge( - ...Object.values(action.componentsWithOptimisticUpdates).map((c) => c.update$) + ...Object.values(action.componentsWithOptimisticUpdates).map((c) => c.update$), ).subscribe(() => checkRequirement(action)); checkRequirement(action); disposer.set(action.id, { dispose: () => subscription?.unsubscribe() }); diff --git a/packages/recs/src/deprecated/defineActionComponent.ts b/packages/recs/src/deprecated/defineActionComponent.ts index 6d73b4882e..3da5829a50 100644 --- a/packages/recs/src/deprecated/defineActionComponent.ts +++ b/packages/recs/src/deprecated/defineActionComponent.ts @@ -12,7 +12,7 @@ export function defineActionComponent(world: World) { overrides: Type.OptionalStringArray, txHash: Type.OptionalString, }, - { id: "Action" } + { id: "Action" }, ); return Action as Component, Metadata, T>; } diff --git a/packages/recs/src/deprecated/waitForActionCompletion.ts b/packages/recs/src/deprecated/waitForActionCompletion.ts index c271c29ce5..e7378bab57 100644 --- a/packages/recs/src/deprecated/waitForActionCompletion.ts +++ b/packages/recs/src/deprecated/waitForActionCompletion.ts @@ -5,7 +5,7 @@ import { waitForComponentValueIn } from "./waitForComponentValueIn"; export async function waitForActionCompletion( Action: ReturnType, - entity: Entity + entity: Entity, ): Promise { return waitForComponentValueIn(Action, entity, [ { state: ActionState.Cancelled }, diff --git a/packages/recs/src/deprecated/waitForComponentValueIn.ts b/packages/recs/src/deprecated/waitForComponentValueIn.ts index 97fba687aa..318649b381 100644 --- a/packages/recs/src/deprecated/waitForComponentValueIn.ts +++ b/packages/recs/src/deprecated/waitForComponentValueIn.ts @@ -6,7 +6,7 @@ import { Component, Metadata, Entity, ComponentValue, Schema } from "../types"; export function waitForComponentValueIn( component: Component, entity: Entity, - values: Partial>[] + values: Partial>[], ): Promise { const [resolve, , promise] = deferred(); @@ -19,13 +19,13 @@ export function waitForComponentValueIn( const value$ = component.update$.pipe( filter((update) => update.entity === entity), // Ignore updates of other entities - map((update) => update.value[0]) // Map the update to the current value + map((update) => update.value[0]), // Map the update to the current value ); const subscription = value$ .pipe( startWith(getComponentValue(component, entity)), - filter((currentValue) => Boolean(values.find((searchValue) => componentValueEquals(searchValue, currentValue)))) + filter((currentValue) => Boolean(values.find((searchValue) => componentValueEquals(searchValue, currentValue)))), ) .subscribe(() => { resolve(); diff --git a/packages/recs/src/utils.ts b/packages/recs/src/utils.ts index 4407acc17a..33989a7ec5 100644 --- a/packages/recs/src/utils.ts +++ b/packages/recs/src/utils.ts @@ -12,7 +12,7 @@ import { Component, ComponentUpdate, ComponentValue, Entity, Indexer, Schema } f */ export function isComponentUpdate( update: ComponentUpdate, - component: Component + component: Component, ): update is ComponentUpdate { return update.component === component; } @@ -62,7 +62,7 @@ export function isIndexer(c: Component | Indexer): c is */ export function isFullComponentValue( component: Component, - value: Partial> + value: Partial>, ): value is ComponentValue { return Object.keys(component.schema).every((key) => key in value); } diff --git a/packages/schema-type/src/typescript/arrayAbiTypes.ts b/packages/schema-type/src/typescript/arrayAbiTypes.ts index 76c7d69673..00dc9a733c 100644 --- a/packages/schema-type/src/typescript/arrayAbiTypes.ts +++ b/packages/schema-type/src/typescript/arrayAbiTypes.ts @@ -11,7 +11,7 @@ export function isArrayAbiType(abiType: string): } export function arrayAbiTypeToStaticAbiType( - abiType: T + abiType: T, ): ArrayAbiTypeToStaticAbiType { return abiType.replace(arrayAbiTypePattern, "") as ArrayAbiTypeToStaticAbiType; } diff --git a/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToPrimitiveType.ts b/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToPrimitiveType.ts index 02982cc2a1..13c9b7c977 100644 --- a/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToPrimitiveType.ts +++ b/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToPrimitiveType.ts @@ -8,5 +8,5 @@ export type AbiTypeToPrimitiveType = T extends `${infer Static ? StaticAbiTypeToPrimitiveType[] : never : T extends AbiType - ? StaticAbiTypeToPrimitiveType - : never; + ? StaticAbiTypeToPrimitiveType + : never; diff --git a/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToSchemaType.ts b/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToSchemaType.ts index fb7f484ad9..9e0d93640a 100644 --- a/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToSchemaType.ts +++ b/packages/schema-type/src/typescript/deprecated/mappings/AbiTypeToSchemaType.ts @@ -2,5 +2,5 @@ import { SchemaTypeToAbiType } from "./SchemaTypeToAbiType"; import { SchemaType } from "../SchemaType"; export const AbiTypeToSchemaType = Object.fromEntries( - Object.entries(SchemaTypeToAbiType).map(([schemaType, abiType]) => [abiType, parseInt(schemaType) as SchemaType]) + Object.entries(SchemaTypeToAbiType).map(([schemaType, abiType]) => [abiType, parseInt(schemaType) as SchemaType]), ) satisfies Record; diff --git a/packages/schema-type/src/typescript/deprecated/types/StaticAbiTypes.ts b/packages/schema-type/src/typescript/deprecated/types/StaticAbiTypes.ts index d4b3506c13..db658108b5 100644 --- a/packages/schema-type/src/typescript/deprecated/types/StaticAbiTypes.ts +++ b/packages/schema-type/src/typescript/deprecated/types/StaticAbiTypes.ts @@ -6,5 +6,5 @@ import { StaticSchemaType } from "./StaticSchemaType"; export type StaticAbiType = (typeof SchemaTypeToAbiType)[StaticSchemaType]; export const StaticAbiTypes = AbiTypes.filter( - (abiType) => getStaticByteLength(AbiTypeToSchemaType[abiType]) > 0 + (abiType) => getStaticByteLength(AbiTypeToSchemaType[abiType]) > 0, ) as StaticAbiType[]; diff --git a/packages/schema-type/src/typescript/schemaAbiTypes.test.ts b/packages/schema-type/src/typescript/schemaAbiTypes.test.ts index 6d23754108..df77fed6f8 100644 --- a/packages/schema-type/src/typescript/schemaAbiTypes.test.ts +++ b/packages/schema-type/src/typescript/schemaAbiTypes.test.ts @@ -9,7 +9,7 @@ describe("schemaAbiTypes", () => { const soliditySchemaTypes = matches?.[1].replace(/\s/g, "").split(",") ?? []; const soliditySchemaTypesAsAbiTypes = soliditySchemaTypes.map((soliditySchemaType) => - soliditySchemaType.replace(/_ARRAY$/, "[]").toLowerCase() + soliditySchemaType.replace(/_ARRAY$/, "[]").toLowerCase(), ); expect(soliditySchemaTypesAsAbiTypes).toStrictEqual(schemaAbiTypes); diff --git a/packages/schema-type/src/typescript/utils.ts b/packages/schema-type/src/typescript/utils.ts index 65d1a05c65..543d6fd6d9 100644 --- a/packages/schema-type/src/typescript/utils.ts +++ b/packages/schema-type/src/typescript/utils.ts @@ -3,21 +3,22 @@ import { Hex } from "viem"; export type TupleSplit = O["length"] extends N ? [O, T] : T extends readonly [infer F, ...infer R] - ? TupleSplit - : [O, T]; + ? TupleSplit + : [O, T]; -export type LiteralToBroad = T extends Readonly> - ? readonly LiteralToBroad[] - : T extends Array - ? LiteralToBroad[] - : T extends number - ? number - : T extends bigint - ? bigint - : T extends Hex - ? Hex - : T extends boolean - ? boolean - : T extends string - ? string - : never; +export type LiteralToBroad = + T extends Readonly> + ? readonly LiteralToBroad[] + : T extends Array + ? LiteralToBroad[] + : T extends number + ? number + : T extends bigint + ? bigint + : T extends Hex + ? Hex + : T extends boolean + ? boolean + : T extends string + ? string + : never; diff --git a/packages/services/protobuf/ts/faucet/faucet.ts b/packages/services/protobuf/ts/faucet/faucet.ts index 0bdb04e62f..c60dc04035 100644 --- a/packages/services/protobuf/ts/faucet/faucet.ts +++ b/packages/services/protobuf/ts/faucet/faucet.ts @@ -231,7 +231,7 @@ export const FaucetStore = { } return acc; }, - {} + {}, ); message.usernameToAddress = Object.entries(object.usernameToAddress ?? {}).reduce<{ [key: string]: string }>( (acc, [key, value]) => { @@ -240,7 +240,7 @@ export const FaucetStore = { } return acc; }, - {} + {}, ); message.latestDrip = Object.entries(object.latestDrip ?? {}).reduce<{ [key: string]: number }>( (acc, [key, value]) => { @@ -249,7 +249,7 @@ export const FaucetStore = { } return acc; }, - {} + {}, ); message.totalDripCount = object.totalDripCount ?? 0; return message; @@ -1092,24 +1092,24 @@ export interface FaucetServiceImplementation { dripVerifyTweet(request: DripRequest, context: CallContext & CallContextExt): Promise>; timeUntilDrip( request: DripRequest, - context: CallContext & CallContextExt + context: CallContext & CallContextExt, ): Promise>; getLinkedTwitters( request: GetLinkedTwittersRequest, - context: CallContext & CallContextExt + context: CallContext & CallContextExt, ): Promise>; getLinkedTwitterForAddress( request: LinkedTwitterForAddressRequest, - context: CallContext & CallContextExt + context: CallContext & CallContextExt, ): Promise>; getLinkedAddressForTwitter( request: LinkedAddressForTwitterRequest, - context: CallContext & CallContextExt + context: CallContext & CallContextExt, ): Promise>; /** Admin utility endpoints for modifying state. Requires a signature with faucet private key. */ setLinkedTwitter( request: SetLinkedTwitterRequest, - context: CallContext & CallContextExt + context: CallContext & CallContextExt, ): Promise>; } @@ -1119,24 +1119,24 @@ export interface FaucetServiceClient { dripVerifyTweet(request: DeepPartial, options?: CallOptions & CallOptionsExt): Promise; timeUntilDrip( request: DeepPartial, - options?: CallOptions & CallOptionsExt + options?: CallOptions & CallOptionsExt, ): Promise; getLinkedTwitters( request: DeepPartial, - options?: CallOptions & CallOptionsExt + options?: CallOptions & CallOptionsExt, ): Promise; getLinkedTwitterForAddress( request: DeepPartial, - options?: CallOptions & CallOptionsExt + options?: CallOptions & CallOptionsExt, ): Promise; getLinkedAddressForTwitter( request: DeepPartial, - options?: CallOptions & CallOptionsExt + options?: CallOptions & CallOptionsExt, ): Promise; /** Admin utility endpoints for modifying state. Requires a signature with faucet private key. */ setLinkedTwitter( request: DeepPartial, - options?: CallOptions & CallOptionsExt + options?: CallOptions & CallOptionsExt, ): Promise; } @@ -1164,12 +1164,12 @@ type Builtin = Date | Function | Uint8Array | string | number | boolean | undefi export type DeepPartial = T extends Builtin ? T : T extends Array - ? Array> - : T extends ReadonlyArray - ? ReadonlyArray> - : T extends {} - ? { [K in keyof T]?: DeepPartial } - : Partial; + ? Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends {} + ? { [K in keyof T]?: DeepPartial } + : Partial; function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { diff --git a/packages/services/ts/faucet/createFaucetService.ts b/packages/services/ts/faucet/createFaucetService.ts index f82eb82c22..ea0b1c565b 100644 --- a/packages/services/ts/faucet/createFaucetService.ts +++ b/packages/services/ts/faucet/createFaucetService.ts @@ -8,7 +8,7 @@ import { FromTsProtoServiceDefinition } from "nice-grpc-web/lib/service-definiti * @returns FaucetServiceClient */ export function createFaucetService( - url: string + url: string, ): RawClient> { return createClient(FaucetServiceDefinition, createChannel(url)); } diff --git a/packages/solhint-plugin-mud/src/rules/NoMsgSender.ts b/packages/solhint-plugin-mud/src/rules/NoMsgSender.ts index 1c81e6ef51..fb3751c4dd 100644 --- a/packages/solhint-plugin-mud/src/rules/NoMsgSender.ts +++ b/packages/solhint-plugin-mud/src/rules/NoMsgSender.ts @@ -29,7 +29,7 @@ export class NoMsgSender implements SolhintRule { this.reporter.error( node, this.ruleId, - `Systems and their libraries should use "_msgSender()" or "_world()" instead of "msg.sender".` + `Systems and their libraries should use "_msgSender()" or "_world()" instead of "msg.sender".`, ); } } diff --git a/packages/solhint-plugin-mud/src/rules/SystemFileName.ts b/packages/solhint-plugin-mud/src/rules/SystemFileName.ts index 2e8706fbba..337cebb1d5 100644 --- a/packages/solhint-plugin-mud/src/rules/SystemFileName.ts +++ b/packages/solhint-plugin-mud/src/rules/SystemFileName.ts @@ -46,7 +46,7 @@ export class SystemFileName implements SolhintRule { this.reporter.error( node, this.ruleId, - `System file must contain a contract with a matching name "${expectedContractName}"` + `System file must contain a contract with a matching name "${expectedContractName}"`, ); } } diff --git a/packages/store-indexer/CHANGELOG.md b/packages/store-indexer/CHANGELOG.md index 10ee41a923..f5b485fae7 100644 --- a/packages/store-indexer/CHANGELOG.md +++ b/packages/store-indexer/CHANGELOG.md @@ -594,7 +594,7 @@ .pipe( map((block) => Number(block.timestamp) * 1000), // Map to timestamp in ms filter((blockTimestamp) => blockTimestamp !== clock.lastUpdateTime), // Ignore if the clock was already refreshed with this block - filter((blockTimestamp) => blockTimestamp !== clock.currentTime) // Ignore if the current local timestamp is correct + filter((blockTimestamp) => blockTimestamp !== clock.currentTime), // Ignore if the current local timestamp is correct ) .subscribe(clock.update); // Update the local clock ``` diff --git a/packages/store-indexer/bin/parseEnv.ts b/packages/store-indexer/bin/parseEnv.ts index 19be86cf8f..5a001a61a3 100644 --- a/packages/store-indexer/bin/parseEnv.ts +++ b/packages/store-indexer/bin/parseEnv.ts @@ -23,7 +23,7 @@ export const indexerEnvSchema = z.intersection( RPC_HTTP_URL: z.string().optional(), RPC_WS_URL: z.string(), }), - ]) + ]), ); export function parseEnv(envSchema: TSchema): z.infer { diff --git a/packages/store-indexer/bin/postgres-decoded-indexer.ts b/packages/store-indexer/bin/postgres-decoded-indexer.ts index 11339892ea..70bce8a446 100644 --- a/packages/store-indexer/bin/postgres-decoded-indexer.ts +++ b/packages/store-indexer/bin/postgres-decoded-indexer.ts @@ -22,8 +22,8 @@ const env = parseEnv( HEALTHCHECK_HOST: z.string().optional(), HEALTHCHECK_PORT: z.coerce.number().optional(), SENTRY_DSN: z.string().optional(), - }) - ) + }), + ), ); const transports: Transport[] = [ @@ -81,9 +81,10 @@ let isCaughtUp = false; combineLatest([latestBlockNumber$, storedBlockLogs$]) .pipe( filter( - ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => latestBlockNumber === lastBlockNumberProcessed + ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => + latestBlockNumber === lastBlockNumberProcessed, ), - first() + first(), ) .subscribe(() => { isCaughtUp = true; @@ -104,12 +105,12 @@ if (env.HEALTHCHECK_HOST != null || env.HEALTHCHECK_PORT != null) { server.use( healthcheck({ isReady: () => isCaughtUp, - }) + }), ); server.use(helloWorld()); server.listen({ host: env.HEALTHCHECK_HOST, port: env.HEALTHCHECK_PORT }); console.log( - `postgres indexer healthcheck server listening on http://${env.HEALTHCHECK_HOST}:${env.HEALTHCHECK_PORT}` + `postgres indexer healthcheck server listening on http://${env.HEALTHCHECK_HOST}:${env.HEALTHCHECK_PORT}`, ); } diff --git a/packages/store-indexer/bin/postgres-frontend.ts b/packages/store-indexer/bin/postgres-frontend.ts index 037a53cddf..f95d80919c 100644 --- a/packages/store-indexer/bin/postgres-frontend.ts +++ b/packages/store-indexer/bin/postgres-frontend.ts @@ -20,8 +20,8 @@ const env = parseEnv( z.object({ DATABASE_URL: z.string(), SENTRY_DSN: z.string().optional(), - }) - ) + }), + ), ); const database = postgres(env.DATABASE_URL, { prepare: false }); @@ -44,7 +44,7 @@ server.use( createContext: async () => ({ queryAdapter: await createQueryAdapter(drizzle(database)), }), - }) + }), ); server.listen({ host: env.HOST, port: env.PORT }); diff --git a/packages/store-indexer/bin/postgres-indexer.ts b/packages/store-indexer/bin/postgres-indexer.ts index 3bcffa9803..28b0ee2482 100644 --- a/packages/store-indexer/bin/postgres-indexer.ts +++ b/packages/store-indexer/bin/postgres-indexer.ts @@ -18,8 +18,8 @@ const env = parseEnv( DATABASE_URL: z.string(), HEALTHCHECK_HOST: z.string().optional(), HEALTHCHECK_PORT: z.coerce.number().optional(), - }) - ) + }), + ), ); const transports: Transport[] = [ @@ -82,9 +82,10 @@ let isCaughtUp = false; combineLatest([latestBlockNumber$, storedBlockLogs$]) .pipe( filter( - ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => latestBlockNumber === lastBlockNumberProcessed + ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => + latestBlockNumber === lastBlockNumberProcessed, ), - first() + first(), ) .subscribe(() => { isCaughtUp = true; @@ -103,12 +104,12 @@ if (env.HEALTHCHECK_HOST != null || env.HEALTHCHECK_PORT != null) { server.use( healthcheck({ isReady: () => isCaughtUp, - }) + }), ); server.use(helloWorld()); server.listen({ host: env.HEALTHCHECK_HOST, port: env.HEALTHCHECK_PORT }); console.log( - `postgres indexer healthcheck server listening on http://${env.HEALTHCHECK_HOST}:${env.HEALTHCHECK_PORT}` + `postgres indexer healthcheck server listening on http://${env.HEALTHCHECK_HOST}:${env.HEALTHCHECK_PORT}`, ); } diff --git a/packages/store-indexer/bin/sqlite-indexer.ts b/packages/store-indexer/bin/sqlite-indexer.ts index 416dc8d8ef..a544fea7d6 100644 --- a/packages/store-indexer/bin/sqlite-indexer.ts +++ b/packages/store-indexer/bin/sqlite-indexer.ts @@ -26,8 +26,8 @@ const env = parseEnv( z.object({ SQLITE_FILENAME: z.string().default("indexer.db"), SENTRY_DSN: z.string().optional(), - }) - ) + }), + ), ); const transports: Transport[] = [ @@ -60,7 +60,7 @@ try { currentChainState.schemaVersion, "to", schemaVersion, - "recreating database" + "recreating database", ); fs.truncateSync(env.SQLITE_FILENAME); } else if (currentChainState.lastUpdatedBlockNumber != null) { @@ -85,9 +85,10 @@ let isCaughtUp = false; combineLatest([latestBlockNumber$, storedBlockLogs$]) .pipe( filter( - ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => latestBlockNumber === lastBlockNumberProcessed + ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) => + latestBlockNumber === lastBlockNumberProcessed, ), - first() + first(), ) .subscribe(() => { isCaughtUp = true; @@ -104,7 +105,7 @@ server.use(cors()); server.use( healthcheck({ isReady: () => isCaughtUp, - }) + }), ); server.use(helloWorld()); server.use(apiRoutes(database)); @@ -116,7 +117,7 @@ server.use( createContext: async () => ({ queryAdapter: await createQueryAdapter(database), }), - }) + }), ); server.listen({ host: env.HOST, port: env.PORT }); diff --git a/packages/store-indexer/src/koa-middleware/sentry.ts b/packages/store-indexer/src/koa-middleware/sentry.ts index ea59ea7492..e8999dffcd 100644 --- a/packages/store-indexer/src/koa-middleware/sentry.ts +++ b/packages/store-indexer/src/koa-middleware/sentry.ts @@ -31,8 +31,8 @@ export function requestHandler(): Koa.Middleware { include: { user: false, }, - }) - ) + }), + ), ); await next(); }); diff --git a/packages/store-indexer/src/postgres/apiRoutes.ts b/packages/store-indexer/src/postgres/apiRoutes.ts index 383700fc5f..66f5d63397 100644 --- a/packages/store-indexer/src/postgres/apiRoutes.ts +++ b/packages/store-indexer/src/postgres/apiRoutes.ts @@ -38,8 +38,8 @@ export function apiRoutes(database: Sql): Middleware { ctx.body = "no logs found"; error( `no logs found for chainId ${options.chainId}, address ${options.address}, filters ${JSON.stringify( - options.filters - )}` + options.filters, + )}`, ); return; } diff --git a/packages/store-indexer/src/postgres/deprecated/getLogs.ts b/packages/store-indexer/src/postgres/deprecated/getLogs.ts index e6138fef2e..a883e9b011 100644 --- a/packages/store-indexer/src/postgres/deprecated/getLogs.ts +++ b/packages/store-indexer/src/postgres/deprecated/getLogs.ts @@ -20,7 +20,7 @@ export async function getLogs( readonly chainId: number; readonly address?: Hex; readonly filters?: readonly SyncFilter[]; - } + }, ): Promise<{ blockNumber: bigint; logs: (StorageAdapterLog & { eventName: "Store_SetRecord" })[] }> { const benchmark = createBenchmark("drizzleGetLogs"); @@ -30,12 +30,12 @@ export async function getLogs( address != null ? eq(tables.recordsTable.address, address) : undefined, eq(tables.recordsTable.tableId, filter.tableId), filter.key0 != null ? eq(tables.recordsTable.key0, filter.key0) : undefined, - filter.key1 != null ? eq(tables.recordsTable.key1, filter.key1) : undefined - ) + filter.key1 != null ? eq(tables.recordsTable.key1, filter.key1) : undefined, + ), ) : address != null - ? [eq(tables.recordsTable.address, address)] - : []; + ? [eq(tables.recordsTable.address, address)] + : []; benchmark("parse config"); // Query for the block number that the indexer (i.e. chain) is at, in case the @@ -63,7 +63,7 @@ export async function getLogs( .from(tables.recordsTable) .where(or(...conditions)) .orderBy( - asc(tables.recordsTable.blockNumber) + asc(tables.recordsTable.blockNumber), // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979) ); benchmark("query records"); diff --git a/packages/store-indexer/src/postgres/queryLogs.ts b/packages/store-indexer/src/postgres/queryLogs.ts index b887a7a026..037f3bdc7b 100644 --- a/packages/store-indexer/src/postgres/queryLogs.ts +++ b/packages/store-indexer/src/postgres/queryLogs.ts @@ -26,16 +26,16 @@ export function queryLogs(sql: Sql, opts: z.infer): PendingQuery hex columns via custom types: https://github.com/porsager/postgres#custom-types diff --git a/packages/store-indexer/src/postgres/recordToLog.ts b/packages/store-indexer/src/postgres/recordToLog.ts index 097a7657f7..b74ec281d3 100644 --- a/packages/store-indexer/src/postgres/recordToLog.ts +++ b/packages/store-indexer/src/postgres/recordToLog.ts @@ -3,7 +3,7 @@ import { decodeDynamicField } from "@latticexyz/protocol-parser"; import { RecordData } from "./common"; export function recordToLog( - record: Omit + record: Omit, ): StorageAdapterLog & { eventName: "Store_SetRecord" } { return { address: record.address, diff --git a/packages/store-indexer/src/sqlite/getTablesWithRecords.ts b/packages/store-indexer/src/sqlite/getTablesWithRecords.ts index 987de4e641..10093c99ef 100644 --- a/packages/store-indexer/src/sqlite/getTablesWithRecords.ts +++ b/packages/store-indexer/src/sqlite/getTablesWithRecords.ts @@ -20,7 +20,7 @@ export function getTablesWithRecords( readonly chainId: number; readonly address?: Hex; readonly filters?: readonly SyncFilter[]; - } + }, ): { blockNumber: bigint | null; tables: readonly TableWithRecords[] } { const metadata = database .select() @@ -44,7 +44,7 @@ export function getTablesWithRecords( .from(sqliteTable) .where(eq(sqliteTable.__isDeleted, false)) .orderBy( - asc(sqliteTable.__lastUpdatedBlockNumber) + asc(sqliteTable.__lastUpdatedBlockNumber), // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979) ) .all(); @@ -56,7 +56,7 @@ export function getTablesWithRecords( (filter) => filter.tableId === table.tableId && (filter.key0 == null || filter.key0 === keyTuple[0]) && - (filter.key1 == null || filter.key1 === keyTuple[1]) + (filter.key1 == null || filter.key1 === keyTuple[1]), ); }); return { diff --git a/packages/store-sync/src/common.ts b/packages/store-sync/src/common.ts index 05aad07606..f0d05866e1 100644 --- a/packages/store-sync/src/common.ts +++ b/packages/store-sync/src/common.ts @@ -13,7 +13,7 @@ export const storeTables = resolveConfig(storeConfig).tables; export const worldTables = resolveConfig(worldConfig).tables; export const internalTableIds = [...Object.values(storeTables), ...Object.values(worldTables)].map( - (table) => table.tableId + (table) => table.tableId, ); export type ChainId = number; diff --git a/packages/store-sync/src/createStoreSync.ts b/packages/store-sync/src/createStoreSync.ts index 6b0fe1a628..ae2cf619be 100644 --- a/packages/store-sync/src/createStoreSync.ts +++ b/packages/store-sync/src/createStoreSync.ts @@ -73,7 +73,7 @@ export async function createStoreSync (filter) => filter.tableId === log.args.tableId && (filter.key0 == null || filter.key0 === log.args.keyTuple[0]) && - (filter.key1 == null || filter.key1 === log.args.keyTuple[1]) + (filter.key1 == null || filter.key1 === log.args.keyTuple[1]), ) : undefined; @@ -120,7 +120,7 @@ export async function createStoreSync return of(undefined); }), - shareReplay(1) + shareReplay(1), ); const storedInitialBlockLogs$ = initialBlockLogs$.pipe( @@ -168,13 +168,13 @@ export async function createStoreSync return { blockNumber, logs }; }), - shareReplay(1) + shareReplay(1), ); const startBlock$ = initialBlockLogs$.pipe( map((block) => bigIntMax(block?.blockNumber ?? 0n, initialStartBlock)), // TODO: if start block is still 0, find via deploy event - tap((startBlock) => debug("starting sync from block", startBlock)) + tap((startBlock) => debug("starting sync from block", startBlock)), ); const latestBlock$ = createBlockStream({ publicClient, blockTag: followBlockTag }).pipe(shareReplay(1)); @@ -183,7 +183,7 @@ export async function createStoreSync tap((blockNumber) => { debug("on block number", blockNumber, "for", followBlockTag, "block tag"); }), - shareReplay(1) + shareReplay(1), ); let startBlock: bigint | null = null; @@ -238,7 +238,7 @@ export async function createStoreSync } } }), - share() + share(), ); const storedBlockLogs$ = concat(storedInitialBlockLogs$, storedBlock$).pipe(share()); @@ -249,10 +249,10 @@ export async function createStoreSync const recentBlocks$ = storedBlockLogs$.pipe( scan( (recentBlocks, block) => [block, ...recentBlocks].slice(0, recentBlocksWindow), - [] + [], ), filter((recentBlocks) => recentBlocks.length > 0), - shareReplay(1) + shareReplay(1), ); // TODO: move to its own file so we can test it, have its own debug instance, etc. @@ -278,7 +278,7 @@ export async function createStoreSync throw error; } }), - tap((result) => debug("has tx?", tx, result)) + tap((result) => debug("has tx?", tx, result)), ); await firstValueFrom(hasTransaction$.pipe(filter(identity))); diff --git a/packages/store-sync/src/flattenSchema.ts b/packages/store-sync/src/flattenSchema.ts index 7cc9a92d90..dd2a61d019 100644 --- a/packages/store-sync/src/flattenSchema.ts +++ b/packages/store-sync/src/flattenSchema.ts @@ -2,7 +2,7 @@ import { mapObject } from "@latticexyz/common/utils"; import { ValueSchema } from "@latticexyz/store"; export function flattenSchema( - schema: schema + schema: schema, ): { readonly [k in keyof schema]: schema[k]["type"] } { return mapObject(schema, (value) => value.type); } diff --git a/packages/store-sync/src/getSnapshot.ts b/packages/store-sync/src/getSnapshot.ts index c79f2df255..f78d6e8cf0 100644 --- a/packages/store-sync/src/getSnapshot.ts +++ b/packages/store-sync/src/getSnapshot.ts @@ -63,7 +63,7 @@ export async function getSnapshot({ const result = await trpcIndexer.findAll.query({ chainId, address, filters }); // warn after we fetch from old endpoint so we know that the indexer is accessible console.warn( - `The indexer at ${indexerUrl} appears to be outdated. Consider upgrading to a recent version for better performance.` + `The indexer at ${indexerUrl} appears to be outdated. Consider upgrading to a recent version for better performance.`, ); // if the indexer returns no block number, it hasn't indexed this chain diff --git a/packages/store-sync/src/indexer-client/input.ts b/packages/store-sync/src/indexer-client/input.ts index 14107f1faa..643c88bf11 100644 --- a/packages/store-sync/src/indexer-client/input.ts +++ b/packages/store-sync/src/indexer-client/input.ts @@ -10,7 +10,7 @@ export const input = z.object({ tableId: z.string().refine(isHex), key0: z.string().refine(isHex).optional(), key1: z.string().refine(isHex).optional(), - }) + }), ) .default([]), }); diff --git a/packages/store-sync/src/isTableRegistrationLog.ts b/packages/store-sync/src/isTableRegistrationLog.ts index 8f6b6148d6..e7f9ac6acf 100644 --- a/packages/store-sync/src/isTableRegistrationLog.ts +++ b/packages/store-sync/src/isTableRegistrationLog.ts @@ -4,7 +4,7 @@ import { StorageAdapterLog, storeTables } from "./common"; * @internal */ export function isTableRegistrationLog( - log: StorageAdapterLog + log: StorageAdapterLog, ): log is StorageAdapterLog & { eventName: "Store_SetRecord" } { return log.eventName === "Store_SetRecord" && log.args.tableId === storeTables.Tables.tableId; } diff --git a/packages/store-sync/src/logToTable.test.ts b/packages/store-sync/src/logToTable.test.ts index f50e813bb5..0feb33c786 100644 --- a/packages/store-sync/src/logToTable.test.ts +++ b/packages/store-sync/src/logToTable.test.ts @@ -18,7 +18,7 @@ describe("logToTable", () => { // eslint-disable-next-line max-len "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000077461626c654964000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000b6669656c644c61796f757400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000096b6579536368656d610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b76616c7565536368656d610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012616269456e636f6465644b65794e616d657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000014616269456e636f6465644669656c644e616d6573000000000000000000000000", }, - }) + }), ).toMatchInlineSnapshot(` { "address": "0x3Aa5ebB10DC797CAC828524e59A333d0A371443c", diff --git a/packages/store-sync/src/logToTable.ts b/packages/store-sync/src/logToTable.ts index 0d50dce3aa..c69e616186 100644 --- a/packages/store-sync/src/logToTable.ts +++ b/packages/store-sync/src/logToTable.ts @@ -17,7 +17,7 @@ export function logToTable(log: StorageAdapterLog & { eventName: "Store_SetRecor const value = decodeValue( // TODO: remove cast when we have strong types for user types schemasTable.valueSchema as ValueSchema, - concatHex([log.args.staticData, log.args.encodedLengths, log.args.dynamicData]) + concatHex([log.args.staticData, log.args.encodedLengths, log.args.dynamicData]), ); // TODO: remove cast when we have strong types for user types diff --git a/packages/store-sync/src/postgres-decoded/buildTable.test.ts b/packages/store-sync/src/postgres-decoded/buildTable.test.ts index f20f846392..b6369772f5 100644 --- a/packages/store-sync/src/postgres-decoded/buildTable.test.ts +++ b/packages/store-sync/src/postgres-decoded/buildTable.test.ts @@ -22,7 +22,7 @@ describe("buildTable", () => { dataType: column.dataType, sqlName: column.sqlName, notNull: column.notNull, - })) + })), ).toMatchInlineSnapshot(` { "__keyBytes": { @@ -81,7 +81,7 @@ describe("buildTable", () => { name: column.name, dataType: column.dataType, sqlName: column.sqlName, - })) + })), ).toMatchInlineSnapshot(` { "__keyBytes": { diff --git a/packages/store-sync/src/postgres-decoded/buildTable.ts b/packages/store-sync/src/postgres-decoded/buildTable.ts index 2f0a6f336c..56797a8438 100644 --- a/packages/store-sync/src/postgres-decoded/buildTable.ts +++ b/packages/store-sync/src/postgres-decoded/buildTable.ts @@ -56,10 +56,10 @@ export function buildTable [name, buildColumn(snakeCase(name), type).notNull()]) + Object.entries(keySchema).map(([name, type]) => [name, buildColumn(snakeCase(name), type).notNull()]), ); const valueColumns = Object.fromEntries( - Object.entries(valueSchema).map(([name, type]) => [name, buildColumn(snakeCase(name), type).notNull()]) + Object.entries(valueSchema).map(([name, type]) => [name, buildColumn(snakeCase(name), type).notNull()]), ); // TODO: make sure there are no meta columns that overlap with key/value columns diff --git a/packages/store-sync/src/postgres-decoded/createStorageAdapter.test.ts b/packages/store-sync/src/postgres-decoded/createStorageAdapter.test.ts index cf692f02a8..cb213fb258 100644 --- a/packages/store-sync/src/postgres-decoded/createStorageAdapter.test.ts +++ b/packages/store-sync/src/postgres-decoded/createStorageAdapter.test.ts @@ -22,7 +22,7 @@ const blocks = groupLogsByBlockNumber( strict: true, }); return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); describe("createStorageAdapter", async () => { @@ -64,9 +64,9 @@ describe("createStorageAdapter", async () => { .where( eq( storageAdapter.tables.recordsTable.tableId, - resourceToHex({ type: "table", namespace: "", name: "NumberList" }) - ) - ) + resourceToHex({ type: "table", namespace: "", name: "NumberList" }), + ), + ), ).toMatchInlineSnapshot(` [ { diff --git a/packages/store-sync/src/postgres-decoded/createStorageAdapter.ts b/packages/store-sync/src/postgres-decoded/createStorageAdapter.ts index 227c0f39aa..d14401ef89 100644 --- a/packages/store-sync/src/postgres-decoded/createStorageAdapter.ts +++ b/packages/store-sync/src/postgres-decoded/createStorageAdapter.ts @@ -44,7 +44,7 @@ export async function createStorageAdapter ({ address: log.address, tableId: log.args.tableId })) + logs.map((log) => ({ address: log.address, tableId: log.args.tableId })), ); // TODO: check if DB schema/table was created? @@ -56,7 +56,7 @@ export async function createStorageAdapter { for (const log of logs) { const table = tables.find( - (table) => getAddress(table.address) === getAddress(log.address) && table.tableId === log.args.tableId + (table) => getAddress(table.address) === getAddress(log.address) && table.tableId === log.args.tableId, ); if (!table) { const { namespace, name } = hexToResource(log.args.tableId); @@ -80,8 +80,8 @@ export async function createStorageAdapter, - filters: { address: Hex | null; tableId: Hex | null }[] = [] + filters: { address: Hex | null; tableId: Hex | null }[] = [], ): Promise { const conditions = filters.map((filter) => and( filter.address != null ? eq(internalTables.recordsTable.address, filter.address) : undefined, - filter.tableId != null ? eq(internalTables.recordsTable.key0, filter.tableId) : undefined - ) + filter.tableId != null ? eq(internalTables.recordsTable.key0, filter.tableId) : undefined, + ), ); const records = await db @@ -34,7 +34,7 @@ export async function getTables( encodedLengths: record.encodedLengths ?? "0x", dynamicData: record.dynamicData ?? "0x", }, - } as const) + }) as const, ); const tables = logs.map(logToTable); diff --git a/packages/store-sync/src/postgres/createStorageAdapter.test.ts b/packages/store-sync/src/postgres/createStorageAdapter.test.ts index c05928640f..bd368633b0 100644 --- a/packages/store-sync/src/postgres/createStorageAdapter.test.ts +++ b/packages/store-sync/src/postgres/createStorageAdapter.test.ts @@ -20,7 +20,7 @@ const blocks = groupLogsByBlockNumber( strict: true, }); return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); describe("createStorageAdapter", async () => { @@ -62,9 +62,9 @@ describe("createStorageAdapter", async () => { .where( eq( storageAdapter.tables.recordsTable.tableId, - resourceToHex({ type: "table", namespace: "", name: "NumberList" }) - ) - ) + resourceToHex({ type: "table", namespace: "", name: "NumberList" }), + ), + ), ).toMatchInlineSnapshot(` [ { diff --git a/packages/store-sync/src/postgres/createStorageAdapter.ts b/packages/store-sync/src/postgres/createStorageAdapter.ts index 43578e9ad9..91cfe6f225 100644 --- a/packages/store-sync/src/postgres/createStorageAdapter.ts +++ b/packages/store-sync/src/postgres/createStorageAdapter.ts @@ -80,8 +80,8 @@ export async function createStorageAdapter, - tables: PgTableWithColumns[] + tables: PgTableWithColumns[], ): Promise<() => Promise> { const schemaNames = unique(tables.map((table) => getTableConfig(table).schema).filter(isDefined)); @@ -49,7 +49,7 @@ export async function setupTables( if (primaryKeyColumns.length) { query = query.addPrimaryKeyConstraint( `${tableConfig.name}_${primaryKeyColumns.join("_")}_pk`, - primaryKeyColumns as any + primaryKeyColumns as any, ); } diff --git a/packages/store-sync/src/postgres/tables.ts b/packages/store-sync/src/postgres/tables.ts index b8871327d3..2f00011976 100644 --- a/packages/store-sync/src/postgres/tables.ts +++ b/packages/store-sync/src/postgres/tables.ts @@ -37,7 +37,7 @@ const recordsTable = pgSchema(schemaName).table( key1Index: index("key1_index").on(table.address, table.tableId, table.key1), // TODO: add indices for querying without table ID // TODO: add indices for querying multiple keys - }) + }), ); export const tables = { diff --git a/packages/store-sync/src/recs/decodeEntity.ts b/packages/store-sync/src/recs/decodeEntity.ts index ba2c084a7f..d4210de20b 100644 --- a/packages/store-sync/src/recs/decodeEntity.ts +++ b/packages/store-sync/src/recs/decodeEntity.ts @@ -5,18 +5,18 @@ import { KeySchema, SchemaToPrimitives } from "@latticexyz/protocol-parser"; export function decodeEntity( keySchema: TKeySchema, - entity: Entity + entity: Entity, ): SchemaToPrimitives { const hexKeyTuple = entityToHexKeyTuple(entity); if (hexKeyTuple.length !== Object.keys(keySchema).length) { throw new Error( - `entity key tuple length ${hexKeyTuple.length} does not match key schema length ${Object.keys(keySchema).length}` + `entity key tuple length ${hexKeyTuple.length} does not match key schema length ${Object.keys(keySchema).length}`, ); } return Object.fromEntries( Object.entries(keySchema).map(([key, type], index) => [ key, decodeAbiParameters([{ type }], hexKeyTuple[index] as Hex)[0], - ]) + ]), ) as SchemaToPrimitives; } diff --git a/packages/store-sync/src/recs/defineInternalComponents.ts b/packages/store-sync/src/recs/defineInternalComponents.ts index 992b878ce4..5b974cbd65 100644 --- a/packages/store-sync/src/recs/defineInternalComponents.ts +++ b/packages/store-sync/src/recs/defineInternalComponents.ts @@ -7,7 +7,7 @@ export function defineInternalComponents(world: World) { RegisteredTables: defineComponent<{ table: Type.T }, Metadata, Table>( world, { table: Type.T }, - { metadata: { componentName: "RegisteredTables" } } + { metadata: { componentName: "RegisteredTables" } }, ), SyncProgress: defineComponent( world, @@ -18,7 +18,7 @@ export function defineInternalComponents(world: World) { latestBlockNumber: Type.BigInt, lastBlockNumberProcessed: Type.BigInt, }, - { metadata: { componentName: "SyncProgress" } } + { metadata: { componentName: "SyncProgress" } }, ), } as const satisfies Record>; } diff --git a/packages/store-sync/src/recs/encodeEntity.ts b/packages/store-sync/src/recs/encodeEntity.ts index bef8a33c1b..061a630dee 100644 --- a/packages/store-sync/src/recs/encodeEntity.ts +++ b/packages/store-sync/src/recs/encodeEntity.ts @@ -5,14 +5,14 @@ import { KeySchema, SchemaToPrimitives } from "@latticexyz/protocol-parser"; export function encodeEntity( keySchema: TKeySchema, - key: SchemaToPrimitives + key: SchemaToPrimitives, ): Entity { if (Object.keys(keySchema).length !== Object.keys(key).length) { throw new Error( - `key length ${Object.keys(key).length} does not match key schema length ${Object.keys(keySchema).length}` + `key length ${Object.keys(key).length} does not match key schema length ${Object.keys(keySchema).length}`, ); } return hexKeyTupleToEntity( - Object.entries(keySchema).map(([keyName, type]) => encodeAbiParameters([{ type }], [key[keyName]])) + Object.entries(keySchema).map(([keyName, type]) => encodeAbiParameters([{ type }], [key[keyName]])), ); } diff --git a/packages/store-sync/src/recs/getTableEntity.ts b/packages/store-sync/src/recs/getTableEntity.ts index 5b92368da3..52ae66b6e3 100644 --- a/packages/store-sync/src/recs/getTableEntity.ts +++ b/packages/store-sync/src/recs/getTableEntity.ts @@ -10,6 +10,6 @@ export function getTableEntity(table: Pick( - component: Component + component: Component, ): component is Component { return ( component.metadata?.componentName != null && diff --git a/packages/store-sync/src/recs/recsStorage.test.ts b/packages/store-sync/src/recs/recsStorage.test.ts index afead84f6b..a1e5217cbe 100644 --- a/packages/store-sync/src/recs/recsStorage.test.ts +++ b/packages/store-sync/src/recs/recsStorage.test.ts @@ -21,7 +21,7 @@ const blocks = groupLogsByBlockNumber( strict: true, }); return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); describe("recsStorage", () => { @@ -29,7 +29,7 @@ describe("recsStorage", () => { const world = createWorld(); const { components } = recsStorage({ world, tables }); expect(components.NumberList.id).toMatchInlineSnapshot( - '"0x746200000000000000000000000000004e756d6265724c697374000000000000"' + '"0x746200000000000000000000000000004e756d6265724c697374000000000000"', ); }); @@ -60,7 +60,9 @@ describe("recsStorage", () => { `); expect( - [...getComponentEntities(components.NumberList)].map((entity) => getComponentValue(components.NumberList, entity)) + [...getComponentEntities(components.NumberList)].map((entity) => + getComponentValue(components.NumberList, entity), + ), ).toMatchInlineSnapshot(` [ { diff --git a/packages/store-sync/src/recs/recsStorage.ts b/packages/store-sync/src/recs/recsStorage.ts index 85a956c402..36849aa6f2 100644 --- a/packages/store-sync/src/recs/recsStorage.ts +++ b/packages/store-sync/src/recs/recsStorage.ts @@ -60,7 +60,7 @@ export function recsStorage>({ components.RegisteredTables, tableEntity, { table: newTable }, - { skipUpdateStream: shouldSkipUpdateStream?.() } + { skipUpdateStream: shouldSkipUpdateStream?.() }, ); } } @@ -69,7 +69,7 @@ export function recsStorage>({ const { namespace, name } = hexToResource(log.args.tableId); const table = getComponentValue( components.RegisteredTables, - getTableEntity({ address: log.address, namespace, name }) + getTableEntity({ address: log.address, namespace, name }), )?.table; if (!table) { debug(`skipping update for unknown table: ${resourceToLabel({ namespace, name })} at ${log.address}`); @@ -82,7 +82,7 @@ export function recsStorage>({ `skipping update for unknown component: ${table.tableId} (${resourceToLabel({ namespace, name, - })}). Available components: ${Object.keys(components)}` + })}). Available components: ${Object.keys(components)}`, ); continue; } @@ -106,7 +106,7 @@ export function recsStorage>({ __encodedLengths: log.args.encodedLengths, __dynamicData: log.args.dynamicData, }, - { skipUpdateStream: shouldSkipUpdateStream?.() } + { skipUpdateStream: shouldSkipUpdateStream?.() }, ); } else if (log.eventName === "Store_SpliceStaticData") { // TODO: add tests that this works when no record had been set before @@ -134,7 +134,7 @@ export function recsStorage>({ ...newValue, __staticData: newStaticData, }, - { skipUpdateStream: shouldSkipUpdateStream?.() } + { skipUpdateStream: shouldSkipUpdateStream?.() }, ); } else if (log.eventName === "Store_SpliceDynamicData") { // TODO: add tests that this works when no record had been set before @@ -164,7 +164,7 @@ export function recsStorage>({ __encodedLengths: log.args.encodedLengths, __dynamicData: newDynamicData, }, - { skipUpdateStream: shouldSkipUpdateStream?.() } + { skipUpdateStream: shouldSkipUpdateStream?.() }, ); } else if (log.eventName === "Store_DeleteRecord") { debug("deleting component", { diff --git a/packages/store-sync/src/recs/tableToComponent.ts b/packages/store-sync/src/recs/tableToComponent.ts index cfd07a9107..588163b6f1 100644 --- a/packages/store-sync/src/recs/tableToComponent.ts +++ b/packages/store-sync/src/recs/tableToComponent.ts @@ -31,7 +31,7 @@ export function tableToComponent
(world: World, table: table Object.entries(table.valueSchema).map(([fieldName, { type: schemaAbiType }]) => [ fieldName, schemaAbiTypeToRecsType[schemaAbiType as SchemaAbiType], - ]) + ]), ), __staticData: Type.OptionalString, __encodedLengths: Type.OptionalString, @@ -45,6 +45,6 @@ export function tableToComponent
(world: World, table: table keySchema: mapObject(table.keySchema, ({ type }) => type), valueSchema: mapObject(table.valueSchema, ({ type }) => type), }, - } + }, ) as TableToComponent
; } diff --git a/packages/store-sync/src/recs/tablesToComponents.ts b/packages/store-sync/src/recs/tablesToComponents.ts index be1a2cde4e..5952f6aa7a 100644 --- a/packages/store-sync/src/recs/tablesToComponents.ts +++ b/packages/store-sync/src/recs/tablesToComponents.ts @@ -9,7 +9,7 @@ export type TablesToComponents> = { export function tablesToComponents>( world: World, - tables: tables + tables: tables, ): TablesToComponents { return mapObject(tables, (table) => tableToComponent(world, table)); } diff --git a/packages/store-sync/src/schemaToDefaults.ts b/packages/store-sync/src/schemaToDefaults.ts index 278b4c77c7..f7658c15e0 100644 --- a/packages/store-sync/src/schemaToDefaults.ts +++ b/packages/store-sync/src/schemaToDefaults.ts @@ -3,6 +3,6 @@ import { schemaAbiTypeToDefaultValue } from "@latticexyz/schema-type"; export function schemaToDefaults(valueSchema: TSchema): SchemaToPrimitives { return Object.fromEntries( - Object.entries(valueSchema).map(([key, abiType]) => [key, schemaAbiTypeToDefaultValue[abiType]]) + Object.entries(valueSchema).map(([key, abiType]) => [key, schemaAbiTypeToDefaultValue[abiType]]), ) as SchemaToPrimitives; } diff --git a/packages/store-sync/src/sqlite/buildTable.ts b/packages/store-sync/src/sqlite/buildTable.ts index 2b9b0efd5c..d37d77d8e7 100644 --- a/packages/store-sync/src/sqlite/buildTable.ts +++ b/packages/store-sync/src/sqlite/buildTable.ts @@ -53,11 +53,11 @@ export function buildTable [name, buildColumn(name, type).notNull()]) + Object.entries(keySchema).map(([name, type]) => [name, buildColumn(name, type).notNull()]), ); const valueColumns = Object.fromEntries( - Object.entries(valueSchema).map(([name, type]) => [name, buildColumn(name, type).notNull()]) + Object.entries(valueSchema).map(([name, type]) => [name, buildColumn(name, type).notNull()]), ); // TODO: unique constraint on key columns? diff --git a/packages/store-sync/src/sqlite/getTables.ts b/packages/store-sync/src/sqlite/getTables.ts index 008a772167..01f9e90aa9 100644 --- a/packages/store-sync/src/sqlite/getTables.ts +++ b/packages/store-sync/src/sqlite/getTables.ts @@ -6,17 +6,17 @@ import { mudStoreTables } from "./internalTables"; export function getTables( db: BaseSQLiteDatabase<"sync", void>, - conditions: Pick[] = [] + conditions: Pick[] = [], ): Table[] { const ids = Array.from( - new Set(conditions.map((condition) => getTableName(condition.address, condition.namespace, condition.name))) + new Set(conditions.map((condition) => getTableName(condition.address, condition.namespace, condition.name))), ); const tables = db .select() .from(mudStoreTables) .where(ids.length ? inArray(mudStoreTables.id, ids) : undefined) .orderBy( - asc(mudStoreTables.lastUpdatedBlockNumber) + asc(mudStoreTables.lastUpdatedBlockNumber), // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979) ) .all(); diff --git a/packages/store-sync/src/sqlite/sqliteStorage.test.ts b/packages/store-sync/src/sqlite/sqliteStorage.test.ts index c8afe6a3d5..ed21a8dc58 100644 --- a/packages/store-sync/src/sqlite/sqliteStorage.test.ts +++ b/packages/store-sync/src/sqlite/sqliteStorage.test.ts @@ -24,7 +24,7 @@ const blocks = groupLogsByBlockNumber( strict: true, }); return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); describe("sqliteStorage", async () => { @@ -44,10 +44,10 @@ describe("sqliteStorage", async () => { it("should create tables and data from block log", async () => { expect(() => db.select().from(chainState).all()).toThrowErrorMatchingInlineSnapshot( - '"no such table: __chainState"' + '"no such table: __chainState"', ); expect(() => db.select().from(mudStoreTables).all()).toThrowErrorMatchingInlineSnapshot( - '"no such table: __mudStoreTables"' + '"no such table: __mudStoreTables"', ); const storageAdapter = await sqliteStorage({ database: db, publicClient }); diff --git a/packages/store-sync/src/sqlite/sqliteStorage.ts b/packages/store-sync/src/sqlite/sqliteStorage.ts index 6c369ab3b2..b29cd660aa 100644 --- a/packages/store-sync/src/sqlite/sqliteStorage.ts +++ b/packages/store-sync/src/sqlite/sqliteStorage.ts @@ -62,10 +62,10 @@ export async function sqliteStorage({ JSON.stringify({ address: getAddress(log.address), ...hexToResource(log.args.tableId), - }) - ) - ) - ).map((json) => JSON.parse(json)) + }), + ), + ), + ).map((json) => JSON.parse(json)), ); await database.transaction(async (tx) => { @@ -76,21 +76,21 @@ export async function sqliteStorage({ and( eq(mudStoreTables.address, address), eq(mudStoreTables.namespace, namespace), - eq(mudStoreTables.name, name) - ) + eq(mudStoreTables.name, name), + ), ) .run(); } for (const log of logs) { const table = tables.find( - (table) => table.address === getAddress(log.address) && table.tableId === log.args.tableId + (table) => table.address === getAddress(log.address) && table.tableId === log.args.tableId, ); if (!table) { const tableId = hexToResource(log.args.tableId); debug( `table ${resourceToLabel({ namespace: tableId.namespace, name: tableId.name })} not found, skipping log`, - log + log, ); continue; } diff --git a/packages/store-sync/src/sqlite/sqliteTableToSql.test.ts b/packages/store-sync/src/sqlite/sqliteTableToSql.test.ts index c07270f84e..cad8a1ca39 100644 --- a/packages/store-sync/src/sqlite/sqliteTableToSql.test.ts +++ b/packages/store-sync/src/sqlite/sqliteTableToSql.test.ts @@ -16,7 +16,7 @@ describe("sqliteTableToSql", () => { expect(sql).toMatchInlineSnapshot( // eslint-disable-next-line max-len - '"create table if not exists \\"some table\\" (\\"x\\" integer not null, \\"y\\" integer not null, \\"name\\" text default \'\' not null, \\"block_number\\" blob default \'1000\' not null, constraint \\"some table__primaryKey\\" primary key (\\"x\\", \\"y\\"))"' + '"create table if not exists \\"some table\\" (\\"x\\" integer not null, \\"y\\" integer not null, \\"name\\" text default \'\' not null, \\"block_number\\" blob default \'1000\' not null, constraint \\"some table__primaryKey\\" primary key (\\"x\\", \\"y\\"))"', ); }); @@ -29,7 +29,7 @@ describe("sqliteTableToSql", () => { const sql = sqliteTableToSql(table); expect(sql).toMatchInlineSnapshot( - '"create table if not exists \\"some table\\" (\\"name\\" text default \'\' not null)"' + '"create table if not exists \\"some table\\" (\\"name\\" text default \'\' not null)"', ); }); @@ -42,7 +42,7 @@ describe("sqliteTableToSql", () => { const sql = sqliteTableToSql(table); expect(sql).toMatchInlineSnapshot( - '"create table if not exists \\"some table\\" (\\"snake_case\\" text default \'\' not null, constraint \\"some table__primaryKey\\" primary key (\\"snake_case\\"))"' + '"create table if not exists \\"some table\\" (\\"snake_case\\" text default \'\' not null, constraint \\"some table__primaryKey\\" primary key (\\"snake_case\\"))"', ); }); }); diff --git a/packages/store-sync/src/tableToLog.test.ts b/packages/store-sync/src/tableToLog.test.ts index 0b58c4c45a..ca1f9de5f5 100644 --- a/packages/store-sync/src/tableToLog.test.ts +++ b/packages/store-sync/src/tableToLog.test.ts @@ -14,7 +14,7 @@ describe("tableToLog", () => { name: storeTables.Tables.name, keySchema: flattenSchema(storeTables.Tables.keySchema), valueSchema: flattenSchema(storeTables.Tables.valueSchema), - }) + }), ).toMatchInlineSnapshot(` { "address": "0x3Aa5ebB10DC797CAC828524e59A333d0A371443c", diff --git a/packages/store-sync/src/tablesWithRecordsToLogs.ts b/packages/store-sync/src/tablesWithRecordsToLogs.ts index a7e35d5a89..afd37437e5 100644 --- a/packages/store-sync/src/tablesWithRecordsToLogs.ts +++ b/packages/store-sync/src/tablesWithRecordsToLogs.ts @@ -18,8 +18,8 @@ export function tablesWithRecordsToLogs(tables: readonly TableWithRecords[]): St keyTuple: encodeKey(table.keySchema, record.key), ...encodeValueArgs(table.valueSchema, record.value), }, - }) - ) + }), + ), ), ]; } diff --git a/packages/store-sync/src/zustand/createStorageAdapter.test.ts b/packages/store-sync/src/zustand/createStorageAdapter.test.ts index 76fa8fc707..cdc089d051 100644 --- a/packages/store-sync/src/zustand/createStorageAdapter.test.ts +++ b/packages/store-sync/src/zustand/createStorageAdapter.test.ts @@ -20,7 +20,7 @@ const blocks = groupLogsByBlockNumber( strict: true, }); return formatLog(log as unknown as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); describe("createStorageAdapter", () => { diff --git a/packages/store-sync/src/zustand/createStorageAdapter.ts b/packages/store-sync/src/zustand/createStorageAdapter.ts index 7dcb55f20c..b8bb5f6974 100644 --- a/packages/store-sync/src/zustand/createStorageAdapter.ts +++ b/packages/store-sync/src/zustand/createStorageAdapter.ts @@ -32,7 +32,7 @@ export function createStorageAdapter({ debug( `skipping update for unknown table: ${resourceToLabel({ namespace, name })} (${log.args.tableId}) at ${ log.address - }` + }`, ); continue; } @@ -140,7 +140,7 @@ export function createStorageAdapter({ }, ]; }) - .filter(isDefined) + .filter(isDefined), ), }; diff --git a/packages/store-sync/src/zustand/createStore.ts b/packages/store-sync/src/zustand/createStore.ts index 77642e3eaa..93a2dd3258 100644 --- a/packages/store-sync/src/zustand/createStore.ts +++ b/packages/store-sync/src/zustand/createStore.ts @@ -36,11 +36,11 @@ export type ZustandState = { readonly getRecords:
(table: table) => TableRecords
; readonly getRecord:
( table: table, - key: SchemaToPrimitives + key: SchemaToPrimitives, ) => TableRecord
| undefined; readonly getValue:
( table: table, - key: SchemaToPrimitives + key: SchemaToPrimitives, ) => TableRecord
["value"] | undefined; }; @@ -65,12 +65,12 @@ export function createStore(opts: CreateStoreOptions(table: table): TableRecords
=> { const records = get().records; return Object.fromEntries( - Object.entries(records).filter(([id, record]) => record.table.tableId === table.tableId) + Object.entries(records).filter(([id, record]) => record.table.tableId === table.tableId), ) as unknown as TableRecords
; }, getRecord:
( table: table, - key: SchemaToPrimitives + key: SchemaToPrimitives, ): TableRecord
| undefined => { const keyTuple = encodeKey(flattenSchema(table.keySchema), key); const id = getId({ tableId: table.tableId, keyTuple }); @@ -78,7 +78,7 @@ export function createStore(opts: CreateStoreOptions( table: table, - key: SchemaToPrimitives + key: SchemaToPrimitives, ): TableRecord
["value"] | undefined => { return get().getRecord(table, key)?.value; }, diff --git a/packages/store-sync/src/zustand/getId.test.ts b/packages/store-sync/src/zustand/getId.test.ts index e47b398a4e..2016d318a0 100644 --- a/packages/store-sync/src/zustand/getId.test.ts +++ b/packages/store-sync/src/zustand/getId.test.ts @@ -7,9 +7,9 @@ describe("getId", () => { getId({ tableId: "0x74626d756473746f72650000000000005461626c657300000000000000000000", keyTuple: ["0x74626d756473746f72650000000000005461626c657300000000000000000000"], - }) + }), ).toMatchInlineSnapshot( - '"0x74626d756473746f72650000000000005461626c657300000000000000000000:0x74626d756473746f72650000000000005461626c657300000000000000000000"' + '"0x74626d756473746f72650000000000005461626c657300000000000000000000:0x74626d756473746f72650000000000005461626c657300000000000000000000"', ); }); }); diff --git a/packages/store-sync/src/zustand/logToTable.test.ts b/packages/store-sync/src/zustand/logToTable.test.ts index 010d25b7ed..fbaf89cd0c 100644 --- a/packages/store-sync/src/zustand/logToTable.test.ts +++ b/packages/store-sync/src/zustand/logToTable.test.ts @@ -18,7 +18,7 @@ describe("logToTable", () => { // eslint-disable-next-line max-len "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000077461626c654964000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000b6669656c644c61796f757400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000096b6579536368656d610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b76616c7565536368656d610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012616269456e636f6465644b65794e616d657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000014616269456e636f6465644669656c644e616d6573000000000000000000000000", }, - }) + }), ).toMatchInlineSnapshot(` { "keySchema": { diff --git a/packages/store-sync/src/zustand/logToTable.ts b/packages/store-sync/src/zustand/logToTable.ts index 8d2b32e4e7..703f276704 100644 --- a/packages/store-sync/src/zustand/logToTable.ts +++ b/packages/store-sync/src/zustand/logToTable.ts @@ -14,7 +14,7 @@ export function logToTable(log: StorageAdapterLog & { eventName: "Store_SetRecor const value = decodeValue( schemasTable.valueSchema, - concatHex([log.args.staticData, log.args.encodedLengths, log.args.dynamicData]) + concatHex([log.args.staticData, log.args.encodedLengths, log.args.dynamicData]), ); const keySchema = hexToSchema(value.keySchema); diff --git a/packages/store-sync/src/zustand/syncToZustand.ts b/packages/store-sync/src/zustand/syncToZustand.ts index 850bb1c231..d5df3c0e80 100644 --- a/packages/store-sync/src/zustand/syncToZustand.ts +++ b/packages/store-sync/src/zustand/syncToZustand.ts @@ -9,7 +9,7 @@ import { SyncStep } from "../SyncStep"; type AllTables< config extends StoreConfig, - extraTables extends Tables | undefined + extraTables extends Tables | undefined, > = ResolvedStoreConfig["tables"] & (extraTables extends Tables ? extraTables : Record) & typeof storeTables & diff --git a/packages/store-sync/test/logsToBlocks.ts b/packages/store-sync/test/logsToBlocks.ts index e3ffb8a9ac..2c92392316 100644 --- a/packages/store-sync/test/logsToBlocks.ts +++ b/packages/store-sync/test/logsToBlocks.ts @@ -4,7 +4,7 @@ import { RpcLog, formatLog, decodeEventLog, Hex } from "viem"; import { StoreEventsLog } from "../src/common"; export function logsToBlocks( - rpcLogs: { data: string; topics: string[] }[] + rpcLogs: { data: string; topics: string[] }[], ): GroupLogsByBlockNumberResult { return groupLogsByBlockNumber( rpcLogs.map((log) => { @@ -15,6 +15,6 @@ export function logsToBlocks( strict: true, }); return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog; - }) + }), ); } diff --git a/packages/store/gas-report.json b/packages/store/gas-report.json index 83b8710dea..875198ffec 100644 --- a/packages/store/gas-report.json +++ b/packages/store/gas-report.json @@ -21,7 +21,7 @@ "file": "test/Callbacks.t.sol", "test": "testSetAndGet", "name": "Callbacks: get field (warm)", - "gasUsed": 2615 + "gasUsed": 2616 }, { "file": "test/Callbacks.t.sol", @@ -321,7 +321,7 @@ "file": "test/KeyEncoding.t.sol", "test": "testRegisterAndGetFieldLayout", "name": "register KeyEncoding table", - "gasUsed": 723941 + "gasUsed": 717787 }, { "file": "test/Mixed.t.sol", @@ -1107,7 +1107,7 @@ "file": "test/Vector2.t.sol", "test": "testRegisterAndGetFieldLayout", "name": "register Vector2 field layout", - "gasUsed": 447721 + "gasUsed": 443849 }, { "file": "test/Vector2.t.sol", diff --git a/packages/store/package.json b/packages/store/package.json index cef5a69075..81ee8a66ab 100644 --- a/packages/store/package.json +++ b/packages/store/package.json @@ -53,6 +53,7 @@ "dependencies": { "@latticexyz/common": "workspace:*", "@latticexyz/config": "workspace:*", + "@latticexyz/protocol-parser": "workspace:*", "@latticexyz/schema-type": "workspace:*", "abitype": "1.0.0", "viem": "2.7.12", diff --git a/packages/store/src/Bytes.sol b/packages/store/src/Bytes.sol index b727cabc09..63cfa8888d 100644 --- a/packages/store/src/Bytes.sol +++ b/packages/store/src/Bytes.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title Bytes + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Utility functions for bytes. */ library Bytes { diff --git a/packages/store/src/FieldLayout.sol b/packages/store/src/FieldLayout.sol index 6db7af9bd3..1cc3bb5154 100644 --- a/packages/store/src/FieldLayout.sol +++ b/packages/store/src/FieldLayout.sol @@ -2,9 +2,11 @@ pragma solidity >=0.8.24; import { WORD_SIZE, WORD_LAST_INDEX, BYTE_TO_BITS, MAX_TOTAL_FIELDS, MAX_DYNAMIC_FIELDS, LayoutOffsets } from "./constants.sol"; +import { IFieldLayoutErrors } from "./IFieldLayoutErrors.sol"; /** * @title FieldLayout + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Represents a field layout encoded into a single bytes32. * From left to right, the bytes are laid out as follows: * - 2 bytes for total length of all static fields @@ -20,19 +22,12 @@ using FieldLayoutInstance for FieldLayout global; /** * @title FieldLayoutLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A library for handling field layout encoding into a single bytes32. * It provides a function to encode static and dynamic fields and ensure * various constraints regarding the length and size of the fields. */ library FieldLayoutLib { - error FieldLayoutLib_TooManyFields(uint256 numFields, uint256 maxFields); - error FieldLayoutLib_TooManyDynamicFields(uint256 numFields, uint256 maxFields); - error FieldLayoutLib_Empty(); - error FieldLayoutLib_InvalidStaticDataLength(uint256 staticDataLength, uint256 computedStaticDataLength); - error FieldLayoutLib_StaticLengthIsZero(uint256 index); - error FieldLayoutLib_StaticLengthIsNotZero(uint256 index); - error FieldLayoutLib_StaticLengthDoesNotFitInAWord(uint256 index); - /** * @notice Encodes the given field layout into a single bytes32. * @dev Ensures various constraints on the length and size of the fields. @@ -45,17 +40,18 @@ library FieldLayoutLib { uint256 fieldLayout; uint256 totalLength; uint256 totalFields = _staticFieldLengths.length + numDynamicFields; - if (totalFields > MAX_TOTAL_FIELDS) revert FieldLayoutLib_TooManyFields(totalFields, MAX_TOTAL_FIELDS); + if (totalFields > MAX_TOTAL_FIELDS) + revert IFieldLayoutErrors.FieldLayout_TooManyFields(totalFields, MAX_TOTAL_FIELDS); if (numDynamicFields > MAX_DYNAMIC_FIELDS) - revert FieldLayoutLib_TooManyDynamicFields(numDynamicFields, MAX_DYNAMIC_FIELDS); + revert IFieldLayoutErrors.FieldLayout_TooManyDynamicFields(numDynamicFields, MAX_DYNAMIC_FIELDS); // Compute the total static length and store the field lengths in the encoded fieldLayout for (uint256 i; i < _staticFieldLengths.length; ) { uint256 staticByteLength = _staticFieldLengths[i]; if (staticByteLength == 0) { - revert FieldLayoutLib_StaticLengthIsZero(i); + revert IFieldLayoutErrors.FieldLayout_StaticLengthIsZero(i); } else if (staticByteLength > WORD_SIZE) { - revert FieldLayoutLib_StaticLengthDoesNotFitInAWord(i); + revert IFieldLayoutErrors.FieldLayout_StaticLengthDoesNotFitInAWord(i); } unchecked { @@ -82,6 +78,7 @@ library FieldLayoutLib { /** * @title FieldLayoutInstance + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides instance functions for obtaining information from an encoded FieldLayout. */ library FieldLayoutInstance { @@ -153,18 +150,18 @@ library FieldLayoutInstance { */ function validate(FieldLayout fieldLayout) internal pure { if (fieldLayout.isEmpty()) { - revert FieldLayoutLib.FieldLayoutLib_Empty(); + revert IFieldLayoutErrors.FieldLayout_Empty(); } uint256 _numDynamicFields = fieldLayout.numDynamicFields(); if (_numDynamicFields > MAX_DYNAMIC_FIELDS) { - revert FieldLayoutLib.FieldLayoutLib_TooManyDynamicFields(_numDynamicFields, MAX_DYNAMIC_FIELDS); + revert IFieldLayoutErrors.FieldLayout_TooManyDynamicFields(_numDynamicFields, MAX_DYNAMIC_FIELDS); } uint256 _numStaticFields = fieldLayout.numStaticFields(); uint256 _numTotalFields = _numStaticFields + _numDynamicFields; if (_numTotalFields > MAX_TOTAL_FIELDS) { - revert FieldLayoutLib.FieldLayoutLib_TooManyFields(_numTotalFields, MAX_TOTAL_FIELDS); + revert IFieldLayoutErrors.FieldLayout_TooManyFields(_numTotalFields, MAX_TOTAL_FIELDS); } // Static lengths must be valid @@ -172,9 +169,9 @@ library FieldLayoutInstance { for (uint256 i; i < _numStaticFields; ) { uint256 staticByteLength = fieldLayout.atIndex(i); if (staticByteLength == 0) { - revert FieldLayoutLib.FieldLayoutLib_StaticLengthIsZero(i); + revert IFieldLayoutErrors.FieldLayout_StaticLengthIsZero(i); } else if (staticByteLength > WORD_SIZE) { - revert FieldLayoutLib.FieldLayoutLib_StaticLengthDoesNotFitInAWord(i); + revert IFieldLayoutErrors.FieldLayout_StaticLengthDoesNotFitInAWord(i); } _staticDataLength += staticByteLength; unchecked { @@ -183,13 +180,13 @@ library FieldLayoutInstance { } // Static length sums must match if (_staticDataLength != fieldLayout.staticDataLength()) { - revert FieldLayoutLib.FieldLayoutLib_InvalidStaticDataLength(fieldLayout.staticDataLength(), _staticDataLength); + revert IFieldLayoutErrors.FieldLayout_InvalidStaticDataLength(fieldLayout.staticDataLength(), _staticDataLength); } // Unused fields must be zero for (uint256 i = _numStaticFields; i < MAX_TOTAL_FIELDS; i++) { uint256 staticByteLength = fieldLayout.atIndex(i); if (staticByteLength != 0) { - revert FieldLayoutLib.FieldLayoutLib_StaticLengthIsNotZero(i); + revert IFieldLayoutErrors.FieldLayout_StaticLengthIsNotZero(i); } } } diff --git a/packages/store/src/Hook.sol b/packages/store/src/Hook.sol index b650c7fd86..35bbbd9ae9 100644 --- a/packages/store/src/Hook.sol +++ b/packages/store/src/Hook.sol @@ -11,6 +11,7 @@ using HookInstance for Hook global; /** * @title HookLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Library for encoding hooks and filtering hooks from a list by address. */ library HookLib { @@ -67,6 +68,7 @@ library HookLib { /** * @title HookInstance + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Library for interacting with Hook instances. **/ library HookInstance { diff --git a/packages/store/src/IFieldLayoutErrors.sol b/packages/store/src/IFieldLayoutErrors.sol new file mode 100644 index 0000000000..6d421e4b85 --- /dev/null +++ b/packages/store/src/IFieldLayoutErrors.sol @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.24; + +/** + * @title IFieldLayoutErrors + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice This interface includes errors for the FieldLayout library. + * @dev We bundle these errors in an interface (instead of at the file-level or in their corresponding libraries) so they can be inherited by IStore. + * This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend. + */ +interface IFieldLayoutErrors { + error FieldLayout_TooManyFields(uint256 numFields, uint256 maxFields); + error FieldLayout_TooManyDynamicFields(uint256 numFields, uint256 maxFields); + error FieldLayout_Empty(); + error FieldLayout_InvalidStaticDataLength(uint256 staticDataLength, uint256 computedStaticDataLength); + error FieldLayout_StaticLengthIsZero(uint256 index); + error FieldLayout_StaticLengthIsNotZero(uint256 index); + error FieldLayout_StaticLengthDoesNotFitInAWord(uint256 index); +} diff --git a/packages/store/src/IPackedCounterErrors.sol b/packages/store/src/IPackedCounterErrors.sol new file mode 100644 index 0000000000..05eb8f50df --- /dev/null +++ b/packages/store/src/IPackedCounterErrors.sol @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.24; + +/** + * @title IPackedCounterErrors + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice This interface includes errors for the PackedCounter library. + * @dev We bundle these errors in an interface (instead of at the file-level or in their corresponding libraries) so they can be inherited by IStore. + * This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend. + */ +interface IPackedCounterErrors { + error PackedCounter_InvalidLength(uint256 length); +} diff --git a/packages/store/src/ISchemaErrors.sol b/packages/store/src/ISchemaErrors.sol new file mode 100644 index 0000000000..103f630a19 --- /dev/null +++ b/packages/store/src/ISchemaErrors.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.24; + +/** + * @title ISchemaErrors + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice This interface includes errors for the Schema library. + * @dev We bundle these errors in an interface (instead of at the file-level or in their corresponding libraries) so they can be inherited by IStore. + * This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend. + */ +interface ISchemaErrors { + /// @dev Error raised when the provided schema has an invalid length. + error Schema_InvalidLength(uint256 length); + + /// @dev Error raised when a static type is placed after a dynamic type in a schema. + error Schema_StaticTypeAfterDynamicType(); +} diff --git a/packages/store/src/ISliceErrors.sol b/packages/store/src/ISliceErrors.sol new file mode 100644 index 0000000000..6660aa2718 --- /dev/null +++ b/packages/store/src/ISliceErrors.sol @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.24; + +/** + * @title ISliceErrors + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice This interface includes errors for the Slice library. + * @dev We bundle these errors in an interface (instead of at the file-level or in their corresponding libraries) so they can be inherited by IStore. + * This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend. + */ +interface ISliceErrors { + error Slice_OutOfBounds(bytes data, uint256 start, uint256 end); +} diff --git a/packages/store/src/IStore.sol b/packages/store/src/IStore.sol index 2809f10339..71f7cb673f 100644 --- a/packages/store/src/IStore.sol +++ b/packages/store/src/IStore.sol @@ -4,5 +4,22 @@ pragma solidity >=0.8.24; import { IStoreErrors } from "./IStoreErrors.sol"; import { IStoreData } from "./IStoreData.sol"; import { IStoreRegistration } from "./IStoreRegistration.sol"; +import { IFieldLayoutErrors } from "./IFieldLayoutErrors.sol"; +import { IPackedCounterErrors } from "./IPackedCounterErrors.sol"; +import { ISchemaErrors } from "./ISchemaErrors.sol"; +import { ISliceErrors } from "./ISliceErrors.sol"; -interface IStore is IStoreData, IStoreRegistration, IStoreErrors {} +/** + * @title IStore + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice IStore implements the error interfaces for each library that it uses. + */ +interface IStore is + IStoreData, + IStoreRegistration, + IStoreErrors, + IFieldLayoutErrors, + IPackedCounterErrors, + ISchemaErrors, + ISliceErrors +{} diff --git a/packages/store/src/IStoreData.sol b/packages/store/src/IStoreData.sol index 93bf87a182..95059765df 100644 --- a/packages/store/src/IStoreData.sol +++ b/packages/store/src/IStoreData.sol @@ -6,16 +6,11 @@ import { IStoreWrite } from "./IStoreWrite.sol"; /** * @title IStoreData + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice The IStoreData interface includes methods for reading and writing table values. * @dev These methods are frequently invoked during runtime, so it is essential to prioritize optimizing their gas cost. */ interface IStoreData is IStoreRead, IStoreWrite { - /** - * @notice Emitted when the store is initialized. - * @param storeVersion The version of the Store contract. - */ - event HelloStore(bytes32 indexed storeVersion); - /** * @notice Returns the version of the Store contract. * @return version The version of the Store contract. diff --git a/packages/store/src/IStoreErrors.sol b/packages/store/src/IStoreErrors.sol index 62d63f085d..8cef288f36 100644 --- a/packages/store/src/IStoreErrors.sol +++ b/packages/store/src/IStoreErrors.sol @@ -3,6 +3,13 @@ pragma solidity >=0.8.24; import { ResourceId } from "./ResourceId.sol"; +/** + * @title IStoreErrors + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice This interface includes errors for Store. + * @dev We bundle these errors in an interface (instead of at the file-level or in their corresponding library) so they can be inherited by IStore. + * This ensures that all possible errors are included in the IStore ABI for proper decoding in the frontend. + */ interface IStoreErrors { // Errors include a stringified version of the tableId for easier debugging if cleartext tableIds are used error Store_TableAlreadyExists(ResourceId tableId, string tableIdString); diff --git a/packages/store/src/IStoreEvents.sol b/packages/store/src/IStoreEvents.sol index 9d894fe7c3..63a93aac87 100644 --- a/packages/store/src/IStoreEvents.sol +++ b/packages/store/src/IStoreEvents.sol @@ -4,7 +4,17 @@ pragma solidity >=0.8.24; import { ResourceId } from "./ResourceId.sol"; import { PackedCounter } from "./PackedCounter.sol"; +/** + * @title IStoreEvents + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ interface IStoreEvents { + /** + * @notice Emitted when the store is initialized. + * @param storeVersion The version of the Store contract. + */ + event HelloStore(bytes32 indexed storeVersion); + /** * @notice Emitted when a new record is set in the store. * @param tableId The ID of the table where the record is set. diff --git a/packages/store/src/IStoreHook.sol b/packages/store/src/IStoreHook.sol index cea4825d48..e6fb034e89 100644 --- a/packages/store/src/IStoreHook.sol +++ b/packages/store/src/IStoreHook.sol @@ -6,6 +6,10 @@ import { IERC165 } from "./IERC165.sol"; import { PackedCounter } from "./PackedCounter.sol"; import { ResourceId } from "./ResourceId.sol"; +/** + * @title IStoreHook + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ interface IStoreHook is IERC165 { /// @notice Error emitted when a function is not implemented. error StoreHook_NotImplemented(); diff --git a/packages/store/src/IStoreRead.sol b/packages/store/src/IStoreRead.sol index 232593aaa1..0237725efa 100644 --- a/packages/store/src/IStoreRead.sol +++ b/packages/store/src/IStoreRead.sol @@ -6,6 +6,10 @@ import { FieldLayout } from "./FieldLayout.sol"; import { Schema } from "./Schema.sol"; import { ResourceId } from "./ResourceId.sol"; +/** + * @title IStoreRead + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ interface IStoreRead { function getFieldLayout(ResourceId tableId) external view returns (FieldLayout fieldLayout); diff --git a/packages/store/src/IStoreRegistration.sol b/packages/store/src/IStoreRegistration.sol index e620358ba2..683daeb27a 100644 --- a/packages/store/src/IStoreRegistration.sol +++ b/packages/store/src/IStoreRegistration.sol @@ -7,9 +7,9 @@ import { IStoreHook } from "./IStoreHook.sol"; import { ResourceId } from "./ResourceId.sol"; /** - * The IStoreRegistration interface includes methods for managing table field layouts, - * metadata, and hooks, which are usually called once in the setup phase of an application, - * making them less performance critical than the methods. + * @title IStoreRegistration + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @dev This interface includes methods for managing table field layouts, metadata, and hooks, which are usually called once in the setup phase of an application, making them less performance critical than the methods. */ interface IStoreRegistration { function registerTable( diff --git a/packages/store/src/IStoreWrite.sol b/packages/store/src/IStoreWrite.sol index 8ee9a8f46b..90139aa6aa 100644 --- a/packages/store/src/IStoreWrite.sol +++ b/packages/store/src/IStoreWrite.sol @@ -6,6 +6,10 @@ import { PackedCounter } from "./PackedCounter.sol"; import { FieldLayout } from "./FieldLayout.sol"; import { ResourceId } from "./ResourceId.sol"; +/** + * @title IStoreWrite + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ interface IStoreWrite is IStoreEvents { // Set full record (including full dynamic data) function setRecord( diff --git a/packages/store/src/Memory.sol b/packages/store/src/Memory.sol index 87d209293e..d530150a24 100644 --- a/packages/store/src/Memory.sol +++ b/packages/store/src/Memory.sol @@ -5,6 +5,7 @@ import { rightMask } from "./rightMask.sol"; /** * @title Memory Operations + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A library for performing low-level memory operations. * @dev This library provides low-level memory operations with safety checks. */ diff --git a/packages/store/src/PackedCounter.sol b/packages/store/src/PackedCounter.sol index e1dcd58120..fba2ac07fb 100644 --- a/packages/store/src/PackedCounter.sol +++ b/packages/store/src/PackedCounter.sol @@ -2,9 +2,11 @@ pragma solidity >=0.8.24; import { BYTE_TO_BITS } from "./constants.sol"; +import { IPackedCounterErrors } from "./IPackedCounterErrors.sol"; /** * @title PackedCounter Type Definition + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Describes how the packed counter is structured. * - 0x00-0x06 The least significant 7 bytes (uint56) represent the total byte length of dynamic (variable length) data. * - 0x07-0xB The next five bytes (uint40) represent the length of the first dynamic field. @@ -28,6 +30,7 @@ uint256 constant MAX_VAL = type(uint40).max; /** * @title PackedCounter Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Static functions for handling PackedCounter type. * @dev Provides utility functions to pack values into a PackedCounter. * The caller must ensure that the value arguments are <= MAX_VAL. @@ -132,12 +135,11 @@ library PackedCounterLib { /** * @title PackedCounter Instance Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Instance functions for handling a PackedCounter. * @dev Offers decoding, extracting, and setting functionalities for a PackedCounter. */ library PackedCounterInstance { - error PackedCounter_InvalidLength(uint256 length); - /** * @notice Decode the accumulated counter from a PackedCounter. * @dev Extracts the right-most 7 bytes of a PackedCounter. @@ -175,7 +177,7 @@ library PackedCounterInstance { uint256 newValueAtIndex ) internal pure returns (PackedCounter) { if (newValueAtIndex > MAX_VAL) { - revert PackedCounter_InvalidLength(newValueAtIndex); + revert IPackedCounterErrors.PackedCounter_InvalidLength(newValueAtIndex); } uint256 rawPackedCounter = uint256(PackedCounter.unwrap(packedCounter)); diff --git a/packages/store/src/ResourceId.sol b/packages/store/src/ResourceId.sol index 62f39e3ba0..f0905e1305 100644 --- a/packages/store/src/ResourceId.sol +++ b/packages/store/src/ResourceId.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title ResourceId type definition and related utilities + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A ResourceId is a bytes32 data structure that consists of a * type and a name */ @@ -15,6 +16,7 @@ uint256 constant TYPE_BITS = 2 * 8; // 2 bytes * 8 bits per byte /** * @title ResourceIdLib Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides functions to encode data into the ResourceId */ library ResourceIdLib { @@ -31,6 +33,7 @@ library ResourceIdLib { /** * @title ResourceIdInstance Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides functions to extract data from a ResourceId. */ library ResourceIdInstance { diff --git a/packages/store/src/Schema.sol b/packages/store/src/Schema.sol index 87171de1a3..16d9fc674b 100644 --- a/packages/store/src/Schema.sol +++ b/packages/store/src/Schema.sol @@ -4,9 +4,11 @@ pragma solidity >=0.8.24; import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; import { WORD_LAST_INDEX, BYTE_TO_BITS, MAX_TOTAL_FIELDS, MAX_DYNAMIC_FIELDS, LayoutOffsets } from "./constants.sol"; +import { ISchemaErrors } from "./ISchemaErrors.sol"; /** * @title Schema handling in Lattice + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Defines and handles the encoding/decoding of Schemas which describe the layout of data structures. * 2 bytes length of all the static (in size) fields in the schema * 1 byte for number of static size fields @@ -18,22 +20,18 @@ type Schema is bytes32; using SchemaInstance for Schema global; /** + * @title SchemaLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Static utility functions for handling Schemas. */ library SchemaLib { - /// @dev Error raised when the provided schema has an invalid length. - error SchemaLib_InvalidLength(uint256 length); - - /// @dev Error raised when a static type is placed after a dynamic type in a schema. - error SchemaLib_StaticTypeAfterDynamicType(); - /** * @notice Encodes a given schema into a single bytes32. * @param schemas The list of SchemaTypes that constitute the schema. * @return The encoded Schema. */ function encode(SchemaType[] memory schemas) internal pure returns (Schema) { - if (schemas.length > MAX_TOTAL_FIELDS) revert SchemaLib_InvalidLength(schemas.length); + if (schemas.length > MAX_TOTAL_FIELDS) revert ISchemaErrors.Schema_InvalidLength(schemas.length); uint256 schema; uint256 totalLength; uint256 dynamicFields; @@ -51,7 +49,7 @@ library SchemaLib { } } else if (dynamicFields > 0) { // Revert if we have seen a dynamic field before, but now we see a static field - revert SchemaLib_StaticTypeAfterDynamicType(); + revert ISchemaErrors.Schema_StaticTypeAfterDynamicType(); } unchecked { @@ -65,7 +63,7 @@ library SchemaLib { } // Require MAX_DYNAMIC_FIELDS - if (dynamicFields > MAX_DYNAMIC_FIELDS) revert SchemaLib_InvalidLength(dynamicFields); + if (dynamicFields > MAX_DYNAMIC_FIELDS) revert ISchemaErrors.Schema_InvalidLength(dynamicFields); // Get the static field count uint256 staticFields; @@ -86,6 +84,8 @@ library SchemaLib { } /** + * @title SchemaInstance + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Instance utility functions for handling a Schema instance. */ library SchemaInstance { @@ -157,23 +157,23 @@ library SchemaInstance { */ function validate(Schema schema, bool allowEmpty) internal pure { // Schema must not be empty - if (!allowEmpty && schema.isEmpty()) revert SchemaLib.SchemaLib_InvalidLength(0); + if (!allowEmpty && schema.isEmpty()) revert ISchemaErrors.Schema_InvalidLength(0); // Schema must have no more than MAX_DYNAMIC_FIELDS uint256 _numDynamicFields = schema.numDynamicFields(); - if (_numDynamicFields > MAX_DYNAMIC_FIELDS) revert SchemaLib.SchemaLib_InvalidLength(_numDynamicFields); + if (_numDynamicFields > MAX_DYNAMIC_FIELDS) revert ISchemaErrors.Schema_InvalidLength(_numDynamicFields); uint256 _numStaticFields = schema.numStaticFields(); // Schema must not have more than MAX_TOTAL_FIELDS in total uint256 _numTotalFields = _numStaticFields + _numDynamicFields; - if (_numTotalFields > MAX_TOTAL_FIELDS) revert SchemaLib.SchemaLib_InvalidLength(_numTotalFields); + if (_numTotalFields > MAX_TOTAL_FIELDS) revert ISchemaErrors.Schema_InvalidLength(_numTotalFields); // No dynamic field can be before a dynamic field uint256 _staticDataLength; for (uint256 i; i < _numStaticFields; ) { uint256 staticByteLength = schema.atIndex(i).getStaticByteLength(); if (staticByteLength == 0) { - revert SchemaLib.SchemaLib_StaticTypeAfterDynamicType(); + revert ISchemaErrors.Schema_StaticTypeAfterDynamicType(); } _staticDataLength += staticByteLength; unchecked { @@ -183,14 +183,14 @@ library SchemaInstance { // Static length sums must match if (_staticDataLength != schema.staticDataLength()) { - revert SchemaLib.SchemaLib_InvalidLength(schema.staticDataLength()); + revert ISchemaErrors.Schema_InvalidLength(schema.staticDataLength()); } // No static field can be after a dynamic field for (uint256 i = _numStaticFields; i < _numTotalFields; ) { uint256 staticByteLength = schema.atIndex(i).getStaticByteLength(); if (staticByteLength > 0) { - revert SchemaLib.SchemaLib_StaticTypeAfterDynamicType(); + revert ISchemaErrors.Schema_StaticTypeAfterDynamicType(); } unchecked { i++; diff --git a/packages/store/src/Slice.sol b/packages/store/src/Slice.sol index cce6cab687..6fcdc114d9 100644 --- a/packages/store/src/Slice.sol +++ b/packages/store/src/Slice.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; import { Memory } from "./Memory.sol"; import { DecodeSlice } from "./tightcoder/DecodeSlice.sol"; +import { ISliceErrors } from "./ISliceErrors.sol"; // Acknowledgements: // Based on @dk1a's Slice.sol library (https://github.com/dk1a/solidity-stringutils/blob/main/src/Slice.sol) @@ -15,10 +16,9 @@ using DecodeSlice for Slice global; /** * @title Static functions for Slice + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) */ library SliceLib { - error Slice_OutOfBounds(bytes data, uint256 start, uint256 end); - uint256 constant MASK_LEN = uint256(type(uint128).max); /** @@ -56,7 +56,7 @@ library SliceLib { */ function getSubslice(bytes memory data, uint256 start, uint256 end) internal pure returns (Slice) { // TODO this check helps catch bugs and can eventually be removed - if (start > end || end > data.length) revert Slice_OutOfBounds(data, start, end); + if (start > end || end > data.length) revert ISliceErrors.Slice_OutOfBounds(data, start, end); uint256 pointer; assembly { @@ -73,6 +73,7 @@ library SliceLib { /** * @title Instance functions for Slice + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) */ library SliceInstance { /** diff --git a/packages/store/src/Storage.sol b/packages/store/src/Storage.sol index 9d8fa82dac..5fa2dbf7d6 100644 --- a/packages/store/src/Storage.sol +++ b/packages/store/src/Storage.sol @@ -7,6 +7,7 @@ import { BYTE_TO_BITS } from "./constants.sol"; /** * @title Storage Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides functions for low-level storage manipulation, including storing and retrieving bytes. */ library Storage { diff --git a/packages/store/src/StoreCore.sol b/packages/store/src/StoreCore.sol index cfd5a23146..f8f26a1a6b 100644 --- a/packages/store/src/StoreCore.sol +++ b/packages/store/src/StoreCore.sol @@ -9,8 +9,7 @@ import { FieldLayout, FieldLayoutLib } from "./FieldLayout.sol"; import { Schema, SchemaLib } from "./Schema.sol"; import { PackedCounter } from "./PackedCounter.sol"; import { Slice, SliceLib } from "./Slice.sol"; -import { Tables, TablesTableId, ResourceIds, ResourceIdsTableId, StoreHooks, StoreHooksTableId } from "./codegen/index.sol"; -import { _fieldLayout as TablesTableFieldLayout } from "./codegen/tables/Tables.sol"; +import { Tables, ResourceIds, StoreHooks } from "./codegen/index.sol"; import { IStoreErrors } from "./IStoreErrors.sol"; import { IStoreHook } from "./IStoreHook.sol"; import { StoreSwitch } from "./StoreSwitch.sol"; @@ -18,67 +17,14 @@ import { Hook, HookLib } from "./Hook.sol"; import { BEFORE_SET_RECORD, AFTER_SET_RECORD, BEFORE_SPLICE_STATIC_DATA, AFTER_SPLICE_STATIC_DATA, BEFORE_SPLICE_DYNAMIC_DATA, AFTER_SPLICE_DYNAMIC_DATA, BEFORE_DELETE_RECORD, AFTER_DELETE_RECORD } from "./storeHookTypes.sol"; import { ResourceId } from "./ResourceId.sol"; import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "./storeResourceTypes.sol"; +import { IStoreEvents } from "./IStoreEvents.sol"; /** * @title StoreCore Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This library includes implementations for all IStore methods and events related to the store actions. */ library StoreCore { - /** - * @notice Emitted when a new record is set in the store. - * @param tableId The ID of the table where the record is set. - * @param keyTuple An array representing the composite key for the record. - * @param staticData The static data of the record. - * @param encodedLengths The encoded lengths of the dynamic data of the record. - * @param dynamicData The dynamic data of the record. - */ - event Store_SetRecord( - ResourceId indexed tableId, - bytes32[] keyTuple, - bytes staticData, - PackedCounter encodedLengths, - bytes dynamicData - ); - - /** - * @notice Emitted when static data in the store is spliced. - * @dev In static data, data is always overwritten starting at the start position, - * so the total length of the data remains the same and no data is shifted. - * @param tableId The ID of the table where the data is spliced. - * @param keyTuple An array representing the key for the record. - * @param start The start position in bytes for the splice operation. - * @param data The data to write to the static data of the record at the start byte. - */ - event Store_SpliceStaticData(ResourceId indexed tableId, bytes32[] keyTuple, uint48 start, bytes data); - - /** - * @notice Emitted when dynamic data in the store is spliced. - * @param tableId The ID of the table where the data is spliced. - * @param keyTuple An array representing the composite key for the record. - * @param dynamicFieldIndex The index of the dynamic field to splice data, relative to the start of the dynamic fields. - * (Dynamic field index = field index - number of static fields) - * @param start The start position in bytes for the splice operation. - * @param deleteCount The number of bytes to delete in the splice operation. - * @param encodedLengths The encoded lengths of the dynamic data of the record. - * @param data The data to insert into the dynamic data of the record at the start byte. - */ - event Store_SpliceDynamicData( - ResourceId indexed tableId, - bytes32[] keyTuple, - uint8 dynamicFieldIndex, - uint48 start, - uint40 deleteCount, - PackedCounter encodedLengths, - bytes data - ); - - /** - * @notice Emitted when a record is deleted from the store. - * @param tableId The ID of the table where the record is deleted. - * @param keyTuple An array representing the composite key for the record. - */ - event Store_DeleteRecord(ResourceId indexed tableId, bytes32[] keyTuple); - /** * @notice Initialize the store address in StoreSwitch. * @dev Consumers must call this function in their constructor. @@ -103,30 +49,33 @@ library StoreCore { // Instead, we'll register them manually, writing everything to the `Tables` table first, // then the `ResourceIds` table. The logic here ought to be kept in sync with the internals // of the `registerTable` function below. - if (ResourceIds._getExists(TablesTableId)) { - revert IStoreErrors.Store_TableAlreadyExists(TablesTableId, string(abi.encodePacked(TablesTableId))); + if (ResourceIds._getExists(Tables._tableId)) { + revert IStoreErrors.Store_TableAlreadyExists(Tables._tableId, string(abi.encodePacked(Tables._tableId))); } - if (ResourceIds._getExists(ResourceIdsTableId)) { - revert IStoreErrors.Store_TableAlreadyExists(ResourceIdsTableId, string(abi.encodePacked(ResourceIdsTableId))); + if (ResourceIds._getExists(ResourceIds._tableId)) { + revert IStoreErrors.Store_TableAlreadyExists( + ResourceIds._tableId, + string(abi.encodePacked(ResourceIds._tableId)) + ); } Tables._set( - TablesTableId, - Tables.getFieldLayout(), - Tables.getKeySchema(), - Tables.getValueSchema(), + Tables._tableId, + Tables._fieldLayout, + Tables._keySchema, + Tables._valueSchema, abi.encode(Tables.getKeyNames()), abi.encode(Tables.getFieldNames()) ); Tables._set( - ResourceIdsTableId, - ResourceIds.getFieldLayout(), - ResourceIds.getKeySchema(), - ResourceIds.getValueSchema(), + ResourceIds._tableId, + ResourceIds._fieldLayout, + ResourceIds._keySchema, + ResourceIds._valueSchema, abi.encode(ResourceIds.getKeyNames()), abi.encode(ResourceIds.getFieldNames()) ); - ResourceIds._setExists(TablesTableId, true); - ResourceIds._setExists(ResourceIdsTableId, true); + ResourceIds._setExists(Tables._tableId, true); + ResourceIds._setExists(ResourceIds._tableId, true); // Now we can register the rest of the core tables as regular tables. StoreHooks.register(); @@ -147,13 +96,13 @@ library StoreCore { // Explicit check for the Tables table to solve the bootstraping issue // of the Tables table not having a field layout before it is registered // since the field layout is stored in the Tables table. - if (ResourceId.unwrap(tableId) == ResourceId.unwrap(TablesTableId)) { - return TablesTableFieldLayout; + if (ResourceId.unwrap(tableId) == ResourceId.unwrap(Tables._tableId)) { + return Tables._fieldLayout; } return FieldLayout.wrap( Storage.loadField({ - storagePointer: StoreCoreInternal._getStaticDataLocation(TablesTableId, ResourceId.unwrap(tableId)), + storagePointer: StoreCoreInternal._getStaticDataLocation(Tables._tableId, ResourceId.unwrap(tableId)), length: 32, offset: 0 }) @@ -306,7 +255,7 @@ library StoreCore { * @param hookAddress The address of the hook to unregister. */ function unregisterStoreHook(ResourceId tableId, IStoreHook hookAddress) internal { - HookLib.filterListByAddress(StoreHooksTableId, tableId, address(hookAddress)); + HookLib.filterListByAddress(StoreHooks._tableId, tableId, address(hookAddress)); } /************************************************************************ @@ -360,7 +309,7 @@ library StoreCore { // Early return if the table is an offchain table if (tableId.getType() == RESOURCE_OFFCHAIN_TABLE) { // Emit event to notify indexers - emit Store_SetRecord(tableId, keyTuple, staticData, encodedLengths, dynamicData); + emit IStoreEvents.Store_SetRecord(tableId, keyTuple, staticData, encodedLengths, dynamicData); return; } @@ -381,7 +330,7 @@ library StoreCore { } // Emit event to notify indexers - emit Store_SetRecord(tableId, keyTuple, staticData, encodedLengths, dynamicData); + emit IStoreEvents.Store_SetRecord(tableId, keyTuple, staticData, encodedLengths, dynamicData); // Store the static data at the static data location uint256 staticDataLocation = StoreCoreInternal._getStaticDataLocation(tableId, keyTuple); @@ -451,7 +400,7 @@ library StoreCore { // Early return if the table is an offchain table if (tableId.getType() == RESOURCE_OFFCHAIN_TABLE) { // Emit event to notify offchain indexers - emit StoreCore.Store_SpliceStaticData({ tableId: tableId, keyTuple: keyTuple, start: start, data: data }); + emit IStoreEvents.Store_SpliceStaticData({ tableId: tableId, keyTuple: keyTuple, start: start, data: data }); return; } @@ -472,7 +421,7 @@ library StoreCore { } // Emit event to notify offchain indexers - emit StoreCore.Store_SpliceStaticData({ tableId: tableId, keyTuple: keyTuple, start: start, data: data }); + emit IStoreEvents.Store_SpliceStaticData({ tableId: tableId, keyTuple: keyTuple, start: start, data: data }); // Store the provided value in storage Storage.store({ storagePointer: location, offset: start, data: data }); @@ -649,7 +598,7 @@ library StoreCore { // Early return if the table is an offchain table if (tableId.getType() == RESOURCE_OFFCHAIN_TABLE) { // Emit event to notify indexers - emit Store_DeleteRecord(tableId, keyTuple); + emit IStoreEvents.Store_DeleteRecord(tableId, keyTuple); return; } @@ -663,7 +612,7 @@ library StoreCore { } // Emit event to notify indexers - emit Store_DeleteRecord(tableId, keyTuple); + emit IStoreEvents.Store_DeleteRecord(tableId, keyTuple); // Delete static data uint256 staticDataLocation = StoreCoreInternal._getStaticDataLocation(tableId, keyTuple); @@ -994,6 +943,7 @@ library StoreCore { /** * @title StoreCoreInternal + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This library contains internal functions used by StoreCore. * They are not intended to be used directly by consumers of StoreCore. */ @@ -1086,7 +1036,7 @@ library StoreCoreInternal { } // Emit event to notify offchain indexers - emit StoreCore.Store_SpliceDynamicData({ + emit IStoreEvents.Store_SpliceDynamicData({ tableId: tableId, keyTuple: keyTuple, dynamicFieldIndex: dynamicFieldIndex, diff --git a/packages/store/src/StoreData.sol b/packages/store/src/StoreData.sol index 4240108cd4..c963bf4623 100644 --- a/packages/store/src/StoreData.sol +++ b/packages/store/src/StoreData.sol @@ -5,9 +5,11 @@ import { STORE_VERSION } from "./version.sol"; import { IStoreData } from "./IStoreData.sol"; import { StoreRead } from "./StoreRead.sol"; import { StoreCore } from "./StoreCore.sol"; +import { IStoreEvents } from "./IStoreEvents.sol"; /** * @title Store Data Contract + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This contract integrates the core storage functionalities and provides an interface for data storage. * @dev This abstract contract initializes `StoreCore`, implements `storeVersion`, and read methods, * but not write methods. @@ -19,7 +21,7 @@ abstract contract StoreData is IStoreData, StoreRead { */ constructor() { StoreCore.initialize(); - emit HelloStore(STORE_VERSION); + emit IStoreEvents.HelloStore(STORE_VERSION); } /** diff --git a/packages/store/src/StoreHook.sol b/packages/store/src/StoreHook.sol index 7463af8880..2c8ce50d86 100644 --- a/packages/store/src/StoreHook.sol +++ b/packages/store/src/StoreHook.sol @@ -9,6 +9,7 @@ import { ResourceId } from "./ResourceId.sol"; /** * @title Store Hook Contract + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This abstract contract provides hooks for the storage operations. * @dev Implementers should override the hook functions to provide custom logic. * If any hooks are activated without overriding these functions, they revert. diff --git a/packages/store/src/StoreRead.sol b/packages/store/src/StoreRead.sol index 1e26674513..26e3002d20 100644 --- a/packages/store/src/StoreRead.sol +++ b/packages/store/src/StoreRead.sol @@ -10,6 +10,7 @@ import { ResourceId } from "./ResourceId.sol"; /** * @title StoreRead + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A contract that provides read operations for storage tables using `StoreCore`. */ contract StoreRead is IStoreRead { diff --git a/packages/store/src/StoreSwitch.sol b/packages/store/src/StoreSwitch.sol index fbf3155bc2..28db67e062 100644 --- a/packages/store/src/StoreSwitch.sol +++ b/packages/store/src/StoreSwitch.sol @@ -12,6 +12,7 @@ import { ResourceId } from "./ResourceId.sol"; /** * @title StoreSwitch Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This library serves as an interface switch to interact with the store, * either by directing calls to itself or to a designated external store. * @dev The primary purpose is to abstract the storage details, such that the diff --git a/packages/store/src/codegen/index.sol b/packages/store/src/codegen/index.sol index e627a7ed26..062209e3db 100644 --- a/packages/store/src/codegen/index.sol +++ b/packages/store/src/codegen/index.sol @@ -3,7 +3,7 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { StoreHooks, StoreHooksTableId } from "./tables/StoreHooks.sol"; -import { Tables, TablesData, TablesTableId } from "./tables/Tables.sol"; -import { ResourceIds, ResourceIdsTableId } from "./tables/ResourceIds.sol"; +import { StoreHooks } from "./tables/StoreHooks.sol"; +import { Tables, TablesData } from "./tables/Tables.sol"; +import { ResourceIds } from "./tables/ResourceIds.sol"; import { Hooks } from "./tables/Hooks.sol"; diff --git a/packages/store/src/codegen/tables/Hooks.sol b/packages/store/src/codegen/tables/Hooks.sol index 117ee33579..0ed6108f1d 100644 --- a/packages/store/src/codegen/tables/Hooks.sol +++ b/packages/store/src/codegen/tables/Hooks.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../IStore.sol"; import { StoreSwitch } from "../../StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "../../Bytes.sol"; import { Memory } from "../../Memory.sol"; import { SliceLib } from "../../Slice.sol"; import { EncodeArray } from "../../tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../FieldLayout.sol"; -import { Schema, SchemaLib } from "../../Schema.sol"; +import { FieldLayout } from "../../FieldLayout.sol"; +import { Schema } from "../../Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../PackedCounter.sol"; import { ResourceId } from "../../ResourceId.sol"; // Import user types import { ResourceId } from "./../../ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library Hooks { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES21_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes21[]) + Schema constant _valueSchema = Schema.wrap(0x00000001b6000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -79,14 +50,14 @@ library Hooks { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/src/codegen/tables/ResourceIds.sol b/packages/store/src/codegen/tables/ResourceIds.sol index 555c16cde4..7951d5c1e4 100644 --- a/packages/store/src/codegen/tables/ResourceIds.sol +++ b/packages/store/src/codegen/tables/ResourceIds.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../IStore.sol"; import { StoreSwitch } from "../../StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "../../Bytes.sol"; import { Memory } from "../../Memory.sol"; import { SliceLib } from "../../Slice.sol"; import { EncodeArray } from "../../tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../FieldLayout.sol"; -import { Schema, SchemaLib } from "../../Schema.sol"; +import { FieldLayout } from "../../FieldLayout.sol"; +import { Schema } from "../../Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../PackedCounter.sol"; import { ResourceId } from "../../ResourceId.sol"; // Import user types import { ResourceId } from "./../../ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "ResourceIds", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000005265736f757263654964730000000000); -ResourceId constant ResourceIdsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library ResourceIds { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "ResourceIds", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000005265736f757263654964730000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library ResourceIds { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/src/codegen/tables/StoreHooks.sol b/packages/store/src/codegen/tables/StoreHooks.sol index 10917219c9..b87dc19fd5 100644 --- a/packages/store/src/codegen/tables/StoreHooks.sol +++ b/packages/store/src/codegen/tables/StoreHooks.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../IStore.sol"; import { StoreSwitch } from "../../StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "../../Bytes.sol"; import { Memory } from "../../Memory.sol"; import { SliceLib } from "../../Slice.sol"; import { EncodeArray } from "../../tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../FieldLayout.sol"; -import { Schema, SchemaLib } from "../../Schema.sol"; +import { FieldLayout } from "../../FieldLayout.sol"; +import { Schema } from "../../Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../PackedCounter.sol"; import { ResourceId } from "../../ResourceId.sol"; // Import user types import { ResourceId } from "./../../ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "StoreHooks", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f726500000000000000000053746f7265486f6f6b73000000000000); -ResourceId constant StoreHooksTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library StoreHooks { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "StoreHooks", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f726500000000000000000053746f7265486f6f6b73000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES21_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes21[]) + Schema constant _valueSchema = Schema.wrap(0x00000001b6000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library StoreHooks { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/src/codegen/tables/Tables.sol b/packages/store/src/codegen/tables/Tables.sol index 17e0190294..8197adb4d8 100644 --- a/packages/store/src/codegen/tables/Tables.sol +++ b/packages/store/src/codegen/tables/Tables.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../IStore.sol"; import { StoreSwitch } from "../../StoreSwitch.sol"; @@ -14,8 +11,8 @@ import { Bytes } from "../../Bytes.sol"; import { Memory } from "../../Memory.sol"; import { SliceLib } from "../../Slice.sol"; import { EncodeArray } from "../../tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../FieldLayout.sol"; -import { Schema, SchemaLib } from "../../Schema.sol"; +import { FieldLayout } from "../../FieldLayout.sol"; +import { Schema } from "../../Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../PackedCounter.sol"; import { ResourceId } from "../../ResourceId.sol"; @@ -24,14 +21,6 @@ import { ResourceId } from "./../../ResourceId.sol"; import { FieldLayout } from "./../../FieldLayout.sol"; import { Schema } from "./../../Schema.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Tables", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000005461626c657300000000000000000000); -ResourceId constant TablesTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0060030220202000000000000000000000000000000000000000000000000000 -); - struct TablesData { FieldLayout fieldLayout; Schema keySchema; @@ -41,39 +30,16 @@ struct TablesData { } library Tables { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Tables", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000005461626c657300000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0060030220202000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](5); - _valueSchema[0] = SchemaType.BYTES32; - _valueSchema[1] = SchemaType.BYTES32; - _valueSchema[2] = SchemaType.BYTES32; - _valueSchema[3] = SchemaType.BYTES; - _valueSchema[4] = SchemaType.BYTES; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32, bytes32, bytes32, bytes, bytes) + Schema constant _valueSchema = Schema.wrap(0x006003025f5f5fc4c40000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -101,14 +67,14 @@ library Tables { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/src/constants.sol b/packages/store/src/constants.sol index 62c41f0896..87683f6a26 100644 --- a/packages/store/src/constants.sol +++ b/packages/store/src/constants.sol @@ -2,12 +2,11 @@ pragma solidity >=0.8.24; /** - * @title Shared Constants for EVM and Schema Handling + * @title Shared constants for EVM and schema handling + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This file provides constants for better handling of EVM and Schema related functionalities. */ -/* Shared constants */ - /// @dev Represents the total byte length of an EVM word. uint256 constant WORD_SIZE = 32; @@ -28,6 +27,7 @@ uint256 constant MAX_DYNAMIC_FIELDS = 5; /** * @title LayoutOffsets Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This library provides constant offsets for FieldLayout and Schema metadata. * @dev FieldLayout and Schema utilize the same offset values for metadata. */ diff --git a/packages/store/src/rightMask.sol b/packages/store/src/rightMask.sol index ad4f94a594..56e13f7921 100644 --- a/packages/store/src/rightMask.sol +++ b/packages/store/src/rightMask.sol @@ -5,6 +5,7 @@ import { BYTE_TO_BITS } from "./constants.sol"; /** * @title Byte Mask Utility + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Utility functions to manage bytes in memory. * @dev Adapted from https://github.com/dk1a/solidity-stringutils/blob/main/src/utils/mem.sol#L149-L167 */ diff --git a/packages/store/src/storeHookTypes.sol b/packages/store/src/storeHookTypes.sol index c504ff618f..2e898baa1c 100644 --- a/packages/store/src/storeHookTypes.sol +++ b/packages/store/src/storeHookTypes.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title Store Hook Flags + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Constants for enabling store hooks. * @dev These bitmaps can be used to enable selected store hooks. They can be combined with a bitwise OR (`|`). */ diff --git a/packages/store/src/storeResourceTypes.sol b/packages/store/src/storeResourceTypes.sol index f72210cb03..e2e1a171fe 100644 --- a/packages/store/src/storeResourceTypes.sol +++ b/packages/store/src/storeResourceTypes.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title Resource Identifiers + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Constants representing unique identifiers for different resource types. * @dev These identifiers can be used to distinguish between various resource types. */ diff --git a/packages/store/src/tightcoder/DecodeSlice.sol b/packages/store/src/tightcoder/DecodeSlice.sol index 6d2f70bd37..e77f4116d9 100644 --- a/packages/store/src/tightcoder/DecodeSlice.sol +++ b/packages/store/src/tightcoder/DecodeSlice.sol @@ -7,6 +7,7 @@ import { Slice } from "../Slice.sol"; /** * @title DecodeSlice Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A library for decoding slices of data into specific data types. * @dev This library provides functions for decoding slices into arrays of basic uint types. */ diff --git a/packages/store/src/tightcoder/EncodeArray.sol b/packages/store/src/tightcoder/EncodeArray.sol index 4b04e9d52b..0eb7673eec 100644 --- a/packages/store/src/tightcoder/EncodeArray.sol +++ b/packages/store/src/tightcoder/EncodeArray.sol @@ -6,6 +6,7 @@ import { TightCoder } from "./TightCoder.sol"; /** * @title EncodeArray + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This library provides utilities for encoding arrays into tightly packed bytes representations. */ library EncodeArray { diff --git a/packages/store/src/tightcoder/TightCoder.sol b/packages/store/src/tightcoder/TightCoder.sol index 5d42eeda84..2c432b0857 100644 --- a/packages/store/src/tightcoder/TightCoder.sol +++ b/packages/store/src/tightcoder/TightCoder.sol @@ -5,6 +5,7 @@ import { Slice } from "../Slice.sol"; /** * @title TightCoder + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides low-level generic implementations of tight encoding and decoding for arrays. * This is consistent with Solidity's internal tight encoding for array data in storage. */ diff --git a/packages/store/src/version.sol b/packages/store/src/version.sol index f7963b91f4..279871337e 100644 --- a/packages/store/src/version.sol +++ b/packages/store/src/version.sol @@ -2,9 +2,10 @@ pragma solidity >=0.8.24; /** - * @title Store Versioning - * @notice Contains a constant representing the version of the store. + * @title Store version + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice Contains a constant representing the version of the Store. */ -/// @dev Identifier for the current store version. +/// @dev Identifier for the current Store version. bytes32 constant STORE_VERSION = "1.0.0-unaudited"; diff --git a/packages/store/test/Callbacks.t.sol b/packages/store/test/Callbacks.t.sol index f9af114b08..108d7d8105 100644 --- a/packages/store/test/Callbacks.t.sol +++ b/packages/store/test/Callbacks.t.sol @@ -5,6 +5,7 @@ import { Test } from "forge-std/Test.sol"; import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { Callbacks } from "./codegen/tables/Callbacks.sol"; import { StoreMock } from "./StoreMock.sol"; +import { Schema, SchemaLib, SchemaType } from "../src/Schema.sol"; contract CallbacksTest is Test, GasReporter, StoreMock { function testSetAndGet() public { @@ -34,4 +35,18 @@ contract CallbacksTest is Test, GasReporter, StoreMock { assertEq(returnedCallbacks.length, 2); assertEq(returnedCallbacks[1], callbacks[0]); } + + function testKeySchemaEncoding() public { + SchemaType[] memory _keySchema = new SchemaType[](1); + _keySchema[0] = SchemaType.BYTES32; + + assertEq(Schema.unwrap(SchemaLib.encode(_keySchema)), Schema.unwrap(Callbacks._keySchema)); + } + + function testValueSchemaEncoding() public { + SchemaType[] memory _valueSchema = new SchemaType[](1); + _valueSchema[0] = SchemaType.BYTES24_ARRAY; + + assertEq(Schema.unwrap(SchemaLib.encode(_valueSchema)), Schema.unwrap(Callbacks._valueSchema)); + } } diff --git a/packages/store/test/FieldLayout.t.sol b/packages/store/test/FieldLayout.t.sol index 915d96618f..bb835a882b 100644 --- a/packages/store/test/FieldLayout.t.sol +++ b/packages/store/test/FieldLayout.t.sol @@ -6,6 +6,7 @@ import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { FieldLayout, FieldLayoutLib } from "../src/FieldLayout.sol"; import { FieldLayoutEncodeHelper } from "./FieldLayoutEncodeHelper.sol"; import { MAX_TOTAL_FIELDS, MAX_DYNAMIC_FIELDS } from "../src/constants.sol"; +import { IFieldLayoutErrors } from "../src/IFieldLayoutErrors.sol"; // TODO add tests for all lengths contract FieldLayoutTest is Test, GasReporter { @@ -36,12 +37,12 @@ contract FieldLayoutTest is Test, GasReporter { } function testInvalidFieldLayoutStaticTypeIsZero() public { - vm.expectRevert(abi.encodeWithSelector(FieldLayoutLib.FieldLayoutLib_StaticLengthIsZero.selector, 1)); + vm.expectRevert(abi.encodeWithSelector(IFieldLayoutErrors.FieldLayout_StaticLengthIsZero.selector, 1)); FieldLayoutEncodeHelper.encode(1, 0, 1); } function testInvalidFieldLayoutStaticTypeDoesNotFitInAWord() public { - vm.expectRevert(abi.encodeWithSelector(FieldLayoutLib.FieldLayoutLib_StaticLengthDoesNotFitInAWord.selector, 1)); + vm.expectRevert(abi.encodeWithSelector(IFieldLayoutErrors.FieldLayout_StaticLengthDoesNotFitInAWord.selector, 1)); FieldLayoutEncodeHelper.encode(1, 33, 1); } @@ -97,7 +98,7 @@ contract FieldLayoutTest is Test, GasReporter { fieldLayout[16] = 32; vm.expectRevert( abi.encodeWithSelector( - FieldLayoutLib.FieldLayoutLib_TooManyFields.selector, + IFieldLayoutErrors.FieldLayout_TooManyFields.selector, fieldLayout.length + dynamicFields, MAX_TOTAL_FIELDS ) @@ -117,7 +118,7 @@ contract FieldLayoutTest is Test, GasReporter { uint256 dynamicFields = 6; vm.expectRevert( abi.encodeWithSelector( - FieldLayoutLib.FieldLayoutLib_TooManyDynamicFields.selector, + IFieldLayoutErrors.FieldLayout_TooManyDynamicFields.selector, fieldLayout.length + dynamicFields, MAX_DYNAMIC_FIELDS ) @@ -202,7 +203,7 @@ contract FieldLayoutTest is Test, GasReporter { vm.expectRevert( abi.encodeWithSelector( - FieldLayoutLib.FieldLayoutLib_TooManyDynamicFields.selector, + IFieldLayoutErrors.FieldLayout_TooManyDynamicFields.selector, encodedFieldLayout.numDynamicFields(), MAX_DYNAMIC_FIELDS ) diff --git a/packages/store/test/KeyEncoding.t.sol b/packages/store/test/KeyEncoding.t.sol index 0f72fe9e48..308bc696b2 100644 --- a/packages/store/test/KeyEncoding.t.sol +++ b/packages/store/test/KeyEncoding.t.sol @@ -5,10 +5,10 @@ import { Test } from "forge-std/Test.sol"; import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { StoreCore } from "../src/StoreCore.sol"; import { FieldLayout } from "../src/FieldLayout.sol"; -import { Schema } from "../src/Schema.sol"; +import { Schema, SchemaLib, SchemaType } from "../src/Schema.sol"; import { StoreMock } from "./StoreMock.sol"; -import { KeyEncoding, KeyEncodingTableId } from "./codegen/index.sol"; +import { KeyEncoding } from "./codegen/index.sol"; import { ExampleEnum } from "./codegen/common.sol"; contract KeyEncodingTest is Test, GasReporter, StoreMock { @@ -17,8 +17,8 @@ contract KeyEncodingTest is Test, GasReporter, StoreMock { KeyEncoding.register(); endGasReport(); - FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(KeyEncodingTableId); - FieldLayout declaredFieldLayout = KeyEncoding.getFieldLayout(); + FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(KeyEncoding._tableId); + FieldLayout declaredFieldLayout = KeyEncoding._fieldLayout; assertEq(keccak256(abi.encode(registeredFieldLayout)), keccak256(abi.encode(declaredFieldLayout))); } @@ -26,8 +26,8 @@ contract KeyEncodingTest is Test, GasReporter, StoreMock { function testRegisterAndGetSchema() public { KeyEncoding.register(); - Schema registeredSchema = StoreCore.getValueSchema(KeyEncodingTableId); - Schema declaredSchema = KeyEncoding.getValueSchema(); + Schema registeredSchema = StoreCore.getValueSchema(KeyEncoding._tableId); + Schema declaredSchema = KeyEncoding._valueSchema; assertEq(keccak256(abi.encode(registeredSchema)), keccak256(abi.encode(declaredSchema))); } @@ -87,4 +87,23 @@ contract KeyEncodingTest is Test, GasReporter, StoreMock { assertEq(keyTuple[4], bytes32(abi.encode(true))); assertEq(keyTuple[5], bytes32(abi.encode(ExampleEnum.Third))); } + + function testKeySchemaEncoding() public { + SchemaType[] memory _keySchema = new SchemaType[](6); + _keySchema[0] = SchemaType.UINT256; + _keySchema[1] = SchemaType.INT32; + _keySchema[2] = SchemaType.BYTES16; + _keySchema[3] = SchemaType.ADDRESS; + _keySchema[4] = SchemaType.BOOL; + _keySchema[5] = SchemaType.UINT8; + + assertEq(Schema.unwrap(SchemaLib.encode(_keySchema)), Schema.unwrap(KeyEncoding._keySchema)); + } + + function testValueSchemaEncoding() public { + SchemaType[] memory _valueSchema = new SchemaType[](1); + _valueSchema[0] = SchemaType.BOOL; + + assertEq(Schema.unwrap(SchemaLib.encode(_valueSchema)), Schema.unwrap(KeyEncoding._valueSchema)); + } } diff --git a/packages/store/test/Mixed.t.sol b/packages/store/test/Mixed.t.sol index c060604df5..31925d812f 100644 --- a/packages/store/test/Mixed.t.sol +++ b/packages/store/test/Mixed.t.sol @@ -6,10 +6,10 @@ import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { StoreCore } from "../src/StoreCore.sol"; import { StoreMock } from "../test/StoreMock.sol"; import { FieldLayout } from "../src/FieldLayout.sol"; -import { Schema } from "../src/Schema.sol"; +import { Schema, SchemaLib, SchemaType } from "../src/Schema.sol"; import { PackedCounter } from "../src/PackedCounter.sol"; -import { Mixed, MixedData, MixedTableId } from "./codegen/index.sol"; +import { Mixed, MixedData } from "./codegen/index.sol"; contract MixedTest is Test, GasReporter, StoreMock { MixedData private testMixed; @@ -26,15 +26,15 @@ contract MixedTest is Test, GasReporter, StoreMock { } function testRegisterAndGetFieldLayout() public { - FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(MixedTableId); - FieldLayout declaredFieldLayout = Mixed.getFieldLayout(); + FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(Mixed._tableId); + FieldLayout declaredFieldLayout = Mixed._fieldLayout; assertEq(keccak256(abi.encode(registeredFieldLayout)), keccak256(abi.encode(declaredFieldLayout))); } function testRegisterAndGetSchema() public { - Schema registeredSchema = StoreCore.getValueSchema(MixedTableId); - Schema declaredSchema = Mixed.getValueSchema(); + Schema registeredSchema = StoreCore.getValueSchema(Mixed._tableId); + Schema declaredSchema = Mixed._valueSchema; assertEq(keccak256(abi.encode(registeredSchema)), keccak256(abi.encode(declaredSchema))); } @@ -130,4 +130,21 @@ contract MixedTest is Test, GasReporter, StoreMock { assertEq(encodedLengths.unwrap(), hex"000000000000000000000000000000000000000b000000000800000000000013"); assertEq(dynamicData, hex"0000000300000004736f6d6520737472696e67"); } + + function testKeySchemaEncoding() public { + SchemaType[] memory _keySchema = new SchemaType[](1); + _keySchema[0] = SchemaType.BYTES32; + + assertEq(Schema.unwrap(SchemaLib.encode(_keySchema)), Schema.unwrap(Mixed._keySchema)); + } + + function testValueSchemaEncoding() public { + SchemaType[] memory _valueSchema = new SchemaType[](4); + _valueSchema[0] = SchemaType.UINT32; + _valueSchema[1] = SchemaType.UINT128; + _valueSchema[2] = SchemaType.UINT32_ARRAY; + _valueSchema[3] = SchemaType.STRING; + + assertEq(Schema.unwrap(SchemaLib.encode(_valueSchema)), Schema.unwrap(Mixed._valueSchema)); + } } diff --git a/packages/store/test/Schema.t.sol b/packages/store/test/Schema.t.sol index 3762448b0c..e648afb589 100644 --- a/packages/store/test/Schema.t.sol +++ b/packages/store/test/Schema.t.sol @@ -7,6 +7,7 @@ import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol" import { Schema, SchemaLib } from "../src/Schema.sol"; import { SchemaEncodeHelper } from "./SchemaEncodeHelper.sol"; import { WORD_LAST_INDEX, BYTE_TO_BITS, LayoutOffsets } from "../src/constants.sol"; +import { ISchemaErrors } from "../src/ISchemaErrors.sol"; /** * @notice Encodes a given schema into a single bytes32, without checks. @@ -89,7 +90,7 @@ contract SchemaTest is Test, GasReporter { } function testInvalidSchemaStaticAfterDynamic() public { - vm.expectRevert(abi.encodeWithSelector(SchemaLib.SchemaLib_StaticTypeAfterDynamicType.selector)); + vm.expectRevert(abi.encodeWithSelector(ISchemaErrors.Schema_StaticTypeAfterDynamicType.selector)); SchemaEncodeHelper.encode(SchemaType.UINT8, SchemaType.UINT32_ARRAY, SchemaType.UINT16); } @@ -159,7 +160,7 @@ contract SchemaTest is Test, GasReporter { schema[26] = SchemaType.UINT32_ARRAY; schema[27] = SchemaType.UINT32_ARRAY; schema[28] = SchemaType.UINT32_ARRAY; - vm.expectRevert(abi.encodeWithSelector(SchemaLib.SchemaLib_InvalidLength.selector, schema.length)); + vm.expectRevert(abi.encodeWithSelector(ISchemaErrors.Schema_InvalidLength.selector, schema.length)); SchemaLib.encode(schema); } @@ -183,7 +184,7 @@ contract SchemaTest is Test, GasReporter { schema[3] = SchemaType.UINT32_ARRAY; schema[4] = SchemaType.UINT32_ARRAY; schema[5] = SchemaType.UINT32_ARRAY; - vm.expectRevert(abi.encodeWithSelector(SchemaLib.SchemaLib_InvalidLength.selector, schema.length)); + vm.expectRevert(abi.encodeWithSelector(ISchemaErrors.Schema_InvalidLength.selector, schema.length)); SchemaLib.encode(schema); } @@ -296,7 +297,7 @@ contract SchemaTest is Test, GasReporter { Schema encodedSchema = Schema.wrap(keccak256("some invalid schema")); vm.expectRevert( - abi.encodeWithSelector(SchemaLib.SchemaLib_InvalidLength.selector, encodedSchema.numDynamicFields()) + abi.encodeWithSelector(ISchemaErrors.Schema_InvalidLength.selector, encodedSchema.numDynamicFields()) ); encodedSchema.validate({ allowEmpty: false }); @@ -334,7 +335,7 @@ contract SchemaTest is Test, GasReporter { schema[27] = SchemaType.UINT32_ARRAY; Schema encodedSchema = encodeUnsafe(schema); - vm.expectRevert(SchemaLib.SchemaLib_StaticTypeAfterDynamicType.selector); + vm.expectRevert(ISchemaErrors.Schema_StaticTypeAfterDynamicType.selector); encodedSchema.validate({ allowEmpty: false }); } diff --git a/packages/store/test/StoreCore.t.sol b/packages/store/test/StoreCore.t.sol index d709b84003..cd416d88c9 100644 --- a/packages/store/test/StoreCore.t.sol +++ b/packages/store/test/StoreCore.t.sol @@ -15,7 +15,7 @@ import { IStoreErrors } from "../src/IStoreErrors.sol"; import { IStore } from "../src/IStore.sol"; import { StoreSwitch } from "../src/StoreSwitch.sol"; import { IStoreHook } from "../src/IStoreHook.sol"; -import { Tables, ResourceIds, TablesTableId } from "../src/codegen/index.sol"; +import { Tables, ResourceIds } from "../src/codegen/index.sol"; import { ResourceId, ResourceIdLib } from "../src/ResourceId.sol"; import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "../src/storeResourceTypes.sol"; import { FieldLayoutEncodeHelper } from "./FieldLayoutEncodeHelper.sol"; @@ -26,6 +26,7 @@ import { MirrorSubscriber, indexerTableId } from "./MirrorSubscriber.sol"; import { RevertSubscriber } from "./RevertSubscriber.sol"; import { EchoSubscriber } from "./EchoSubscriber.sol"; import { setDynamicDataLengthAtIndex } from "./setDynamicDataLengthAtIndex.sol"; +import { IFieldLayoutErrors } from "../src/IFieldLayoutErrors.sol"; struct TestStruct { uint128 firstData; @@ -82,7 +83,7 @@ contract StoreCoreTest is Test, StoreMock { keyTuple[0] = ResourceId.unwrap(tableId); vm.expectEmit(true, true, true, true); emit Store_SetRecord( - TablesTableId, + Tables._tableId, keyTuple, Tables.encodeStatic(fieldLayout, keySchema, valueSchema), Tables.encodeLengths(abi.encode(keyNames), abi.encode(fieldNames)), @@ -130,7 +131,7 @@ contract StoreCoreTest is Test, StoreMock { vm.expectRevert( abi.encodeWithSelector( - FieldLayoutLib.FieldLayoutLib_TooManyDynamicFields.selector, + IFieldLayoutErrors.FieldLayout_TooManyDynamicFields.selector, invalidFieldLayout.numDynamicFields(), 5 ) diff --git a/packages/store/test/StoreMock.t.sol b/packages/store/test/StoreMock.t.sol index b4e7be586a..3aa1191288 100644 --- a/packages/store/test/StoreMock.t.sol +++ b/packages/store/test/StoreMock.t.sol @@ -7,13 +7,12 @@ import { STORE_VERSION } from "../src/version.sol"; import { StoreCore } from "../src/StoreCore.sol"; import { StoreMock } from "../test/StoreMock.sol"; import { StoreSwitch } from "../src/StoreSwitch.sol"; +import { IStoreEvents } from "../src/IStoreEvents.sol"; contract StoreMockTest is Test { - event HelloStore(bytes32 indexed storeVersion); - function testStoreMockConstrctor() public { vm.expectEmit(true, true, true, true); - emit HelloStore(STORE_VERSION); + emit IStoreEvents.HelloStore(STORE_VERSION); new StoreMock(); } } diff --git a/packages/store/test/Vector2.t.sol b/packages/store/test/Vector2.t.sol index c07cb1f0d0..6ad8c1aae6 100644 --- a/packages/store/test/Vector2.t.sol +++ b/packages/store/test/Vector2.t.sol @@ -6,9 +6,9 @@ import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { StoreCore } from "../src/StoreCore.sol"; import { StoreMock } from "../test/StoreMock.sol"; import { FieldLayout } from "../src/FieldLayout.sol"; -import { Schema } from "../src/Schema.sol"; +import { Schema, SchemaLib, SchemaType } from "../src/Schema.sol"; -import { Vector2, Vector2Data, Vector2TableId } from "./codegen/index.sol"; +import { Vector2, Vector2Data } from "./codegen/index.sol"; contract Vector2Test is Test, GasReporter, StoreMock { function testRegisterAndGetFieldLayout() public { @@ -16,8 +16,8 @@ contract Vector2Test is Test, GasReporter, StoreMock { Vector2.register(); endGasReport(); - FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(Vector2TableId); - FieldLayout declaredFieldLayout = Vector2.getFieldLayout(); + FieldLayout registeredFieldLayout = StoreCore.getFieldLayout(Vector2._tableId); + FieldLayout declaredFieldLayout = Vector2._fieldLayout; assertEq(FieldLayout.unwrap(registeredFieldLayout), FieldLayout.unwrap(declaredFieldLayout)); } @@ -25,8 +25,8 @@ contract Vector2Test is Test, GasReporter, StoreMock { function testRegisterAndGetSchema() public { Vector2.register(); - Schema registeredSchema = StoreCore.getValueSchema(Vector2TableId); - Schema declaredSchema = Vector2.getValueSchema(); + Schema registeredSchema = StoreCore.getValueSchema(Vector2._tableId); + Schema declaredSchema = Vector2._valueSchema; assertEq(Schema.unwrap(registeredSchema), Schema.unwrap(declaredSchema)); } @@ -46,4 +46,19 @@ contract Vector2Test is Test, GasReporter, StoreMock { assertEq(vector.x, 1); assertEq(vector.y, 2); } + + function testKeySchemaEncoding() public { + SchemaType[] memory _keySchema = new SchemaType[](1); + _keySchema[0] = SchemaType.BYTES32; + + assertEq(Schema.unwrap(SchemaLib.encode(_keySchema)), Schema.unwrap(Vector2._keySchema)); + } + + function testValueSchemaEncoding() public { + SchemaType[] memory _valueSchema = new SchemaType[](2); + _valueSchema[0] = SchemaType.UINT32; + _valueSchema[1] = SchemaType.UINT32; + + assertEq(Schema.unwrap(SchemaLib.encode(_valueSchema)), Schema.unwrap(Vector2._valueSchema)); + } } diff --git a/packages/store/test/codegen/index.sol b/packages/store/test/codegen/index.sol index a37fcf0edf..77c2b35159 100644 --- a/packages/store/test/codegen/index.sol +++ b/packages/store/test/codegen/index.sol @@ -3,7 +3,7 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Callbacks, CallbacksTableId } from "./tables/Callbacks.sol"; -import { Mixed, MixedData, MixedTableId } from "./tables/Mixed.sol"; -import { Vector2, Vector2Data, Vector2TableId } from "./tables/Vector2.sol"; -import { KeyEncoding, KeyEncodingTableId } from "./tables/KeyEncoding.sol"; +import { Callbacks } from "./tables/Callbacks.sol"; +import { Mixed, MixedData } from "./tables/Mixed.sol"; +import { Vector2, Vector2Data } from "./tables/Vector2.sol"; +import { KeyEncoding } from "./tables/KeyEncoding.sol"; diff --git a/packages/store/test/codegen/tables/Callbacks.sol b/packages/store/test/codegen/tables/Callbacks.sol index b69a323a2c..e2a5e14f51 100644 --- a/packages/store/test/codegen/tables/Callbacks.sol +++ b/packages/store/test/codegen/tables/Callbacks.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../../src/IStore.sol"; import { StoreSwitch } from "../../../src/StoreSwitch.sol"; @@ -14,49 +11,22 @@ import { Bytes } from "../../../src/Bytes.sol"; import { Memory } from "../../../src/Memory.sol"; import { SliceLib } from "../../../src/Slice.sol"; import { EncodeArray } from "../../../src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../../src/FieldLayout.sol"; -import { Schema, SchemaLib } from "../../../src/Schema.sol"; +import { FieldLayout } from "../../../src/FieldLayout.sol"; +import { Schema } from "../../../src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../../src/PackedCounter.sol"; import { ResourceId } from "../../../src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Callbacks", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f726500000000000000000043616c6c6261636b7300000000000000); -ResourceId constant CallbacksTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library Callbacks { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Callbacks", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f726500000000000000000043616c6c6261636b7300000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES24_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes24[]) + Schema constant _valueSchema = Schema.wrap(0x00000001b9000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -80,14 +50,14 @@ library Callbacks { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/test/codegen/tables/KeyEncoding.sol b/packages/store/test/codegen/tables/KeyEncoding.sol index ecdf0b260b..4ee62a2c8f 100644 --- a/packages/store/test/codegen/tables/KeyEncoding.sol +++ b/packages/store/test/codegen/tables/KeyEncoding.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../../src/IStore.sol"; import { StoreSwitch } from "../../../src/StoreSwitch.sol"; @@ -14,57 +11,25 @@ import { Bytes } from "../../../src/Bytes.sol"; import { Memory } from "../../../src/Memory.sol"; import { SliceLib } from "../../../src/Slice.sol"; import { EncodeArray } from "../../../src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../../src/FieldLayout.sol"; -import { Schema, SchemaLib } from "../../../src/Schema.sol"; +import { FieldLayout } from "../../../src/FieldLayout.sol"; +import { Schema } from "../../../src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../../src/PackedCounter.sol"; import { ResourceId } from "../../../src/ResourceId.sol"; // Import user types import { ExampleEnum } from "./../common.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "KeyEncoding", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000004b6579456e636f64696e670000000000); -ResourceId constant KeyEncodingTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library KeyEncoding { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "KeyEncoding", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000004b6579456e636f64696e670000000000); - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](6); - _keySchema[0] = SchemaType.UINT256; - _keySchema[1] = SchemaType.INT32; - _keySchema[2] = SchemaType.BYTES16; - _keySchema[3] = SchemaType.ADDRESS; - _keySchema[4] = SchemaType.BOOL; - _keySchema[5] = SchemaType.UINT8; - - return SchemaLib.encode(_keySchema); - } - - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint256, int32, bytes16, address, bool, uint8) + Schema constant _keySchema = Schema.wrap(0x004a06001f234f61600000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -93,14 +58,14 @@ library KeyEncoding { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/test/codegen/tables/Mixed.sol b/packages/store/test/codegen/tables/Mixed.sol index 57a7977e55..68c8a475ed 100644 --- a/packages/store/test/codegen/tables/Mixed.sol +++ b/packages/store/test/codegen/tables/Mixed.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../../src/IStore.sol"; import { StoreSwitch } from "../../../src/StoreSwitch.sol"; @@ -14,19 +11,11 @@ import { Bytes } from "../../../src/Bytes.sol"; import { Memory } from "../../../src/Memory.sol"; import { SliceLib } from "../../../src/Slice.sol"; import { EncodeArray } from "../../../src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../../src/FieldLayout.sol"; -import { Schema, SchemaLib } from "../../../src/Schema.sol"; +import { FieldLayout } from "../../../src/FieldLayout.sol"; +import { Schema } from "../../../src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../../src/PackedCounter.sol"; import { ResourceId } from "../../../src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Mixed", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000004d697865640000000000000000000000); -ResourceId constant MixedTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014020204100000000000000000000000000000000000000000000000000000 -); - struct MixedData { uint32 u32; uint128 u128; @@ -35,38 +24,16 @@ struct MixedData { } library Mixed { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Mixed", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f72650000000000000000004d697865640000000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014020204100000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](4); - _valueSchema[0] = SchemaType.UINT32; - _valueSchema[1] = SchemaType.UINT128; - _valueSchema[2] = SchemaType.UINT32_ARRAY; - _valueSchema[3] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32, uint128, uint32[], string) + Schema constant _valueSchema = Schema.wrap(0x00140202030f65c5000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -93,14 +60,14 @@ library Mixed { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/test/codegen/tables/Vector2.sol b/packages/store/test/codegen/tables/Vector2.sol index 687db88179..d15b8fef52 100644 --- a/packages/store/test/codegen/tables/Vector2.sol +++ b/packages/store/test/codegen/tables/Vector2.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "../../../src/IStore.sol"; import { StoreSwitch } from "../../../src/StoreSwitch.sol"; @@ -14,55 +11,27 @@ import { Bytes } from "../../../src/Bytes.sol"; import { Memory } from "../../../src/Memory.sol"; import { SliceLib } from "../../../src/Slice.sol"; import { EncodeArray } from "../../../src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "../../../src/FieldLayout.sol"; -import { Schema, SchemaLib } from "../../../src/Schema.sol"; +import { FieldLayout } from "../../../src/FieldLayout.sol"; +import { Schema } from "../../../src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "../../../src/PackedCounter.sol"; import { ResourceId } from "../../../src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Vector2", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746273746f7265000000000000000000566563746f7232000000000000000000); -ResourceId constant Vector2TableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0008020004040000000000000000000000000000000000000000000000000000 -); - struct Vector2Data { uint32 x; uint32 y; } library Vector2 { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "store", name: "Vector2", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746273746f7265000000000000000000566563746f7232000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0008020004040000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.UINT32; - _valueSchema[1] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32, uint32) + Schema constant _valueSchema = Schema.wrap(0x0008020003030000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -87,14 +56,14 @@ library Vector2 { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/store/ts/codegen/field.ts b/packages/store/ts/codegen/field.ts index b9992e8ba7..ce62a59584 100644 --- a/packages/store/ts/codegen/field.ts +++ b/packages/store/ts/codegen/field.ts @@ -35,10 +35,10 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @notice Get ${field.name}${_commentSuffix}. */ function ${_methodNamePrefix}get${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - ])}) internal view returns (${_typedFieldName}) { + _typedStore, + _typedTableId, + _typedKeyArgs, + ])}) internal view returns (${_typedFieldName}) { ${_keyTupleDefinition} ${ field.isDynamic @@ -56,8 +56,8 @@ export function renderFieldMethods(options: RenderTableOptions): string { } return ${renderDecodeFieldSingle(field)}; } - ` - ) + `, + ), ); } @@ -79,7 +79,7 @@ export function renderFieldMethods(options: RenderTableOptions): string { ${_store}.${setFieldMethod}(${internalArguments}); } `; - }) + }), ); if (field.isDynamic) { @@ -97,14 +97,14 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @notice Get the length of ${field.name}${_commentSuffix}. */ function ${_methodNamePrefix}length${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - ])}) internal pure returns (uint256) { + _typedStore, + _typedTableId, + _typedKeyArgs, + ])}) internal pure returns (uint256) { return ${typeWrappingData.staticLength}; } - ` - ) + `, + ), ); } else { result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) => @@ -115,18 +115,18 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @notice Get the length of ${field.name}${_commentSuffix}. */ function ${_methodNamePrefix}length${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - ])}) internal view returns (uint256) { + _typedStore, + _typedTableId, + _typedKeyArgs, + ])}) internal view returns (uint256) { ${_keyTupleDefinition} uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex}); unchecked { return _byteLength / ${portionData.elementLength}; } } - ` - ) + `, + ), ); } @@ -139,11 +139,11 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @dev Reverts with Store_IndexOutOfBounds if \`_index\` is out of bounds for the array. */ function ${_methodNamePrefix}getItem${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - "uint256 _index", - ])}) internal view returns (${portionData.typeWithLocation}) { + _typedStore, + _typedTableId, + _typedKeyArgs, + "uint256 _index", + ])}) internal view returns (${portionData.typeWithLocation}) { ${_keyTupleDefinition} unchecked { bytes memory _blob = ${_store}.getDynamicFieldSlice( @@ -156,8 +156,8 @@ export function renderFieldMethods(options: RenderTableOptions): string { return ${portionData.decoded}; } } - ` - ) + `, + ), ); } @@ -170,16 +170,16 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @notice Push ${portionData.title} to ${field.name}${_commentSuffix}. */ function ${_methodNamePrefix}push${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - `${portionData.typeWithLocation} ${portionData.name}`, - ])}) internal { + _typedStore, + _typedTableId, + _typedKeyArgs, + `${portionData.typeWithLocation} ${portionData.name}`, + ])}) internal { ${_keyTupleDefinition} ${_store}.pushToDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.encoded}); } - ` - ) + `, + ), ); result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) => @@ -190,15 +190,15 @@ export function renderFieldMethods(options: RenderTableOptions): string { * @notice Pop ${portionData.title} from ${field.name}${_commentSuffix}. */ function ${_methodNamePrefix}pop${_methodNameSuffix}(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - ])}) internal { + _typedStore, + _typedTableId, + _typedKeyArgs, + ])}) internal { ${_keyTupleDefinition} ${_store}.popFromDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.elementLength}); } - ` - ) + `, + ), ); } @@ -233,7 +233,7 @@ export function renderFieldMethods(options: RenderTableOptions): string { } } `; - }) + }), ); } } diff --git a/packages/store/ts/codegen/record.ts b/packages/store/ts/codegen/record.ts index 7d190b8185..bd540d7068 100644 --- a/packages/store/ts/codegen/record.ts +++ b/packages/store/ts/codegen/record.ts @@ -27,10 +27,10 @@ export function renderRecordMethods(options: RenderTableOptions) { * @notice Get the full data${_commentSuffix}. */ function ${_methodNamePrefix}get(${renderArguments([ - _typedStore, - _typedTableId, - _typedKeyArgs, - ])}) internal view returns (${renderDecodedRecord(options)}) { + _typedStore, + _typedTableId, + _typedKeyArgs, + ])}) internal view returns (${renderDecodedRecord(options)}) { ${_keyTupleDefinition} ( @@ -40,7 +40,7 @@ export function renderRecordMethods(options: RenderTableOptions) { ) = ${_store}.getRecord(_tableId, _keyTuple, _fieldLayout); return decode(_staticData, _encodedLengths, _dynamicData); } - ` + `, ); } @@ -70,7 +70,7 @@ export function renderRecordMethods(options: RenderTableOptions) { ${_store}.setRecord(${internalArguments}); } `; - } + }, ); if (structName !== undefined) { @@ -100,7 +100,7 @@ export function renderRecordMethods(options: RenderTableOptions) { ${_store}.setRecord(${internalArguments}); } `; - } + }, ); } @@ -170,7 +170,7 @@ export function renderDeleteRecordMethods(options: RenderTableOptions) { ${_store}.deleteRecord(${internalArguments}); } `; - } + }, ); } @@ -202,13 +202,13 @@ function renderDecodeFunctions({ structName, fields, staticFields, dynamicFields * @notice Decode the tightly packed blob of static data using this table's field layout. */ function decodeStatic(bytes memory _blob) internal pure returns (${renderArguments( - staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) { ${renderList( staticFields, (field, index) => ` ${field.name} = ${renderDecodeValueType(field, staticOffsets[index])}; - ` + `, )} } `; @@ -220,7 +220,7 @@ function renderDecodeFunctions({ structName, fields, staticFields, dynamicFields * @notice Decode the tightly packed blob of dynamic data using the encoded lengths. */ function decodeDynamic(PackedCounter _encodedLengths, bytes memory _blob) internal pure returns (${renderArguments( - dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) { ${renderList( dynamicFields, @@ -245,7 +245,7 @@ function renderDecodeFunctions({ structName, fields, staticFields, dynamicFields ${field.name} = ${renderDecodeDynamicFieldPartial(field)}; `; } - } + }, )} } `; @@ -273,7 +273,7 @@ function renderDecodeFunctions({ structName, fields, staticFields, dynamicFields if (dynamicFields.length > 0) { result += ` (${renderArguments( - dynamicFields.map((field) => `${fieldNamePrefix}${field.name}`) + dynamicFields.map((field) => `${fieldNamePrefix}${field.name}`), )}) = decodeDynamic(_encodedLengths, _dynamicData); `; } diff --git a/packages/store/ts/codegen/renderFieldLayout.test.ts b/packages/store/ts/codegen/renderFieldLayout.test.ts index 38b8b4b6df..89c6663f74 100644 --- a/packages/store/ts/codegen/renderFieldLayout.test.ts +++ b/packages/store/ts/codegen/renderFieldLayout.test.ts @@ -35,23 +35,23 @@ describe("renderFieldLayout", () => { ]; expect(renderFieldLayout(fields)).toMatchInlineSnapshot( - '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x013418040102030405060708090a0b0c0d0e0f10111213141516172000000000);"' + '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x013418040102030405060708090a0b0c0d0e0f10111213141516172000000000);"', ); expect(renderFieldLayout([{ isDynamic: false, staticByteLength: 2 }])).toMatchInlineSnapshot( - '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0002010002000000000000000000000000000000000000000000000000000000);"' + '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0002010002000000000000000000000000000000000000000000000000000000);"', ); expect(renderFieldLayout([{ isDynamic: false, staticByteLength: 8 }])).toMatchInlineSnapshot( - '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0008010008000000000000000000000000000000000000000000000000000000);"' + '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0008010008000000000000000000000000000000000000000000000000000000);"', ); expect(renderFieldLayout([{ isDynamic: false, staticByteLength: 16 }])).toMatchInlineSnapshot( - '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0010010010000000000000000000000000000000000000000000000000000000);"' + '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0010010010000000000000000000000000000000000000000000000000000000);"', ); expect(renderFieldLayout([{ isDynamic: true, staticByteLength: 0 }])).toMatchInlineSnapshot( - '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000);"' + '"FieldLayout constant _fieldLayout = FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000);"', ); }); diff --git a/packages/store/ts/codegen/renderTable.ts b/packages/store/ts/codegen/renderTable.ts index 9bcd9fa05b..b67fc87650 100644 --- a/packages/store/ts/codegen/renderTable.ts +++ b/packages/store/ts/codegen/renderTable.ts @@ -14,6 +14,7 @@ import { renderEncodeFieldSingle, renderFieldMethods } from "./field"; import { renderDeleteRecordMethods, renderRecordData, renderRecordMethods } from "./record"; import { renderFieldLayout } from "./renderFieldLayout"; import { RenderTableOptions } from "./types"; +import { KeySchema, ValueSchema, keySchemaToHex, valueSchemaToHex } from "@latticexyz/protocol-parser"; /** * Renders Solidity code for a MUD table library, using the specified options @@ -40,9 +41,6 @@ export function renderTable(options: RenderTableOptions) { return ` ${renderedSolidityHeader} - // Import schema type - import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "${storeImportPath}IStore.sol"; import { StoreSwitch } from "${storeImportPath}StoreSwitch.sol"; @@ -51,8 +49,8 @@ export function renderTable(options: RenderTableOptions) { import { Memory } from "${storeImportPath}Memory.sol"; import { SliceLib } from "${storeImportPath}Slice.sol"; import { EncodeArray } from "${storeImportPath}tightcoder/EncodeArray.sol"; - import { FieldLayout, FieldLayoutLib } from "${storeImportPath}FieldLayout.sol"; - import { Schema, SchemaLib } from "${storeImportPath}Schema.sol"; + import { FieldLayout } from "${storeImportPath}FieldLayout.sol"; + import { Schema } from "${storeImportPath}Schema.sol"; import { PackedCounter, PackedCounterLib } from "${storeImportPath}PackedCounter.sol"; import { ResourceId } from "${storeImportPath}ResourceId.sol"; @@ -65,10 +63,6 @@ export function renderTable(options: RenderTableOptions) { : "" } - ${staticResourceData ? renderTableId(staticResourceData) : ""} - - ${renderFieldLayout(fields)} - ${ !structName ? "" @@ -80,35 +74,18 @@ export function renderTable(options: RenderTableOptions) { } library ${libraryName} { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](${keyTuple.length}); - ${renderList(keyTuple, ({ enumName }, index) => `_keySchema[${index}] = SchemaType.${enumName};`)} - - return SchemaLib.encode(_keySchema); - } - - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](${fields.length}); - ${renderList(fields, ({ enumName }, index) => `_valueSchema[${index}] = SchemaType.${enumName};`)} - - return SchemaLib.encode(_valueSchema); - } + ${staticResourceData ? renderTableId(staticResourceData) : ""} + + ${renderFieldLayout(fields)} + + // Hex-encoded key schema of (${keyTuple.map((field) => field.internalTypeId).join(", ")}) + Schema constant _keySchema = Schema.wrap(${keySchemaToHex( + Object.fromEntries(keyTuple.map((field) => [field.name, field.internalTypeId])) as KeySchema, + )}); + // Hex-encoded value schema of (${fields.map((field) => field.internalTypeId).join(", ")}) + Schema constant _valueSchema = Schema.wrap(${valueSchemaToHex( + Object.fromEntries(fields.map((field) => [field.name, field.internalTypeId])) as ValueSchema, + )}); /** * @notice Get the table's key field names. @@ -135,9 +112,9 @@ export function renderTable(options: RenderTableOptions) { * @notice Register the table with its config${_commentSuffix}. */ function ${_methodNamePrefix}register(${renderArguments([_typedStore, _typedTableId])}) internal { - ${_store}.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + ${_store}.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } - ` + `, )} ${renderFieldMethods(options)} @@ -159,7 +136,7 @@ export function renderTable(options: RenderTableOptions) { * @return The dynamic (variable length) data, encoded into a sequence of bytes. */ function encode(${renderArguments( - options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) internal pure returns (bytes memory, PackedCounter, bytes memory) { ${renderRecordData(options)} @@ -194,7 +171,7 @@ function renderEncodeStatic(staticFields: RenderStaticField[]) { * @return The static data, encoded into a sequence of bytes. */ function encodeStatic(${renderArguments( - staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) internal pure returns (bytes memory) { return abi.encodePacked(${renderArguments(staticFields.map(({ name }) => name))}); } @@ -216,7 +193,7 @@ function renderEncodeLengths(dynamicFields: RenderDynamicField[]) { * @return _encodedLengths The lengths of the dynamic fields (packed into a single bytes32 value). */ function encodeLengths(${renderArguments( - dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) internal pure returns (PackedCounter _encodedLengths) { // Lengths are effectively checked during copy by 2**40 bytes exceeding gas limits unchecked { @@ -228,7 +205,7 @@ function renderEncodeLengths(dynamicFields: RenderDynamicField[]) { } else { return `bytes(${name}).length`; } - }) + }), )} ); } @@ -251,7 +228,7 @@ function renderEncodeDynamic(dynamicFields: RenderDynamicField[]) { * @return The dynamic data, encoded into a sequence of bytes. */ function encodeDynamic(${renderArguments( - dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`) + dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`), )}) internal pure returns (bytes memory) { return abi.encodePacked(${renderArguments(dynamicFields.map((field) => renderEncodeFieldSingle(field)))}); } diff --git a/packages/store/ts/codegen/renderTableIndex.ts b/packages/store/ts/codegen/renderTableIndex.ts index 56c8be6376..1bb5a990f5 100644 --- a/packages/store/ts/codegen/renderTableIndex.ts +++ b/packages/store/ts/codegen/renderTableIndex.ts @@ -10,10 +10,9 @@ export function renderTableIndex(options: TableOptions[]) { return ` ${renderedSolidityHeader} - ${renderList(options, ({ outputPath, tableName, renderOptions: { structName, staticResourceData } }) => { + ${renderList(options, ({ outputPath, tableName, renderOptions: { structName } }) => { const imports = [tableName]; if (structName) imports.push(structName); - if (staticResourceData) imports.push(staticResourceData.tableIdName); return `import { ${imports.join(", ")} } from "./${posixPath(outputPath)}";`; })} diff --git a/packages/store/ts/codegen/tableOptions.ts b/packages/store/ts/codegen/tableOptions.ts index ce8425b349..208fc42e6e 100644 --- a/packages/store/ts/codegen/tableOptions.ts +++ b/packages/store/ts/codegen/tableOptions.ts @@ -26,7 +26,7 @@ export interface TableOptions { */ export function getTableOptions( config: StoreConfig, - solidityUserTypes: Record + solidityUserTypes: Record, ): TableOptions[] { const storeImportPath = config.storeImportPath; @@ -84,7 +84,6 @@ export function getTableOptions( const staticResourceData = tableData.tableIdArgument ? undefined : { - tableIdName: tableName + "TableId", namespace: config.namespace, name: tableData.name, offchainOnly: tableData.offchainOnly, diff --git a/packages/store/ts/codegen/tablegen.ts b/packages/store/ts/codegen/tablegen.ts index 18d0bcfb56..02cd7a62c2 100644 --- a/packages/store/ts/codegen/tablegen.ts +++ b/packages/store/ts/codegen/tablegen.ts @@ -15,7 +15,7 @@ export async function tablegen(config: StoreConfig, outputBaseDirectory: string, await Promise.all( uniqueTableDirectories.map(async (tableDir) => { await rm(path.join(outputBaseDirectory, tableDir), { recursive: true, force: true }); - }) + }), ); // write tables to files @@ -24,7 +24,7 @@ export async function tablegen(config: StoreConfig, outputBaseDirectory: string, const fullOutputPath = path.join(outputBaseDirectory, outputPath); const output = renderTable(renderOptions); await formatAndWriteSolidity(output, fullOutputPath, "Generated table"); - }) + }), ); // write table index diff --git a/packages/store/ts/codegen/tightcoder/renderDecodeSlice.ts b/packages/store/ts/codegen/tightcoder/renderDecodeSlice.ts index 3506405ac6..1e1518eaec 100644 --- a/packages/store/ts/codegen/tightcoder/renderDecodeSlice.ts +++ b/packages/store/ts/codegen/tightcoder/renderDecodeSlice.ts @@ -14,7 +14,8 @@ export function renderDecodeSlice() { import { Slice } from "../Slice.sol"; /** - * @title DecodeSlice Library + * @title DecodeSlice Library + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A library for decoding slices of data into specific data types. * @dev This library provides functions for decoding slices into arrays of basic uint types. */ @@ -24,7 +25,7 @@ export function renderDecodeSlice() { renderTightCoderDecode({ internalTypeId: staticAbiType, staticByteLength: staticAbiTypeToByteLength[staticAbiType], - }) + }), ) .join("\n")} } diff --git a/packages/store/ts/codegen/tightcoder/renderEncodeArray.ts b/packages/store/ts/codegen/tightcoder/renderEncodeArray.ts index 7e80df8537..27d894a2d4 100644 --- a/packages/store/ts/codegen/tightcoder/renderEncodeArray.ts +++ b/packages/store/ts/codegen/tightcoder/renderEncodeArray.ts @@ -13,7 +13,8 @@ export function renderEncodeArray() { import { TightCoder } from "./TightCoder.sol"; /** - * @title EncodeArray + * @title EncodeArray + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This library provides utilities for encoding arrays into tightly packed bytes representations. */ library EncodeArray { @@ -22,7 +23,7 @@ export function renderEncodeArray() { renderTightCoderEncode({ internalTypeId: staticAbiType, staticByteLength: staticAbiTypeToByteLength[staticAbiType], - }) + }), ) .join("\n")} } diff --git a/packages/store/ts/codegen/userType.ts b/packages/store/ts/codegen/userType.ts index 72e613df37..62b371c8d9 100644 --- a/packages/store/ts/codegen/userType.ts +++ b/packages/store/ts/codegen/userType.ts @@ -14,7 +14,7 @@ import { StoreConfig } from "../config"; export function resolveAbiOrUserType( abiOrUserType: string, config: StoreConfig, - solidityUserTypes: Record + solidityUserTypes: Record, ): { schemaType: SchemaType; renderType: RenderType; @@ -47,7 +47,7 @@ export function importForAbiOrUserType( abiOrUserType: string, usedInDirectory: string, config: StoreConfig, - solidityUserTypes: Record + solidityUserTypes: Record, ): ImportDatum | undefined { // abi types which directly mirror a SchemaType if (abiOrUserType in AbiTypeToSchemaType) { @@ -103,7 +103,7 @@ export function getSchemaTypeInfo(schemaType: SchemaType): RenderType { export function getUserTypeInfo( userType: string, config: StoreConfig, - solidityUserTypes: Record + solidityUserTypes: Record, ): { schemaType: SchemaType; renderType: RenderType; diff --git a/packages/store/ts/common.ts b/packages/store/ts/common.ts index a4d57e182c..5a9d1ebeb9 100644 --- a/packages/store/ts/common.ts +++ b/packages/store/ts/common.ts @@ -33,14 +33,14 @@ export type SchemaToPrimitives = { export type ConfigFieldTypeToSchemaAbiType> = T extends SchemaAbiType ? T : T extends `${string}[${string}]` - ? "uint8[]" - : "uint8"; + ? "uint8[]" + : "uint8"; export type ConfigFieldTypeToPrimitiveType> = T extends SchemaAbiType ? SchemaAbiTypeToPrimitiveType : T extends `${string}[${string}]` // field type might include enums and enum arrays, which are mapped to uint8/uint8[] - ? number[] // map enum arrays to `number[]` - : number; // map enums to `number` + ? number[] // map enum arrays to `number[]` + : number; // map enums to `number` /** Map a table schema config like `{ value: "uint256", type: "SomeEnum" }` to its primitive types like `{ value: bigint, type: number }` */ export type SchemaConfigToPrimitives = { @@ -56,12 +56,12 @@ export type ConfigToTablesPrimitives = { export type ConfigToKeyPrimitives< C extends StoreConfig, - Table extends keyof ConfigToTablesPrimitives + Table extends keyof ConfigToTablesPrimitives, > = ConfigToTablesPrimitives[Table]["key"]; export type ConfigToValuePrimitives< C extends StoreConfig, - Table extends keyof ConfigToTablesPrimitives + Table extends keyof ConfigToTablesPrimitives, > = ConfigToTablesPrimitives[Table]["value"]; export type ConfigToRecordPrimitives> = { diff --git a/packages/store/ts/config/experimental/resolveConfig.test-d.ts b/packages/store/ts/config/experimental/resolveConfig.test-d.ts index 0c5f5e52a3..80d8c8a960 100644 --- a/packages/store/ts/config/experimental/resolveConfig.test-d.ts +++ b/packages/store/ts/config/experimental/resolveConfig.test-d.ts @@ -29,7 +29,7 @@ describe("resolveConfig", () => { valueSchema: "ResourceType", }, }, - }) + }), ); expectTypeOf().toEqualTypeOf<"the-namespace">(); diff --git a/packages/store/ts/config/experimental/resolveConfig.test.ts b/packages/store/ts/config/experimental/resolveConfig.test.ts index d6187ca73c..c011aa1d01 100644 --- a/packages/store/ts/config/experimental/resolveConfig.test.ts +++ b/packages/store/ts/config/experimental/resolveConfig.test.ts @@ -25,7 +25,7 @@ const config = resolveConfig( valueSchema: "ResourceType", }, }, - }) + }), ); describe("resolveConfig", () => { @@ -35,7 +35,7 @@ describe("resolveConfig", () => { expect(config.tables.Shorthand.name).toEqual("Shorthand"); expect(config.tables.Shorthand.tableId).toEqual( - resourceToHex({ type: "table", namespace: "the-namespace", name: "Shorthand" }) + resourceToHex({ type: "table", namespace: "the-namespace", name: "Shorthand" }), ); expect(config.tables.Shorthand.keySchema).toEqual({ diff --git a/packages/store/ts/config/experimental/resolveConfig.ts b/packages/store/ts/config/experimental/resolveConfig.ts index 83354fa8f5..0d03e36884 100644 --- a/packages/store/ts/config/experimental/resolveConfig.ts +++ b/packages/store/ts/config/experimental/resolveConfig.ts @@ -26,7 +26,7 @@ type ResolvedTableConfig< TUserTypes extends UserTypesConfig["userTypes"], TEnumNames extends StringForUnion, TNamespace extends string = string, - TName extends string = string + TName extends string = string, > = { keySchema: ResolvedKeySchema; valueSchema: ResolvedValueSchema; @@ -38,34 +38,34 @@ type ResolvedTableConfig< type ResolvedKeySchema< TKeySchema extends TableConfig["keySchema"], TUserTypes extends UserTypesConfig["userTypes"], - TEnumNames extends StringForUnion + TEnumNames extends StringForUnion, > = ResolvedSchema; type ResolvedValueSchema< TValueSchema extends TableConfig["valueSchema"], TUserTypes extends UserTypesConfig["userTypes"], - TEnumNames extends StringForUnion + TEnumNames extends StringForUnion, > = ResolvedSchema, TUserTypes, TEnumNames>; type ResolvedSchema< TSchema extends Exclude, TUserTypes extends UserTypesConfig["userTypes"], - TEnumNames extends StringForUnion + TEnumNames extends StringForUnion, > = { [key in keyof TSchema]: { type: TSchema[key] extends SchemaAbiType ? TSchema[key] : TSchema[key] extends keyof TUserTypes - ? TUserTypes[TSchema[key]] extends UserType - ? // Note: we mistakenly named the plain ABI type "internalType", - // while in Solidity ABIs the plain ABI type is called "type" and - // and the custom type "internalType". We're planning to - // change our version and align with Solidity ABIs going forward. - TUserTypes[TSchema[key]]["internalType"] - : never - : TSchema[key] extends TEnumNames - ? "uint8" - : never; + ? TUserTypes[TSchema[key]] extends UserType + ? // Note: we mistakenly named the plain ABI type "internalType", + // while in Solidity ABIs the plain ABI type is called "type" and + // and the custom type "internalType". We're planning to + // change our version and align with Solidity ABIs going forward. + TUserTypes[TSchema[key]]["internalType"] + : never + : TSchema[key] extends TEnumNames + ? "uint8" + : never; internalType: TSchema[key]; }; }; @@ -75,7 +75,7 @@ type ResolvedSchema< * @deprecated Internal only */ export function resolveConfig( - config: TStoreConfig + config: TStoreConfig, ): ResolvedStoreConfig { const resolvedTables: Record> = {}; @@ -85,7 +85,7 @@ export function resolveConfig( config.userTypes, Object.keys(config.enums), config.namespace, - key + key, ) as ReturnType; } @@ -99,13 +99,13 @@ function resolveTable< TUserTypes extends UserTypesConfig["userTypes"], TEnums extends StringForUnion[], TNamespace extends string, - TName extends string + TName extends string, >( tableConfig: TTableConfig, userTypes: TUserTypes, enums: TEnums, namespace: TNamespace, - name: TName + name: TName, ): ResolvedTableConfig { const { keySchema, valueSchema } = tableConfig; @@ -125,11 +125,11 @@ function resolveTable< function resolveKeySchema< TKeySchema extends TableConfig["keySchema"], TUserTypes extends UserTypesConfig["userTypes"], - TEnums extends StringForUnion[] + TEnums extends StringForUnion[], >( keySchema: TKeySchema, userTypes: TUserTypes, - enums: TEnums + enums: TEnums, ): ResolvedKeySchema { const schema = ( keySchema == null ? { key: "bytes32" } : typeof keySchema === "string" ? { key: keySchema } : keySchema @@ -140,11 +140,11 @@ function resolveKeySchema< function resolveValueSchema< TValueSchema extends TableConfig["valueSchema"], TUserTypes extends UserTypesConfig["userTypes"], - TEnums extends StringForUnion[] + TEnums extends StringForUnion[], >( valueSchema: TValueSchema, userTypes: TUserTypes, - enums: TEnums + enums: TEnums, ): ResolvedValueSchema { const schema = ( typeof valueSchema === "string" ? ({ value: valueSchema } as unknown as TValueSchema) : valueSchema @@ -155,7 +155,7 @@ function resolveValueSchema< function resolveSchema< TSchema extends Exclude | TableConfig["valueSchema"], string>, TUserTypes extends UserTypesConfig["userTypes"], - TEnums extends StringForUnion[] + TEnums extends StringForUnion[], >(schema: TSchema, userTypes: TUserTypes, enums: TEnums): ResolvedSchema { return mapObject>(schema, (value, key) => { const isUserType = userTypes && value in userTypes; diff --git a/packages/store/ts/config/storeConfig.ts b/packages/store/ts/config/storeConfig.ts index 01c2b5e002..dc474f4f49 100644 --- a/packages/store/ts/config/storeConfig.ts +++ b/packages/store/ts/config/storeConfig.ts @@ -73,7 +73,7 @@ export const zSchemaConfig = zFullSchemaConfig.or(zShorthandSchemaConfig); type ResolvedSchema< TSchema extends Record, - TUserTypes extends Record> + TUserTypes extends Record>, > = { [key in keyof TSchema]: TSchema[key] extends keyof TUserTypes ? TUserTypes[TSchema[key]]["internalType"] @@ -84,7 +84,7 @@ type ResolvedSchema< // (see https://github.com/latticexyz/mud/pull/1588) export function resolveUserTypes< TSchema extends Record, - TUserTypes extends Record> + TUserTypes extends Record>, >(schema: TSchema, userTypes: TUserTypes): ResolvedSchema { const resolvedSchema: Record = {}; for (const [key, value] of Object.entries(schema)) { @@ -109,7 +109,7 @@ export function resolveUserTypes< export interface TableConfig< UserTypes extends StringForUnion = StringForUnion, - StaticUserTypes extends StringForUnion = StringForUnion + StaticUserTypes extends StringForUnion = StringForUnion, > { /** Output directory path for the file. Default is "tables" */ directory?: string; @@ -136,7 +136,7 @@ export interface TableConfig< export type FullTableConfig< UserTypes extends StringForUnion = StringForUnion, - StaticUserTypes extends StringForUnion = StringForUnion + StaticUserTypes extends StringForUnion = StringForUnion, > = Required> & { valueSchema: FullSchemaConfig; }; @@ -197,7 +197,7 @@ export const zTableConfig = zFullTableConfig.or(zShorthandTableConfig); export type TablesConfig< UserTypes extends StringForUnion = StringForUnion, - StaticUserTypes extends StringForUnion = StringForUnion + StaticUserTypes extends StringForUnion = StringForUnion, > = Record | FieldData>; export const zTablesConfig = z.record(zTableName, zTableConfig).transform((tables) => { @@ -213,17 +213,17 @@ export const zTablesConfig = z.record(zTableName, zTableConfig).transform((table export type FullTablesConfig< UserTypes extends StringForUnion = StringForUnion, - StaticUserTypes extends StringForUnion = StringForUnion + StaticUserTypes extends StringForUnion = StringForUnion, > = Record>; export type ExpandTablesConfig> = { [TableName in keyof T]: T[TableName] extends FieldData ? ExpandTableConfig<{ valueSchema: { value: T[TableName] } }, TableName extends string ? TableName : never> : T[TableName] extends TableConfig - ? ExpandTableConfig - : // Weakly typed values get a weakly typed expansion. - // This shouldn't normally happen within `mudConfig`, but can be manually triggered via `ExpandMUDUserConfig` - ExpandTableConfig, TableName extends string ? TableName : string>; + ? ExpandTableConfig + : // Weakly typed values get a weakly typed expansion. + // This shouldn't normally happen within `mudConfig`, but can be manually triggered via `ExpandMUDUserConfig` + ExpandTableConfig, TableName extends string ? TableName : string>; }; /************************************************************************ @@ -242,22 +242,22 @@ export type EnumsConfig = never extends EnumNa enums?: Record; } : StringForUnion extends EnumNames - ? { - /** - * Enum names mapped to lists of their member names - * - * (enums aren't inferred - use `mudConfig` or `storeConfig` helper, and `as const` for variables) - */ - enums?: Record; - } - : { - /** - * Enum names mapped to lists of their member names - * - * Enums defined here can be used as types in table schemas/keys - */ - enums: Record; - }; + ? { + /** + * Enum names mapped to lists of their member names + * + * (enums aren't inferred - use `mudConfig` or `storeConfig` helper, and `as const` for variables) + */ + enums?: Record; + } + : { + /** + * Enum names mapped to lists of their member names + * + * Enums defined here can be used as types in table schemas/keys + */ + enums: Record; + }; export type FullEnumsConfig = { enums: Record; @@ -285,26 +285,26 @@ export type UserTypesConfig; } : StringForUnion extends UserTypeNames - ? { - /** - * User types mapped to file paths from which to import them. - * Paths are treated as relative to root. - * Paths that don't start with a "." have foundry remappings applied to them first. - * - * (user types aren't inferred - use `mudConfig` or `storeConfig` helper, and `as const` for variables) - */ - userTypes?: Record; - } - : { - /** - * User types mapped to file paths from which to import them. - * Paths are treated as relative to root. - * Paths that don't start with a "." have foundry remappings applied to them first. - * - * User types defined here can be used as types in table schemas/keys - */ - userTypes: Record; - }; + ? { + /** + * User types mapped to file paths from which to import them. + * Paths are treated as relative to root. + * Paths that don't start with a "." have foundry remappings applied to them first. + * + * (user types aren't inferred - use `mudConfig` or `storeConfig` helper, and `as const` for variables) + */ + userTypes?: Record; + } + : { + /** + * User types mapped to file paths from which to import them. + * Paths are treated as relative to root. + * Paths that don't start with a "." have foundry remappings applied to them first. + * + * User types defined here can be used as types in table schemas/keys + */ + userTypes: Record; + }; const zUserTypeConfig = z.object({ filePath: z.string(), @@ -327,7 +327,7 @@ export type MUDUserConfig< T extends MUDCoreUserConfig = MUDCoreUserConfig, EnumNames extends StringForUnion = StringForUnion, UserTypeNames extends StringForUnion = StringForUnion, - StaticUserTypes extends ExtractUserTypes = ExtractUserTypes + StaticUserTypes extends ExtractUserTypes = ExtractUserTypes, > = T & EnumsConfig & UserTypesConfig & { @@ -404,7 +404,7 @@ function validateStoreConfig(config: z.output, ctx: ctx.addIssue({ code: ZodIssueCode.custom, message: `Table library names, enum names, user type names must be globally unique: ${duplicateGlobalNames.join( - ", " + ", ", )}`, }); } @@ -432,7 +432,7 @@ function validateAbiOrUserType( userTypeNames: string[], staticUserTypeNames: string[], type: string, - ctx: RefinementCtx + ctx: RefinementCtx, ) { if (!(AbiTypes as string[]).includes(type) && !userTypeNames.includes(type)) { const staticArray = parseStaticArray(type); @@ -460,7 +460,7 @@ function validateStaticArray( staticUserTypeNames: string[], elementType: string, staticLength: number, - ctx: RefinementCtx + ctx: RefinementCtx, ) { validateStaticAbiOrUserType(staticUserTypeNames, elementType, ctx); diff --git a/packages/store/ts/register/mudConfig.ts b/packages/store/ts/register/mudConfig.ts index 907ef5fb1c..4ac0be54d4 100644 --- a/packages/store/ts/register/mudConfig.ts +++ b/packages/store/ts/register/mudConfig.ts @@ -9,7 +9,7 @@ export function mudConfig< // (`never` is overridden by inference, so only the defined enums can be used by default) EnumNames extends StringForUnion = never, UserTypeNames extends StringForUnion = never, - StaticUserTypes extends ExtractUserTypes = ExtractUserTypes + StaticUserTypes extends ExtractUserTypes = ExtractUserTypes, >(config: MUDUserConfig): ExpandMUDUserConfig { // eslint-disable-next-line @typescript-eslint/no-explicit-any return mudCoreConfig(config) as any; diff --git a/packages/store/ts/scripts/generate-tightcoder.ts b/packages/store/ts/scripts/generate-tightcoder.ts index dd95ddb9bb..d4f0a56579 100644 --- a/packages/store/ts/scripts/generate-tightcoder.ts +++ b/packages/store/ts/scripts/generate-tightcoder.ts @@ -6,5 +6,5 @@ await formatAndWriteSolidity(renderEncodeArray(), "src/tightcoder/EncodeArray.so await formatAndWriteSolidity( renderTightCoderAutoTest(), "test/tightcoder/TightCoderAuto.t.sol", - "Generated TightCoderAutoTest" + "Generated TightCoderAutoTest", ); diff --git a/packages/store/ts/storeEvents.test.ts b/packages/store/ts/storeEvents.test.ts index b7361f5664..e4e7c06daf 100644 --- a/packages/store/ts/storeEvents.test.ts +++ b/packages/store/ts/storeEvents.test.ts @@ -20,7 +20,7 @@ describe("Store events", () => { for (const storeEvent of storeEvents) { const parsedStoreEvent = parseAbiItem(storeEvent); const abiItem = IStoreAbi.find( - (item) => item.type === parsedStoreEvent.type && item.name === parsedStoreEvent.name + (item) => item.type === parsedStoreEvent.type && item.name === parsedStoreEvent.name, ); expect(abiItem).not.toBeUndefined(); expect(normalizeAbiEvent(parsedStoreEvent)).toMatchObject(normalizeAbiEvent(abiItem as AbiEvent)); diff --git a/packages/utils/src/bytes.ts b/packages/utils/src/bytes.ts index c90728e7b9..659cda462f 100644 --- a/packages/utils/src/bytes.ts +++ b/packages/utils/src/bytes.ts @@ -20,7 +20,7 @@ export function concatUint8Arrays(...arrays: Uint8Array[]): Uint8Array { return Uint8Array.from( arrays.reduce((acc, curr) => { return [...acc, ...curr]; - }, []) + }, []), ); } diff --git a/packages/utils/src/cubic.ts b/packages/utils/src/cubic.ts index 611da1a9b5..bddb47e232 100644 --- a/packages/utils/src/cubic.ts +++ b/packages/utils/src/cubic.ts @@ -30,7 +30,7 @@ export function cubicNoiseConfig( octave: number, scale: number, periodX = Number.MAX_SAFE_INTEGER, - periodY = Number.MAX_SAFE_INTEGER + periodY = Number.MAX_SAFE_INTEGER, ) { return { seed: Math.floor(seed * Number.MAX_SAFE_INTEGER), @@ -59,7 +59,7 @@ export function cubicNoiseSample1(config: ReturnType, x randomize(config.seed, tile(xi + 2, config.periodX), 0), lerp, 1, - 1 + 1, ) * 0.666666 + 0.166666 @@ -76,7 +76,7 @@ export function cubicNoiseSample1(config: ReturnType, x export function cubicNoiseSample2( { octave, periodX, periodY, seed, scale }: ReturnType, x: number, - y: number + y: number, ) { const xi = Math.floor(x / octave); const lerpX = Math.floor((x * ACCURACY) / octave) - xi * ACCURACY; @@ -99,11 +99,11 @@ export function cubicNoiseSample2( randomize(seed, x3, y), lerpX, ACCURACY, - 1 + 1, ); } return Math.floor( - interpolate(xSamples[0], xSamples[1], xSamples[2], xSamples[3], lerpY, ACCURACY, scale) / Math.pow(ACCURACY, 6) + interpolate(xSamples[0], xSamples[1], xSamples[2], xSamples[3], lerpY, ACCURACY, scale) / Math.pow(ACCURACY, 6), ); } diff --git a/packages/utils/src/mobx.ts b/packages/utils/src/mobx.ts index 659c28fa54..40583c831c 100644 --- a/packages/utils/src/mobx.ts +++ b/packages/utils/src/mobx.ts @@ -15,7 +15,7 @@ export async function awaitValue(comp: IComputedValue | IObser resolve(value); } }, - { fireImmediately: true } + { fireImmediately: true }, ); const value = await promise; diff --git a/packages/utils/src/objects.ts b/packages/utils/src/objects.ts index fc491bb3c5..8b75d21d22 100644 --- a/packages/utils/src/objects.ts +++ b/packages/utils/src/objects.ts @@ -6,7 +6,7 @@ */ export function mapObject( source: S, - valueMap: (value: S[keyof S], key: keyof S) => T[keyof S] + valueMap: (value: S[keyof S], key: keyof S) => T[keyof S], ): T { const target: Partial<{ [key in keyof typeof source]: T[keyof S] }> = {}; for (const key in source) { diff --git a/packages/utils/src/promise.ts b/packages/utils/src/promise.ts index fcd11bd2a6..0af015a14b 100644 --- a/packages/utils/src/promise.ts +++ b/packages/utils/src/promise.ts @@ -20,7 +20,7 @@ export const callWithRetry = ( fn: (...args: any[]) => Promise, args: any[] = [], maxRetries = 10, - retryInterval = 1000 + retryInterval = 1000, ): Promise => { const [resolve, reject, promise] = deferred(); const process = async () => { diff --git a/packages/utils/src/proxy.ts b/packages/utils/src/proxy.ts index dc41151af6..85c599c21c 100644 --- a/packages/utils/src/proxy.ts +++ b/packages/utils/src/proxy.ts @@ -20,7 +20,7 @@ function deepAccess(target: Record, path: string[]): any { * @returns Cached */ export function cacheUntilReady>( - target: IObservableValue | IComputedValue + target: IObservableValue | IComputedValue, ): Cached { // The call queue contains the path and arguments of calls to the // proxiedTarget while the target was not available yet. @@ -71,7 +71,7 @@ export function cacheUntilReady>( return promise; } }, - } + }, ); reaction( @@ -94,7 +94,7 @@ export function cacheUntilReady>( resolve(target); } } - } + }, ); return proxiedTarget as Cached; diff --git a/packages/utils/src/rx.ts b/packages/utils/src/rx.ts index b18835a6b4..7a37b1f24a 100644 --- a/packages/utils/src/rx.ts +++ b/packages/utils/src/rx.ts @@ -19,7 +19,7 @@ import { awaitValue } from "./mobx"; export function filterNullish(): OperatorFunction> { return pipe, Observable>>( - filter((x: T) => x != null) as OperatorFunction> + filter((x: T) => x != null) as OperatorFunction>, ); } @@ -50,7 +50,7 @@ export function stretch(spacingDelayMs: number) { }; }, null), filterNullish(), - mergeMap((i) => of(i.value).pipe(delay(i.delay)), 1) + mergeMap((i) => of(i.value).pipe(delay(i.delay)), 1), ); } @@ -65,7 +65,7 @@ export function computedToStream(comp: IComputedValue | IObservableValue { if (value != null) stream.next(value); }, - { fireImmediately: true } + { fireImmediately: true }, ); return stream; } @@ -77,7 +77,7 @@ export function observableToStream(obs: T): Observable { (value) => { if (value != null) stream.next(value); }, - { fireImmediately: true } + { fireImmediately: true }, ); return stream; } @@ -104,7 +104,7 @@ export async function streamToDefinedComputed(stream$: Observable): Promis */ export async function awaitStreamValue( stream$: Observable, - predicate: (value: T) => boolean = (value) => value != null + predicate: (value: T) => boolean = (value) => value != null, ): Promise { const [resolve, , promise] = deferred(); stream$.pipe(first(predicate)).subscribe(resolve); diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts index 1649769316..b9c1f99a4a 100644 --- a/packages/utils/src/types.ts +++ b/packages/utils/src/types.ts @@ -8,13 +8,13 @@ export type CachedValue = Proxied extends true ? V extends Func ? AsyncFunc : V extends Record - ? Cached & { proxied: true } - : { proxied: true } + ? Cached & { proxied: true } + : { proxied: true } : V extends Func - ? Func - : V extends Record - ? V - : V & { proxied: false }; + ? Func + : V extends Record + ? V + : V & { proxied: false }; export type Cached = | ({ proxied: false } & { [key in keyof C]: CachedValue }) diff --git a/packages/world-modules/gas-report.json b/packages/world-modules/gas-report.json index 1e887a7bd8..5c555d87b2 100644 --- a/packages/world-modules/gas-report.json +++ b/packages/world-modules/gas-report.json @@ -75,13 +75,13 @@ "file": "test/KeysInTableModule.t.sol", "test": "testInstallComposite", "name": "install keys in table module", - "gasUsed": 1467040 + "gasUsed": 1456815 }, { "file": "test/KeysInTableModule.t.sol", "test": "testInstallGas", "name": "install keys in table module", - "gasUsed": 1467040 + "gasUsed": 1456815 }, { "file": "test/KeysInTableModule.t.sol", @@ -93,13 +93,13 @@ "file": "test/KeysInTableModule.t.sol", "test": "testInstallSingleton", "name": "install keys in table module", - "gasUsed": 1467040 + "gasUsed": 1456815 }, { "file": "test/KeysInTableModule.t.sol", "test": "testSetAndDeleteRecordHookCompositeGas", "name": "install keys in table module", - "gasUsed": 1467040 + "gasUsed": 1456815 }, { "file": "test/KeysInTableModule.t.sol", @@ -117,7 +117,7 @@ "file": "test/KeysInTableModule.t.sol", "test": "testSetAndDeleteRecordHookGas", "name": "install keys in table module", - "gasUsed": 1467040 + "gasUsed": 1456815 }, { "file": "test/KeysInTableModule.t.sol", @@ -135,7 +135,7 @@ "file": "test/KeysWithValueModule.t.sol", "test": "testGetKeysWithValueGas", "name": "install keys with value module", - "gasUsed": 719126 + "gasUsed": 715762 }, { "file": "test/KeysWithValueModule.t.sol", @@ -153,7 +153,7 @@ "file": "test/KeysWithValueModule.t.sol", "test": "testInstall", "name": "install keys with value module", - "gasUsed": 719126 + "gasUsed": 715762 }, { "file": "test/KeysWithValueModule.t.sol", @@ -165,7 +165,7 @@ "file": "test/KeysWithValueModule.t.sol", "test": "testSetAndDeleteRecordHook", "name": "install keys with value module", - "gasUsed": 719126 + "gasUsed": 715762 }, { "file": "test/KeysWithValueModule.t.sol", @@ -183,7 +183,7 @@ "file": "test/KeysWithValueModule.t.sol", "test": "testSetField", "name": "install keys with value module", - "gasUsed": 719126 + "gasUsed": 715762 }, { "file": "test/KeysWithValueModule.t.sol", @@ -303,7 +303,7 @@ "file": "test/UniqueEntityModule.t.sol", "test": "testInstall", "name": "install unique entity module", - "gasUsed": 713209 + "gasUsed": 710507 }, { "file": "test/UniqueEntityModule.t.sol", @@ -315,7 +315,7 @@ "file": "test/UniqueEntityModule.t.sol", "test": "testInstallRoot", "name": "installRoot unique entity module", - "gasUsed": 683678 + "gasUsed": 680976 }, { "file": "test/UniqueEntityModule.t.sol", diff --git a/packages/world-modules/src/index.sol b/packages/world-modules/src/index.sol index 3602fdb1bd..138d5a9e37 100644 --- a/packages/world-modules/src/index.sol +++ b/packages/world-modules/src/index.sol @@ -4,12 +4,12 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ import { KeysWithValue } from "./modules/keyswithvalue/tables/KeysWithValue.sol"; -import { KeysInTable, KeysInTableData, KeysInTableTableId } from "./modules/keysintable/tables/KeysInTable.sol"; -import { UsedKeysIndex, UsedKeysIndexTableId } from "./modules/keysintable/tables/UsedKeysIndex.sol"; +import { KeysInTable, KeysInTableData } from "./modules/keysintable/tables/KeysInTable.sol"; +import { UsedKeysIndex } from "./modules/keysintable/tables/UsedKeysIndex.sol"; import { UniqueEntity } from "./modules/uniqueentity/tables/UniqueEntity.sol"; -import { CallboundDelegations, CallboundDelegationsTableId } from "./modules/std-delegations/tables/CallboundDelegations.sol"; -import { SystemboundDelegations, SystemboundDelegationsTableId } from "./modules/std-delegations/tables/SystemboundDelegations.sol"; -import { TimeboundDelegations, TimeboundDelegationsTableId } from "./modules/std-delegations/tables/TimeboundDelegations.sol"; +import { CallboundDelegations } from "./modules/std-delegations/tables/CallboundDelegations.sol"; +import { SystemboundDelegations } from "./modules/std-delegations/tables/SystemboundDelegations.sol"; +import { TimeboundDelegations } from "./modules/std-delegations/tables/TimeboundDelegations.sol"; import { PuppetRegistry } from "./modules/puppet/tables/PuppetRegistry.sol"; import { Balances } from "./modules/tokens/tables/Balances.sol"; import { ERC20Metadata, ERC20MetadataData } from "./modules/erc20-puppet/tables/ERC20Metadata.sol"; diff --git a/packages/world-modules/src/interfaces/IBaseWorld.sol b/packages/world-modules/src/interfaces/IBaseWorld.sol index 554767a8a4..c71f2becc9 100644 --- a/packages/world-modules/src/interfaces/IBaseWorld.sol +++ b/packages/world-modules/src/interfaces/IBaseWorld.sol @@ -8,10 +8,9 @@ import { IWorldKernel } from "@latticexyz/world/src/IWorldKernel.sol"; /** * @title IBaseWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IBaseWorld is IStore, IWorldKernel { - -} +interface IBaseWorld is IStore, IWorldKernel {} diff --git a/packages/world-modules/src/interfaces/IERC20System.sol b/packages/world-modules/src/interfaces/IERC20System.sol index 80ab29773d..18a6bd63a7 100644 --- a/packages/world-modules/src/interfaces/IERC20System.sol +++ b/packages/world-modules/src/interfaces/IERC20System.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IERC20System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IERC20System { diff --git a/packages/world-modules/src/interfaces/IPuppetFactorySystem.sol b/packages/world-modules/src/interfaces/IPuppetFactorySystem.sol index c64bb25ff3..773b02e31b 100644 --- a/packages/world-modules/src/interfaces/IPuppetFactorySystem.sol +++ b/packages/world-modules/src/interfaces/IPuppetFactorySystem.sol @@ -7,6 +7,7 @@ import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; /** * @title IPuppetFactorySystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IPuppetFactorySystem { diff --git a/packages/world-modules/src/modules/erc20-puppet/ERC20Module.sol b/packages/world-modules/src/modules/erc20-puppet/ERC20Module.sol index 3fce7e97cd..4a4c84e595 100644 --- a/packages/world-modules/src/modules/erc20-puppet/ERC20Module.sol +++ b/packages/world-modules/src/modules/erc20-puppet/ERC20Module.sol @@ -75,9 +75,7 @@ contract ERC20ModuleRegistrationLibrary { function register(IBaseWorld world, bytes14 namespace) public { // Register the namespace if it doesn't exist yet ResourceId tokenNamespace = WorldResourceIdLib.encodeNamespace(namespace); - if (!ResourceIds.getExists(tokenNamespace)) { - world.registerNamespace(tokenNamespace); - } + world.registerNamespace(tokenNamespace); // Register the tables Allowances.register(_allowancesTableId(namespace)); diff --git a/packages/world-modules/src/modules/erc20-puppet/tables/Allowances.sol b/packages/world-modules/src/modules/erc20-puppet/tables/Allowances.sol index e803d156a2..f8b2fb9b23 100644 --- a/packages/world-modules/src/modules/erc20-puppet/tables/Allowances.sol +++ b/packages/world-modules/src/modules/erc20-puppet/tables/Allowances.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,46 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library Allowances { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address) + Schema constant _keySchema = Schema.wrap(0x0028020061610000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +48,14 @@ library Allowances { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Metadata.sol b/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Metadata.sol index 2786f6afcf..830107f1bf 100644 --- a/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Metadata.sol +++ b/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Metadata.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,15 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010201000000000000000000000000000000000000000000000000000000 -); - struct ERC20MetadataData { uint8 decimals; string name; @@ -30,36 +23,13 @@ struct ERC20MetadataData { } library ERC20Metadata { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010201000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](3); - _valueSchema[0] = SchemaType.UINT8; - _valueSchema[1] = SchemaType.STRING; - _valueSchema[2] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint8, string, string) + Schema constant _valueSchema = Schema.wrap(0x0001010200c5c500000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -84,14 +54,14 @@ library ERC20Metadata { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Registry.sol b/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Registry.sol index a257de1880..85737c4120 100644 --- a/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Registry.sol +++ b/packages/world-modules/src/modules/erc20-puppet/tables/ERC20Registry.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library ERC20Registry { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -79,14 +50,14 @@ library ERC20Registry { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc20-puppet/tables/TotalSupply.sol b/packages/world-modules/src/modules/erc20-puppet/tables/TotalSupply.sol index eaf6762370..a633aff8ec 100644 --- a/packages/world-modules/src/modules/erc20-puppet/tables/TotalSupply.sol +++ b/packages/world-modules/src/modules/erc20-puppet/tables/TotalSupply.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,44 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library TotalSupply { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -74,14 +46,14 @@ library TotalSupply { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/ERC721Module.sol b/packages/world-modules/src/modules/erc721-puppet/ERC721Module.sol index 78e7c5ef91..33cbb8d858 100644 --- a/packages/world-modules/src/modules/erc721-puppet/ERC721Module.sol +++ b/packages/world-modules/src/modules/erc721-puppet/ERC721Module.sol @@ -79,9 +79,7 @@ contract ERC721ModuleRegistrationLibrary { function register(IBaseWorld world, bytes14 namespace) public { // Register the namespace if it doesn't exist yet ResourceId tokenNamespace = WorldResourceIdLib.encodeNamespace(namespace); - if (!ResourceIds.getExists(tokenNamespace)) { - world.registerNamespace(tokenNamespace); - } + world.registerNamespace(tokenNamespace); // Register the tables OperatorApproval.register(_operatorApprovalTableId(namespace)); diff --git a/packages/world-modules/src/modules/erc721-puppet/IERC721Metadata.sol b/packages/world-modules/src/modules/erc721-puppet/IERC721Metadata.sol index 9991672c81..263c0498b5 100644 --- a/packages/world-modules/src/modules/erc721-puppet/IERC721Metadata.sol +++ b/packages/world-modules/src/modules/erc721-puppet/IERC721Metadata.sol @@ -6,6 +6,7 @@ import { IERC721 } from "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { diff --git a/packages/world-modules/src/modules/erc721-puppet/IERC721Receiver.sol b/packages/world-modules/src/modules/erc721-puppet/IERC721Receiver.sol index 136fbeb4c3..d6bd419f9b 100644 --- a/packages/world-modules/src/modules/erc721-puppet/IERC721Receiver.sol +++ b/packages/world-modules/src/modules/erc721-puppet/IERC721Receiver.sol @@ -4,6 +4,7 @@ pragma solidity >=0.8.24; /** * @title ERC721 token receiver interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Metadata.sol b/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Metadata.sol index 42967867a1..dd43390ec5 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Metadata.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Metadata.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,15 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000300000000000000000000000000000000000000000000000000000000 -); - struct ERC721MetadataData { string name; string symbol; @@ -30,36 +23,13 @@ struct ERC721MetadataData { } library ERC721Metadata { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000300000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](3); - _valueSchema[0] = SchemaType.STRING; - _valueSchema[1] = SchemaType.STRING; - _valueSchema[2] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (string, string, string) + Schema constant _valueSchema = Schema.wrap(0x00000003c5c5c500000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -84,14 +54,14 @@ library ERC721Metadata { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Registry.sol b/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Registry.sol index 9b1b0b7a46..59b1a502f9 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Registry.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/ERC721Registry.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library ERC721Registry { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -79,14 +50,14 @@ library ERC721Registry { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/OperatorApproval.sol b/packages/world-modules/src/modules/erc721-puppet/tables/OperatorApproval.sol index f8ed7b9a51..561f31d6ca 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/OperatorApproval.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/OperatorApproval.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,46 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library OperatorApproval { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address) + Schema constant _keySchema = Schema.wrap(0x0028020061610000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +48,14 @@ library OperatorApproval { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/Owners.sol b/packages/world-modules/src/modules/erc721-puppet/tables/Owners.sol index 9fd9b9d7ac..abb43fed8c 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/Owners.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/Owners.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library Owners { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint256) + Schema constant _keySchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,14 +47,14 @@ library Owners { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/TokenApproval.sol b/packages/world-modules/src/modules/erc721-puppet/tables/TokenApproval.sol index 81b050e9cd..8427e9e2ba 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/TokenApproval.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/TokenApproval.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library TokenApproval { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint256) + Schema constant _keySchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,14 +47,14 @@ library TokenApproval { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/erc721-puppet/tables/TokenURI.sol b/packages/world-modules/src/modules/erc721-puppet/tables/TokenURI.sol index 6a93a319da..def9646cfb 100644 --- a/packages/world-modules/src/modules/erc721-puppet/tables/TokenURI.sol +++ b/packages/world-modules/src/modules/erc721-puppet/tables/TokenURI.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library TokenURI { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (uint256) + Schema constant _keySchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (string) + Schema constant _valueSchema = Schema.wrap(0x00000001c5000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,14 +47,14 @@ library TokenURI { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/keysintable/KeysInTableModule.sol b/packages/world-modules/src/modules/keysintable/KeysInTableModule.sol index d81268304b..295129885d 100644 --- a/packages/world-modules/src/modules/keysintable/KeysInTableModule.sol +++ b/packages/world-modules/src/modules/keysintable/KeysInTableModule.sol @@ -13,8 +13,8 @@ import { ResourceId, WorldResourceIdInstance } from "@latticexyz/world/src/World import { revertWithBytes } from "@latticexyz/world/src/revertWithBytes.sol"; import { KeysInTableHook } from "./KeysInTableHook.sol"; -import { KeysInTable, KeysInTableTableId } from "./tables/KeysInTable.sol"; -import { UsedKeysIndex, UsedKeysIndexTableId } from "./tables/UsedKeysIndex.sol"; +import { KeysInTable } from "./tables/KeysInTable.sol"; +import { UsedKeysIndex } from "./tables/UsedKeysIndex.sol"; /** * This module deploys a hook that is called when a value is set in the `sourceTableId` @@ -47,16 +47,16 @@ contract KeysInTableModule is Module { bool success; bytes memory returnData; - if (!ResourceIds._getExists(KeysInTableTableId)) { + if (!ResourceIds._getExists(KeysInTable._tableId)) { // Register the tables (success, returnData) = address(world).delegatecall( abi.encodeCall( world.registerTable, ( - KeysInTableTableId, - KeysInTable.getFieldLayout(), - KeysInTable.getKeySchema(), - KeysInTable.getValueSchema(), + KeysInTable._tableId, + KeysInTable._fieldLayout, + KeysInTable._keySchema, + KeysInTable._valueSchema, KeysInTable.getKeyNames(), KeysInTable.getFieldNames() ) @@ -68,10 +68,10 @@ contract KeysInTableModule is Module { abi.encodeCall( world.registerTable, ( - UsedKeysIndexTableId, - UsedKeysIndex.getFieldLayout(), - UsedKeysIndex.getKeySchema(), - UsedKeysIndex.getValueSchema(), + UsedKeysIndex._tableId, + UsedKeysIndex._fieldLayout, + UsedKeysIndex._keySchema, + UsedKeysIndex._valueSchema, UsedKeysIndex.getKeyNames(), UsedKeysIndex.getFieldNames() ) @@ -81,12 +81,12 @@ contract KeysInTableModule is Module { // Grant the hook access to the tables (success, returnData) = address(world).delegatecall( - abi.encodeCall(world.grantAccess, (KeysInTableTableId, address(hook))) + abi.encodeCall(world.grantAccess, (KeysInTable._tableId, address(hook))) ); if (!success) revertWithBytes(returnData); (success, returnData) = address(world).delegatecall( - abi.encodeCall(world.grantAccess, (UsedKeysIndexTableId, address(hook))) + abi.encodeCall(world.grantAccess, (UsedKeysIndex._tableId, address(hook))) ); if (!success) revertWithBytes(returnData); } diff --git a/packages/world-modules/src/modules/keysintable/tables/KeysInTable.sol b/packages/world-modules/src/modules/keysintable/tables/KeysInTable.sol index a2352e77ca..f3cc092eb6 100644 --- a/packages/world-modules/src/modules/keysintable/tables/KeysInTable.sol +++ b/packages/world-modules/src/modules/keysintable/tables/KeysInTable.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,22 +11,14 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "KeysInTable", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004b657973496e5461626c650000000000); -ResourceId constant KeysInTableTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000500000000000000000000000000000000000000000000000000000000 -); - struct KeysInTableData { bytes32[] keys0; bytes32[] keys1; @@ -39,39 +28,16 @@ struct KeysInTableData { } library KeysInTable { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "KeysInTable", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000004b657973496e5461626c650000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000500000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](5); - _valueSchema[0] = SchemaType.BYTES32_ARRAY; - _valueSchema[1] = SchemaType.BYTES32_ARRAY; - _valueSchema[2] = SchemaType.BYTES32_ARRAY; - _valueSchema[3] = SchemaType.BYTES32_ARRAY; - _valueSchema[4] = SchemaType.BYTES32_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32[], bytes32[], bytes32[], bytes32[], bytes32[]) + Schema constant _valueSchema = Schema.wrap(0x00000005c1c1c1c1c10000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -99,21 +65,21 @@ library KeysInTable { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config (using the specified store). */ function register(IStore _store) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + _store.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/keysintable/tables/UsedKeysIndex.sol b/packages/world-modules/src/modules/keysintable/tables/UsedKeysIndex.sol index 120728ffec..a5e8d55e2f 100644 --- a/packages/world-modules/src/modules/keysintable/tables/UsedKeysIndex.sol +++ b/packages/world-modules/src/modules/keysintable/tables/UsedKeysIndex.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,54 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "UsedKeysIndex", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000557365644b657973496e646578000000); -ResourceId constant UsedKeysIndexTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0006020001050000000000000000000000000000000000000000000000000000 -); - library UsedKeysIndex { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.BYTES32; - _keySchema[1] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "UsedKeysIndex", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000557365644b657973496e646578000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0006020001050000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.BOOL; - _valueSchema[1] = SchemaType.UINT40; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32, bytes32) + Schema constant _keySchema = Schema.wrap(0x004002005f5f0000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool, uint40) + Schema constant _valueSchema = Schema.wrap(0x0006020060040000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -87,21 +55,21 @@ library UsedKeysIndex { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config (using the specified store). */ function register(IStore _store) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + _store.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/keyswithvalue/KeysWithValueModule.sol b/packages/world-modules/src/modules/keyswithvalue/KeysWithValueModule.sol index 3ee92750a0..5d35813389 100644 --- a/packages/world-modules/src/modules/keyswithvalue/KeysWithValueModule.sol +++ b/packages/world-modules/src/modules/keyswithvalue/KeysWithValueModule.sol @@ -60,9 +60,9 @@ contract KeysWithValueModule is Module { world.registerTable, ( targetTableId, - KeysWithValue.getFieldLayout(), - KeysWithValue.getKeySchema(), - KeysWithValue.getValueSchema(), + KeysWithValue._fieldLayout, + KeysWithValue._keySchema, + KeysWithValue._valueSchema, KeysWithValue.getKeyNames(), KeysWithValue.getFieldNames() ) diff --git a/packages/world-modules/src/modules/keyswithvalue/tables/KeysWithValue.sol b/packages/world-modules/src/modules/keyswithvalue/tables/KeysWithValue.sol index f8ca13729d..d6209086ce 100644 --- a/packages/world-modules/src/modules/keyswithvalue/tables/KeysWithValue.sol +++ b/packages/world-modules/src/modules/keyswithvalue/tables/KeysWithValue.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library KeysWithValue { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES32_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32[]) + Schema constant _valueSchema = Schema.wrap(0x00000001c1000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,21 +47,21 @@ library KeysWithValue { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config (using the specified store). */ function register(IStore _store, ResourceId _tableId) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + _store.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/puppet/tables/PuppetRegistry.sol b/packages/world-modules/src/modules/puppet/tables/PuppetRegistry.sol index 2cb94c5370..ef08642e3a 100644 --- a/packages/world-modules/src/modules/puppet/tables/PuppetRegistry.sol +++ b/packages/world-modules/src/modules/puppet/tables/PuppetRegistry.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library PuppetRegistry { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -79,14 +50,14 @@ library PuppetRegistry { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/std-delegations/tables/CallboundDelegations.sol b/packages/world-modules/src/modules/std-delegations/tables/CallboundDelegations.sol index d5423166a2..73f3f5a65b 100644 --- a/packages/world-modules/src/modules/std-delegations/tables/CallboundDelegations.sol +++ b/packages/world-modules/src/modules/std-delegations/tables/CallboundDelegations.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,55 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "CallboundDelegat", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000043616c6c626f756e6444656c65676174); -ResourceId constant CallboundDelegationsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library CallboundDelegations { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "CallboundDelegat", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000043616c6c626f756e6444656c65676174); - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](4); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; - _keySchema[2] = SchemaType.BYTES32; - _keySchema[3] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } - - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address, bytes32, bytes32) + Schema constant _keySchema = Schema.wrap(0x0068040061615f5f000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -89,14 +56,14 @@ library CallboundDelegations { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/std-delegations/tables/SystemboundDelegations.sol b/packages/world-modules/src/modules/std-delegations/tables/SystemboundDelegations.sol index d02c2b5587..c0d3d130c3 100644 --- a/packages/world-modules/src/modules/std-delegations/tables/SystemboundDelegations.sol +++ b/packages/world-modules/src/modules/std-delegations/tables/SystemboundDelegations.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,54 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "SystemboundDeleg", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053797374656d626f756e6444656c6567); -ResourceId constant SystemboundDelegationsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library SystemboundDelegations { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](3); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; - _keySchema[2] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "SystemboundDeleg", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000053797374656d626f756e6444656c6567); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address, bytes32) + Schema constant _keySchema = Schema.wrap(0x0048030061615f00000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -87,14 +55,14 @@ library SystemboundDelegations { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/std-delegations/tables/TimeboundDelegations.sol b/packages/world-modules/src/modules/std-delegations/tables/TimeboundDelegations.sol index 481c8157ec..8cc669aaa6 100644 --- a/packages/world-modules/src/modules/std-delegations/tables/TimeboundDelegations.sol +++ b/packages/world-modules/src/modules/std-delegations/tables/TimeboundDelegations.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,50 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "TimeboundDelegat", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000054696d65626f756e6444656c65676174); -ResourceId constant TimeboundDelegationsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library TimeboundDelegations { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "TimeboundDelegat", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462000000000000000000000000000054696d65626f756e6444656c65676174); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address) + Schema constant _keySchema = Schema.wrap(0x0028020061610000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -82,14 +51,14 @@ library TimeboundDelegations { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/tokens/tables/Balances.sol b/packages/world-modules/src/modules/tokens/tables/Balances.sol index ef3b7d0ca9..bf4005967f 100644 --- a/packages/world-modules/src/modules/tokens/tables/Balances.sol +++ b/packages/world-modules/src/modules/tokens/tables/Balances.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library Balances { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address) + Schema constant _keySchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,14 +47,14 @@ library Balances { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/modules/uniqueentity/tables/UniqueEntity.sol b/packages/world-modules/src/modules/uniqueentity/tables/UniqueEntity.sol index e00eb767a6..9d5a77ff8d 100644 --- a/packages/world-modules/src/modules/uniqueentity/tables/UniqueEntity.sol +++ b/packages/world-modules/src/modules/uniqueentity/tables/UniqueEntity.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,44 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library UniqueEntity { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -74,21 +46,21 @@ library UniqueEntity { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config (using the specified store). */ function register(IStore _store, ResourceId _tableId) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + _store.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world-modules/src/utils/AccessControlLib.sol b/packages/world-modules/src/utils/AccessControlLib.sol index c697de9c17..798f1e80e1 100644 --- a/packages/world-modules/src/utils/AccessControlLib.sol +++ b/packages/world-modules/src/utils/AccessControlLib.sol @@ -8,6 +8,7 @@ import { NamespaceOwner } from "@latticexyz/world/src/codegen/tables/NamespaceOw /** * @title AccessControlLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides access control functions for checking permissions and ownership within a namespace. * This library is functionally equivalent with the AccessControl library from world, * but uses StoreSwitch instead of always reading from own storage. diff --git a/packages/world-modules/src/utils/SystemSwitch.sol b/packages/world-modules/src/utils/SystemSwitch.sol index e68bd73844..8f98d89b34 100644 --- a/packages/world-modules/src/utils/SystemSwitch.sol +++ b/packages/world-modules/src/utils/SystemSwitch.sol @@ -23,6 +23,7 @@ import { Balances } from "@latticexyz/world/src/codegen/tables/Balances.sol"; /** * @title SystemSwitch + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev The SystemSwitch library provides functions for interacting with systems from other systems. */ library SystemSwitch { diff --git a/packages/world-modules/test/ERC721.t.sol b/packages/world-modules/test/ERC721.t.sol index dfb421c77c..80899fffb0 100644 --- a/packages/world-modules/test/ERC721.t.sol +++ b/packages/world-modules/test/ERC721.t.sol @@ -301,9 +301,8 @@ contract ERC721Test is Test, GasReporter, IERC721Events, IERC721Errors { } function testSafeTransferFromToERC721Recipient(uint256 id, address from, address operator) public { - _assumeDifferentNonZero(from, operator); - ERC721Recipient recipient = new ERC721Recipient(); + _assumeDifferentNonZero(from, operator, address(recipient)); token.mint(from, id); diff --git a/packages/world-modules/test/SystemSwitch.t.sol b/packages/world-modules/test/SystemSwitch.t.sol index 2944b3bf31..6965ab2265 100644 --- a/packages/world-modules/test/SystemSwitch.t.sol +++ b/packages/world-modules/test/SystemSwitch.t.sol @@ -5,7 +5,7 @@ import { Test } from "forge-std/Test.sol"; import { GasReporter } from "@latticexyz/gas-report/src/GasReporter.sol"; import { IStoreErrors } from "@latticexyz/store/src/IStoreErrors.sol"; -import { ResourceIds, ResourceIdsTableId } from "@latticexyz/store/src/codegen/tables/ResourceIds.sol"; +import { ResourceIds } from "@latticexyz/store/src/codegen/tables/ResourceIds.sol"; import { Schema } from "@latticexyz/store/src/Schema.sol"; import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; @@ -28,7 +28,7 @@ contract EchoSystem is System { } function readTable() public view returns (Schema) { - return StoreCore.getKeySchema(ResourceIdsTableId); + return StoreCore.getKeySchema(ResourceIds._tableId); } function echo(string memory message) public pure returns (string memory) { @@ -140,7 +140,7 @@ contract SystemSwitchTest is Test, GasReporter { function testCallRootFromRootReadTable() public { vm.prank(caller); bytes memory returnData = _executeFromSystemA(rootSystemBId, abi.encodeCall(EchoSystem.readTable, ())); - assertEq(Schema.unwrap(abi.decode(returnData, (Schema))), Schema.unwrap(ResourceIds.getKeySchema())); + assertEq(Schema.unwrap(abi.decode(returnData, (Schema))), Schema.unwrap(ResourceIds._keySchema)); } // - ROOT FROM NON ROOT ---------------------------------------------------------------------------- // @@ -179,7 +179,7 @@ contract SystemSwitchTest is Test, GasReporter { function testCallRootFromNonRootReadTable() public { vm.prank(caller); bytes memory returnData = _executeFromSystemA(rootSystemBId, abi.encodeCall(EchoSystem.readTable, ())); - assertEq(Schema.unwrap(abi.decode(returnData, (Schema))), Schema.unwrap(ResourceIds.getKeySchema())); + assertEq(Schema.unwrap(abi.decode(returnData, (Schema))), Schema.unwrap(ResourceIds._keySchema)); } // - NON ROOT FROM ROOT ---------------------------------------------------------------------------- // @@ -222,8 +222,8 @@ contract SystemSwitchTest is Test, GasReporter { vm.expectRevert( abi.encodeWithSelector( IStoreErrors.Store_TableNotFound.selector, - ResourceIdsTableId, - string(abi.encodePacked(ResourceIdsTableId)) + ResourceIds._tableId, + string(abi.encodePacked(ResourceIds._tableId)) ) ); world.call(systemAId, abi.encodeCall(EchoSystem.call, (systemBId, abi.encodeCall(EchoSystem.readTable, ())))); @@ -269,8 +269,8 @@ contract SystemSwitchTest is Test, GasReporter { vm.expectRevert( abi.encodeWithSelector( IStoreErrors.Store_TableNotFound.selector, - ResourceIdsTableId, - string(abi.encodePacked(ResourceIdsTableId)) + ResourceIds._tableId, + string(abi.encodePacked(ResourceIds._tableId)) ) ); world.call(systemAId, abi.encodeCall(EchoSystem.call, (systemBId, abi.encodeCall(EchoSystem.readTable, ())))); diff --git a/packages/world/gas-report.json b/packages/world/gas-report.json index 099e00fac3..1eb0de70d3 100644 --- a/packages/world/gas-report.json +++ b/packages/world/gas-report.json @@ -63,7 +63,7 @@ "file": "test/Factories.t.sol", "test": "testWorldFactoryGas", "name": "deploy world via WorldFactory", - "gasUsed": 12712883 + "gasUsed": 12657699 }, { "file": "test/World.t.sol", @@ -93,7 +93,7 @@ "file": "test/World.t.sol", "test": "testDeleteRecord", "name": "Delete record", - "gasUsed": 36717 + "gasUsed": 36718 }, { "file": "test/World.t.sol", @@ -141,7 +141,7 @@ "file": "test/World.t.sol", "test": "testSetField", "name": "Write data to a table field", - "gasUsed": 60883 + "gasUsed": 60884 }, { "file": "test/World.t.sol", diff --git a/packages/world/src/AccessControl.sol b/packages/world/src/AccessControl.sol index 69035f16d0..716a7f4270 100644 --- a/packages/world/src/AccessControl.sol +++ b/packages/world/src/AccessControl.sol @@ -11,6 +11,7 @@ import { NamespaceOwner } from "./codegen/tables/NamespaceOwner.sol"; /** * @title AccessControl + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Provides access control functions for checking permissions and ownership within a namespace. */ library AccessControl { diff --git a/packages/world/src/Create2.sol b/packages/world/src/Create2.sol index a96c14c10c..07a513a36f 100644 --- a/packages/world/src/Create2.sol +++ b/packages/world/src/Create2.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title Create2 + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Library to deploy contracts using the CREATE2 opcode. */ library Create2 { diff --git a/packages/world/src/Create2Factory.sol b/packages/world/src/Create2Factory.sol index 3ada9c2eff..4ae2a36980 100644 --- a/packages/world/src/Create2Factory.sol +++ b/packages/world/src/Create2Factory.sol @@ -5,6 +5,7 @@ import { Create2 } from "./Create2.sol"; /** * @title Create2Factory + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Helper Contract to facilitate create2 deployment of Contracts. */ contract Create2Factory { diff --git a/packages/world/src/Delegation.sol b/packages/world/src/Delegation.sol index 3f0c180a1f..3da7315550 100644 --- a/packages/world/src/Delegation.sol +++ b/packages/world/src/Delegation.sol @@ -8,6 +8,7 @@ import { SystemCall } from "./SystemCall.sol"; /** * @title Delegation + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Library for managing and verifying delegations. */ library Delegation { diff --git a/packages/world/src/DelegationControl.sol b/packages/world/src/DelegationControl.sol index 7135830047..8ace8023fa 100644 --- a/packages/world/src/DelegationControl.sol +++ b/packages/world/src/DelegationControl.sol @@ -9,6 +9,7 @@ import { IERC165 } from "./IERC165.sol"; /** * @title DelegationControl + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Abstract contract to manage delegations and check interface support. * Inherits functionalities from WorldContextConsumer and IDelegationControl. */ diff --git a/packages/world/src/ERC165Checker.sol b/packages/world/src/ERC165Checker.sol index 670db7933d..bdf0910152 100644 --- a/packages/world/src/ERC165Checker.sol +++ b/packages/world/src/ERC165Checker.sol @@ -1,6 +1,5 @@ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165Checker.sol) - pragma solidity ^0.8.20; import { IERC165 } from "./IERC165.sol"; diff --git a/packages/world/src/IDelegationControl.sol b/packages/world/src/IDelegationControl.sol index 0be7e5abad..6e10bc079d 100644 --- a/packages/world/src/IDelegationControl.sol +++ b/packages/world/src/IDelegationControl.sol @@ -6,6 +6,7 @@ import { ResourceId } from "./WorldResourceId.sol"; /** * @title IDelegationControl + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Interface for managing and verifying delegations within the context of a world. * Inherits functionalities from IWorldContextConsumer. */ diff --git a/packages/world/src/IERC165.sol b/packages/world/src/IERC165.sol index f98e35ee84..a11fd1b4a1 100644 --- a/packages/world/src/IERC165.sol +++ b/packages/world/src/IERC165.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title IERC165 + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Interface for the ERC-165 standard as described in the EIP-165. * Allows for contracts to be checked for their support of an interface. * See: https://eips.ethereum.org/EIPS/eip-165 diff --git a/packages/world/src/IModule.sol b/packages/world/src/IModule.sol index 71559922cf..25adb58993 100644 --- a/packages/world/src/IModule.sol +++ b/packages/world/src/IModule.sol @@ -5,6 +5,7 @@ import { IERC165 } from "./IERC165.sol"; /** * @title IModule + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Interface for the Module system. * A module can be installed within the context of a world, either as a root or non-root module. * This interface adheres to the ERC-165 standard for determining interface support. diff --git a/packages/world/src/ISystemHook.sol b/packages/world/src/ISystemHook.sol index ef0c4a8a92..91c6664d55 100644 --- a/packages/world/src/ISystemHook.sol +++ b/packages/world/src/ISystemHook.sol @@ -6,6 +6,7 @@ import { ResourceId } from "./WorldResourceId.sol"; /** * @title ISystemHook + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Interface defining system hooks for external functionality. * Provides pre and post hooks that can be triggered before and after a system call respectively. * This interface adheres to the ERC-165 standard for determining interface support. diff --git a/packages/world/src/IWorldContextConsumer.sol b/packages/world/src/IWorldContextConsumer.sol index ff781d3835..77c08fc4cf 100644 --- a/packages/world/src/IWorldContextConsumer.sol +++ b/packages/world/src/IWorldContextConsumer.sol @@ -3,15 +3,9 @@ pragma solidity >=0.8.24; import { IERC165 } from "./IERC165.sol"; -/** - * @dev World Context Consumer Interface - * This interface defines the functions a contract needs to consume the world context. - * It includes helper functions to retrieve the message sender, value, and world address. - * Additionally, it integrates with the ERC-165 standard for interface detection. - */ - /** * @title WorldContextConsumer - Extracting trusted context values from appended calldata. + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This contract is designed to extract trusted context values (like msg.sender and msg.value) * from the appended calldata. It provides mechanisms similar to EIP-2771 (https://eips.ethereum.org/EIPS/eip-2771), * but allowing any contract to be the trusted forwarder. diff --git a/packages/world/src/IWorldErrors.sol b/packages/world/src/IWorldErrors.sol index 36b9014cde..e702f86695 100644 --- a/packages/world/src/IWorldErrors.sol +++ b/packages/world/src/IWorldErrors.sol @@ -5,6 +5,7 @@ import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; /** * @title World Errors Interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface contains custom error types for the World contract. These errors provide * more informative messages for certain operations within the World contract. */ diff --git a/packages/world/src/IWorldFactory.sol b/packages/world/src/IWorldFactory.sol index af3380570d..786e671d78 100644 --- a/packages/world/src/IWorldFactory.sol +++ b/packages/world/src/IWorldFactory.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title World Factory Interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface defines the contract responsible for deploying and keeping track * of World contract instances. */ diff --git a/packages/world/src/IWorldKernel.sol b/packages/world/src/IWorldKernel.sol index 5a1aa67c18..cfd3a2f455 100644 --- a/packages/world/src/IWorldKernel.sol +++ b/packages/world/src/IWorldKernel.sol @@ -7,6 +7,7 @@ import { ResourceId } from "./WorldResourceId.sol"; /** * @title World Module Installation Interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface defines the contract responsible for managing root modules installation. */ interface IWorldModuleInstallation { @@ -21,6 +22,7 @@ interface IWorldModuleInstallation { /** * @title World Call Interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface defines the contract for executing calls on the World's systems. */ interface IWorldCall { @@ -52,6 +54,7 @@ interface IWorldCall { /** * @title World Kernel Interface + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice The IWorldKernel interface includes all methods that are part of the World contract's * internal bytecode. Consumers should use the `IBaseWorld` interface instead, which includes dynamically * registered functions selectors from the `InitModule`. diff --git a/packages/world/src/Module.sol b/packages/world/src/Module.sol index 70d687acec..5a993935f2 100644 --- a/packages/world/src/Module.sol +++ b/packages/world/src/Module.sol @@ -9,6 +9,7 @@ import { InstalledModules } from "./codegen/tables/InstalledModules.sol"; /** * @title Module + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Abstract contract that implements the ERC-165 supportsInterface function for IModule. */ abstract contract Module is IModule, WorldContextConsumer { diff --git a/packages/world/src/System.sol b/packages/world/src/System.sol index be5e76cf4e..f1add8cd23 100644 --- a/packages/world/src/System.sol +++ b/packages/world/src/System.sol @@ -5,10 +5,10 @@ import { WorldContextConsumer } from "./WorldContext.sol"; /** * @title System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev The System contract currently acts as an alias for `WorldContextConsumer`. * This structure is chosen for potential extensions in the future, where default functionality might be added to the System. */ - contract System is WorldContextConsumer { // Currently, no additional functionality is added. Future enhancements can be introduced here. } diff --git a/packages/world/src/SystemCall.sol b/packages/world/src/SystemCall.sol index 9817a18ebd..a60ffe579e 100644 --- a/packages/world/src/SystemCall.sol +++ b/packages/world/src/SystemCall.sol @@ -19,6 +19,7 @@ import { Balances } from "./codegen/tables/Balances.sol"; /** * @title SystemCall + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev The SystemCall library provides functions for interacting with systems using their unique Resource IDs. * It ensures the necessary access control checks, handles system hooks, and performs system calls. */ diff --git a/packages/world/src/SystemHook.sol b/packages/world/src/SystemHook.sol index 81770822bc..94af51c6ae 100644 --- a/packages/world/src/SystemHook.sol +++ b/packages/world/src/SystemHook.sol @@ -6,6 +6,7 @@ import { IERC165 } from "./IERC165.sol"; /** * @title SystemHook + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev The abstract SystemHook contract implements the ERC-165 supportsInterface function for ISystemHook. * System hooks are used for executing additional logic before or after certain system actions. */ diff --git a/packages/world/src/Utils.sol b/packages/world/src/Utils.sol index 200b02cfef..ace6e42921 100644 --- a/packages/world/src/Utils.sol +++ b/packages/world/src/Utils.sol @@ -6,6 +6,8 @@ import { ResourceId, WorldResourceIdInstance } from "./WorldResourceId.sol"; import { SystemRegistry } from "./codegen/tables/SystemRegistry.sol"; /** + * @title Utils + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Various utilities * @dev These utilities are not used by MUD itself, they are for developers using MUD. */ diff --git a/packages/world/src/World.sol b/packages/world/src/World.sol index e6480edc1d..d75a755218 100644 --- a/packages/world/src/World.sol +++ b/packages/world/src/World.sol @@ -29,6 +29,7 @@ import { Balances } from "./codegen/tables/Balances.sol"; /** * @title World Contract + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This contract is the core "World" contract containing various methods for * data manipulation, system calls, and dynamic function selector handling. */ @@ -51,6 +52,9 @@ contract World is StoreData, IWorldKernel { /** * @dev Prevents the World contract from calling itself. + * If the World is able to call itself via `delegatecall` from a system, the system would have root access to context like internal tables, causing a potential vulnerability. + * Ideally this should not happen because all operations to internal tables happen as internal library calls, and all calls to root systems happen as a `delegatecall` to the system. + * However, since this is an important invariant, we make it explicit by reverting if `msg.sender` is `address(this)` in all `World` methods. */ modifier prohibitDirectCallback() { if (msg.sender == address(this)) { diff --git a/packages/world/src/WorldContext.sol b/packages/world/src/WorldContext.sol index b33bc722bc..be7be9f7ae 100644 --- a/packages/world/src/WorldContext.sol +++ b/packages/world/src/WorldContext.sol @@ -11,6 +11,7 @@ uint256 constant CONTEXT_BYTES = 20 + 32; /** * @title WorldContextConsumer - Extracting trusted context values from appended calldata. + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This contract is designed to extract trusted context values (like msg.sender and msg.value) * from the appended calldata. It provides mechanisms similar to EIP-2771 (https://eips.ethereum.org/EIPS/eip-2771), * but allowing any contract to be the trusted forwarder. @@ -54,6 +55,11 @@ abstract contract WorldContextConsumer is IWorldContextConsumer { } } +/** + * @title WorldContextConsumerLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice Helpers for working with data in the context of calling a World + */ library WorldContextConsumerLib { /** * @notice Extract the `msg.sender` from the context appended to the calldata. @@ -93,6 +99,7 @@ library WorldContextConsumerLib { /** * @title WorldContextProviderLib - Utility functions to call contracts with context values appended to calldata. + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This library provides functions to make calls or delegatecalls to other contracts, * appending the context values (like msg.sender and msg.value) to the calldata for WorldContextConsumer to consume. */ diff --git a/packages/world/src/WorldFactory.sol b/packages/world/src/WorldFactory.sol index 75492b5843..7191870142 100644 --- a/packages/world/src/WorldFactory.sol +++ b/packages/world/src/WorldFactory.sol @@ -10,6 +10,7 @@ import { ROOT_NAMESPACE_ID } from "./constants.sol"; /** * @title WorldFactory + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A factory contract to deploy new World instances. * @dev This contract allows users to deploy a new World, install the InitModule, and transfer the ownership. */ diff --git a/packages/world/src/WorldResourceId.sol b/packages/world/src/WorldResourceId.sol index 9a97d52ee3..d6226ef51d 100644 --- a/packages/world/src/WorldResourceId.sol +++ b/packages/world/src/WorldResourceId.sol @@ -15,6 +15,7 @@ bytes32 constant NAMESPACE_MASK = bytes32(~bytes14("")) >> (TYPE_BITS); /** * @title WorldResourceIdLib + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A library for handling World Resource ID encoding and decoding. */ library WorldResourceIdLib { @@ -56,6 +57,7 @@ library WorldResourceIdLib { /** * @title WorldResourceIdInstance + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice A library for handling instances of World Resource IDs. */ library WorldResourceIdInstance { diff --git a/packages/world/src/codegen/index.sol b/packages/world/src/codegen/index.sol index 9adaf020c9..b00d58a490 100644 --- a/packages/world/src/codegen/index.sol +++ b/packages/world/src/codegen/index.sol @@ -3,15 +3,15 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { NamespaceOwner, NamespaceOwnerTableId } from "./tables/NamespaceOwner.sol"; -import { ResourceAccess, ResourceAccessTableId } from "./tables/ResourceAccess.sol"; -import { InstalledModules, InstalledModulesTableId } from "./tables/InstalledModules.sol"; -import { UserDelegationControl, UserDelegationControlTableId } from "./tables/UserDelegationControl.sol"; -import { NamespaceDelegationControl, NamespaceDelegationControlTableId } from "./tables/NamespaceDelegationControl.sol"; -import { Balances, BalancesTableId } from "./tables/Balances.sol"; -import { Systems, SystemsTableId } from "./tables/Systems.sol"; -import { SystemRegistry, SystemRegistryTableId } from "./tables/SystemRegistry.sol"; -import { SystemHooks, SystemHooksTableId } from "./tables/SystemHooks.sol"; -import { FunctionSelectors, FunctionSelectorsTableId } from "./tables/FunctionSelectors.sol"; -import { FunctionSignatures, FunctionSignaturesTableId } from "./tables/FunctionSignatures.sol"; -import { InitModuleAddress, InitModuleAddressTableId } from "./tables/InitModuleAddress.sol"; +import { NamespaceOwner } from "./tables/NamespaceOwner.sol"; +import { ResourceAccess } from "./tables/ResourceAccess.sol"; +import { InstalledModules } from "./tables/InstalledModules.sol"; +import { UserDelegationControl } from "./tables/UserDelegationControl.sol"; +import { NamespaceDelegationControl } from "./tables/NamespaceDelegationControl.sol"; +import { Balances } from "./tables/Balances.sol"; +import { Systems } from "./tables/Systems.sol"; +import { SystemRegistry } from "./tables/SystemRegistry.sol"; +import { SystemHooks } from "./tables/SystemHooks.sol"; +import { FunctionSelectors } from "./tables/FunctionSelectors.sol"; +import { FunctionSignatures } from "./tables/FunctionSignatures.sol"; +import { InitModuleAddress } from "./tables/InitModuleAddress.sol"; diff --git a/packages/world/src/codegen/interfaces/IAccessManagementSystem.sol b/packages/world/src/codegen/interfaces/IAccessManagementSystem.sol index 48eda4c6df..fac3eb1116 100644 --- a/packages/world/src/codegen/interfaces/IAccessManagementSystem.sol +++ b/packages/world/src/codegen/interfaces/IAccessManagementSystem.sol @@ -7,6 +7,7 @@ import { ResourceId } from "./../../WorldResourceId.sol"; /** * @title IAccessManagementSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IAccessManagementSystem { diff --git a/packages/world/src/codegen/interfaces/IBalanceTransferSystem.sol b/packages/world/src/codegen/interfaces/IBalanceTransferSystem.sol index 26beb1349b..0aa4b268b1 100644 --- a/packages/world/src/codegen/interfaces/IBalanceTransferSystem.sol +++ b/packages/world/src/codegen/interfaces/IBalanceTransferSystem.sol @@ -7,6 +7,7 @@ import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; /** * @title IBalanceTransferSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IBalanceTransferSystem { diff --git a/packages/world/src/codegen/interfaces/IBaseWorld.sol b/packages/world/src/codegen/interfaces/IBaseWorld.sol index 6026287465..a30241297a 100644 --- a/packages/world/src/codegen/interfaces/IBaseWorld.sol +++ b/packages/world/src/codegen/interfaces/IBaseWorld.sol @@ -15,6 +15,7 @@ import { IRegistrationSystem } from "./IRegistrationSystem.sol"; /** * @title IBaseWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. @@ -28,6 +29,4 @@ interface IBaseWorld is IModuleInstallationSystem, IWorldRegistrationSystem, IRegistrationSystem -{ - -} +{} diff --git a/packages/world/src/codegen/interfaces/IBatchCallSystem.sol b/packages/world/src/codegen/interfaces/IBatchCallSystem.sol index 62cf366bbb..c6f95b5489 100644 --- a/packages/world/src/codegen/interfaces/IBatchCallSystem.sol +++ b/packages/world/src/codegen/interfaces/IBatchCallSystem.sol @@ -7,6 +7,7 @@ import { SystemCallData, SystemCallFromData } from "./../../modules/init/types.s /** * @title IBatchCallSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IBatchCallSystem { diff --git a/packages/world/src/codegen/interfaces/IModuleInstallationSystem.sol b/packages/world/src/codegen/interfaces/IModuleInstallationSystem.sol index c8f34102bc..80fb477ecf 100644 --- a/packages/world/src/codegen/interfaces/IModuleInstallationSystem.sol +++ b/packages/world/src/codegen/interfaces/IModuleInstallationSystem.sol @@ -7,6 +7,7 @@ import { IModule } from "./../../IModule.sol"; /** * @title IModuleInstallationSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IModuleInstallationSystem { diff --git a/packages/world/src/codegen/interfaces/IRegistrationSystem.sol b/packages/world/src/codegen/interfaces/IRegistrationSystem.sol index f14496a41b..d4dd6649d8 100644 --- a/packages/world/src/codegen/interfaces/IRegistrationSystem.sol +++ b/packages/world/src/codegen/interfaces/IRegistrationSystem.sol @@ -5,8 +5,7 @@ pragma solidity >=0.8.24; /** * @title IRegistrationSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ -interface IRegistrationSystem { - -} +interface IRegistrationSystem {} diff --git a/packages/world/src/codegen/interfaces/IWorldRegistrationSystem.sol b/packages/world/src/codegen/interfaces/IWorldRegistrationSystem.sol index cf097e0204..214e0d3f01 100644 --- a/packages/world/src/codegen/interfaces/IWorldRegistrationSystem.sol +++ b/packages/world/src/codegen/interfaces/IWorldRegistrationSystem.sol @@ -9,6 +9,7 @@ import { System } from "./../../System.sol"; /** * @title IWorldRegistrationSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IWorldRegistrationSystem { diff --git a/packages/world/src/codegen/tables/Balances.sol b/packages/world/src/codegen/tables/Balances.sol index 7e478bb7b3..26291f56b3 100644 --- a/packages/world/src/codegen/tables/Balances.sol +++ b/packages/world/src/codegen/tables/Balances.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "Balances", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000042616c616e6365730000000000000000); -ResourceId constant BalancesTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library Balances { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "Balances", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000042616c616e6365730000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT256; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256) + Schema constant _valueSchema = Schema.wrap(0x002001001f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library Balances { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/FunctionSelectors.sol b/packages/world/src/codegen/tables/FunctionSelectors.sol index f45012ae4d..d8e9424bd7 100644 --- a/packages/world/src/codegen/tables/FunctionSelectors.sol +++ b/packages/world/src/codegen/tables/FunctionSelectors.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,53 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "FunctionSelector", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000046756e6374696f6e53656c6563746f72); -ResourceId constant FunctionSelectorsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0024020020040000000000000000000000000000000000000000000000000000 -); - library FunctionSelectors { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES4; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "FunctionSelector", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000046756e6374696f6e53656c6563746f72); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0024020020040000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.BYTES32; - _valueSchema[1] = SchemaType.BYTES4; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes4) + Schema constant _keySchema = Schema.wrap(0x0004010043000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32, bytes4) + Schema constant _valueSchema = Schema.wrap(0x002402005f430000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -85,14 +54,14 @@ library FunctionSelectors { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/FunctionSignatures.sol b/packages/world/src/codegen/tables/FunctionSignatures.sol index 227f39e97a..d2a4611869 100644 --- a/packages/world/src/codegen/tables/FunctionSignatures.sol +++ b/packages/world/src/codegen/tables/FunctionSignatures.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,49 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "FunctionSignatur", typeId: RESOURCE_OFFCHAIN_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x6f74776f726c6400000000000000000046756e6374696f6e5369676e61747572); -ResourceId constant FunctionSignaturesTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library FunctionSignatures { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES4; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "FunctionSignatur", typeId: RESOURCE_OFFCHAIN_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x6f74776f726c6400000000000000000046756e6374696f6e5369676e61747572); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes4) + Schema constant _keySchema = Schema.wrap(0x0004010043000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (string) + Schema constant _valueSchema = Schema.wrap(0x00000001c5000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -80,14 +50,14 @@ library FunctionSignatures { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/InitModuleAddress.sol b/packages/world/src/codegen/tables/InitModuleAddress.sol index b179b181c5..b79eb9f210 100644 --- a/packages/world/src/codegen/tables/InitModuleAddress.sol +++ b/packages/world/src/codegen/tables/InitModuleAddress.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "InitModuleAddres", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c64000000000000000000496e69744d6f64756c65416464726573); -ResourceId constant InitModuleAddressTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library InitModuleAddress { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "InitModuleAddres", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c64000000000000000000496e69744d6f64756c65416464726573); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library InitModuleAddress { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/InstalledModules.sol b/packages/world/src/codegen/tables/InstalledModules.sol index 1961a8c2a6..6cf4235993 100644 --- a/packages/world/src/codegen/tables/InstalledModules.sol +++ b/packages/world/src/codegen/tables/InstalledModules.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,50 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "InstalledModules", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c64000000000000000000496e7374616c6c65644d6f64756c6573); -ResourceId constant InstalledModulesTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library InstalledModules { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "InstalledModules", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c64000000000000000000496e7374616c6c65644d6f64756c6573); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, bytes32) + Schema constant _keySchema = Schema.wrap(0x00340200615f0000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -82,14 +51,14 @@ library InstalledModules { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/NamespaceDelegationControl.sol b/packages/world/src/codegen/tables/NamespaceDelegationControl.sol index aebe7d0930..308b9ef2eb 100644 --- a/packages/world/src/codegen/tables/NamespaceDelegationControl.sol +++ b/packages/world/src/codegen/tables/NamespaceDelegationControl.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "NamespaceDelegat", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000004e616d65737061636544656c65676174); -ResourceId constant NamespaceDelegationControlTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library NamespaceDelegationControl { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "NamespaceDelegat", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000004e616d65737061636544656c65676174); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32) + Schema constant _valueSchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library NamespaceDelegationControl { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/NamespaceOwner.sol b/packages/world/src/codegen/tables/NamespaceOwner.sol index e5cb0a3b7b..147d8cd9fc 100644 --- a/packages/world/src/codegen/tables/NamespaceOwner.sol +++ b/packages/world/src/codegen/tables/NamespaceOwner.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "NamespaceOwner", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000004e616d6573706163654f776e65720000); -ResourceId constant NamespaceOwnerTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0014010014000000000000000000000000000000000000000000000000000000 -); - library NamespaceOwner { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "NamespaceOwner", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000004e616d6573706163654f776e65720000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0014010014000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address) + Schema constant _valueSchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library NamespaceOwner { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/ResourceAccess.sol b/packages/world/src/codegen/tables/ResourceAccess.sol index 5d5a6a50af..afe61091c2 100644 --- a/packages/world/src/codegen/tables/ResourceAccess.sol +++ b/packages/world/src/codegen/tables/ResourceAccess.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,53 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "ResourceAccess", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000005265736f757263654163636573730000); -ResourceId constant ResourceAccessTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library ResourceAccess { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.BYTES32; - _keySchema[1] = SchemaType.ADDRESS; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "ResourceAccess", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000005265736f757263654163636573730000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32, address) + Schema constant _keySchema = Schema.wrap(0x003402005f610000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -85,14 +54,14 @@ library ResourceAccess { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/SystemHooks.sol b/packages/world/src/codegen/tables/SystemHooks.sol index e73edd6d16..dc99c8190f 100644 --- a/packages/world/src/codegen/tables/SystemHooks.sol +++ b/packages/world/src/codegen/tables/SystemHooks.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "SystemHooks", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d486f6f6b730000000000); -ResourceId constant SystemHooksTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library SystemHooks { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "SystemHooks", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d486f6f6b730000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES21_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes21[]) + Schema constant _valueSchema = Schema.wrap(0x00000001b6000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library SystemHooks { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/SystemRegistry.sol b/packages/world/src/codegen/tables/SystemRegistry.sol index 551a22293c..c538650d08 100644 --- a/packages/world/src/codegen/tables/SystemRegistry.sol +++ b/packages/world/src/codegen/tables/SystemRegistry.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,52 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "SystemRegistry", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d52656769737472790000); -ResourceId constant SystemRegistryTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library SystemRegistry { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.ADDRESS; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "SystemRegistry", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d52656769737472790000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address) + Schema constant _keySchema = Schema.wrap(0x0014010061000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32) + Schema constant _valueSchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -83,14 +53,14 @@ library SystemRegistry { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/Systems.sol b/packages/world/src/codegen/tables/Systems.sol index ec75746b38..9dc15cfa1a 100644 --- a/packages/world/src/codegen/tables/Systems.sol +++ b/packages/world/src/codegen/tables/Systems.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,53 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "Systems", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d73000000000000000000); -ResourceId constant SystemsTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0015020014010000000000000000000000000000000000000000000000000000 -); - library Systems { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "Systems", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c6400000000000000000053797374656d73000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0015020014010000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.ADDRESS; - _valueSchema[1] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address, bool) + Schema constant _valueSchema = Schema.wrap(0x0015020061600000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -85,14 +54,14 @@ library Systems { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/codegen/tables/UserDelegationControl.sol b/packages/world/src/codegen/tables/UserDelegationControl.sol index f32fa0ca47..66064511cc 100644 --- a/packages/world/src/codegen/tables/UserDelegationControl.sol +++ b/packages/world/src/codegen/tables/UserDelegationControl.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,53 +11,25 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; // Import user types import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "UserDelegationCo", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000005573657244656c65676174696f6e436f); -ResourceId constant UserDelegationControlTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0020010020000000000000000000000000000000000000000000000000000000 -); - library UserDelegationControl { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](2); - _keySchema[0] = SchemaType.ADDRESS; - _keySchema[1] = SchemaType.ADDRESS; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "world", name: "UserDelegationCo", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x7462776f726c640000000000000000005573657244656c65676174696f6e436f); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0020010020000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (address, address) + Schema constant _keySchema = Schema.wrap(0x0028020061610000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bytes32) + Schema constant _valueSchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -85,14 +54,14 @@ library UserDelegationControl { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/src/modules/init/InitModule.sol b/packages/world/src/modules/init/InitModule.sol index a6f98112a5..7cf84679df 100644 --- a/packages/world/src/modules/init/InitModule.sol +++ b/packages/world/src/modules/init/InitModule.sol @@ -36,10 +36,10 @@ import { WorldRegistrationSystem } from "./implementations/WorldRegistrationSyst /** * @title Init Module + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Registers internal World tables, systems, and their function selectors. * @dev This module only supports `installRoot` because it installs root tables, systems and function selectors. */ - contract InitModule is Module { address internal immutable accessManagementSystem; address internal immutable balanceTransferSystem; diff --git a/packages/world/src/modules/init/LimitedCallContext.sol b/packages/world/src/modules/init/LimitedCallContext.sol index 6fa218d3e6..41139858be 100644 --- a/packages/world/src/modules/init/LimitedCallContext.sol +++ b/packages/world/src/modules/init/LimitedCallContext.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title LimitedCallContext + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev Systems are expected to be always called via the central World contract. * Depending on whether it is a root or non-root system, the call is performed via `delegatecall` or `call`. * Since Systems are expected to be stateless and only interact with the World state, diff --git a/packages/world/src/modules/init/RegistrationSystem.sol b/packages/world/src/modules/init/RegistrationSystem.sol index ae019010a8..1e677ecb1b 100644 --- a/packages/world/src/modules/init/RegistrationSystem.sol +++ b/packages/world/src/modules/init/RegistrationSystem.sol @@ -9,6 +9,7 @@ import { WorldRegistrationSystem } from "./implementations/WorldRegistrationSyst /** * @title Registration System for World + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This system aggregates World registration and installation functionalities externalized from the World contract, aiming to keep the World contract's bytecode lean. * @dev Aggregates multiple system implementations for the World. */ diff --git a/packages/world/src/modules/init/implementations/AccessManagementSystem.sol b/packages/world/src/modules/init/implementations/AccessManagementSystem.sol index 1c05a7f050..04a897b405 100644 --- a/packages/world/src/modules/init/implementations/AccessManagementSystem.sol +++ b/packages/world/src/modules/init/implementations/AccessManagementSystem.sol @@ -12,6 +12,7 @@ import { LimitedCallContext } from "../LimitedCallContext.sol"; /** * @title Access Management System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This contract manages the granting and revoking of access from/to resources. */ contract AccessManagementSystem is System, LimitedCallContext { diff --git a/packages/world/src/modules/init/implementations/BalanceTransferSystem.sol b/packages/world/src/modules/init/implementations/BalanceTransferSystem.sol index 58bfa7b174..88fedb3b66 100644 --- a/packages/world/src/modules/init/implementations/BalanceTransferSystem.sol +++ b/packages/world/src/modules/init/implementations/BalanceTransferSystem.sol @@ -17,6 +17,7 @@ import { LimitedCallContext } from "../LimitedCallContext.sol"; /** * @title Balance Transfer System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A system contract that facilitates balance transfers in the World and outside of the World. */ contract BalanceTransferSystem is System, IWorldErrors, LimitedCallContext { diff --git a/packages/world/src/modules/init/implementations/BatchCallSystem.sol b/packages/world/src/modules/init/implementations/BatchCallSystem.sol index e9e39d06dc..9a62614193 100644 --- a/packages/world/src/modules/init/implementations/BatchCallSystem.sol +++ b/packages/world/src/modules/init/implementations/BatchCallSystem.sol @@ -9,6 +9,7 @@ import { LimitedCallContext } from "../LimitedCallContext.sol"; /** * @title Batch Call System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A system contract that facilitates batching of calls to various systems in a single transaction. */ contract BatchCallSystem is System, LimitedCallContext { diff --git a/packages/world/src/modules/init/implementations/ModuleInstallationSystem.sol b/packages/world/src/modules/init/implementations/ModuleInstallationSystem.sol index 1b03dc8abd..59cd98a17a 100644 --- a/packages/world/src/modules/init/implementations/ModuleInstallationSystem.sol +++ b/packages/world/src/modules/init/implementations/ModuleInstallationSystem.sol @@ -11,6 +11,7 @@ import { LimitedCallContext } from "../LimitedCallContext.sol"; /** * @title Module Installation System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev A system contract to handle the installation of (non-root) modules in the World. */ contract ModuleInstallationSystem is System, LimitedCallContext { diff --git a/packages/world/src/modules/init/implementations/StoreRegistrationSystem.sol b/packages/world/src/modules/init/implementations/StoreRegistrationSystem.sol index 3c83e26259..1b4eb63d50 100644 --- a/packages/world/src/modules/init/implementations/StoreRegistrationSystem.sol +++ b/packages/world/src/modules/init/implementations/StoreRegistrationSystem.sol @@ -22,6 +22,7 @@ import { WorldRegistrationSystem } from "./WorldRegistrationSystem.sol"; /** * @title Store Registration System + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This contract provides functionality for the registration of store-related resources within the World framework. */ contract StoreRegistrationSystem is System, IWorldErrors, LimitedCallContext { diff --git a/packages/world/src/modules/init/implementations/WorldRegistrationSystem.sol b/packages/world/src/modules/init/implementations/WorldRegistrationSystem.sol index 5ac6bf1664..e5fd723544 100644 --- a/packages/world/src/modules/init/implementations/WorldRegistrationSystem.sol +++ b/packages/world/src/modules/init/implementations/WorldRegistrationSystem.sol @@ -22,7 +22,7 @@ import { ISystemHook } from "../../../ISystemHook.sol"; import { IWorldErrors } from "../../../IWorldErrors.sol"; import { IDelegationControl } from "../../../IDelegationControl.sol"; -import { SystemHooks, SystemHooksTableId } from "../../../codegen/tables/SystemHooks.sol"; +import { SystemHooks } from "../../../codegen/tables/SystemHooks.sol"; import { SystemRegistry } from "../../../codegen/tables/SystemRegistry.sol"; import { Systems } from "../../../codegen/tables/Systems.sol"; import { FunctionSelectors } from "../../../codegen/tables/FunctionSelectors.sol"; @@ -34,6 +34,7 @@ import { LimitedCallContext } from "../LimitedCallContext.sol"; /** * @title WorldRegistrationSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This contract provides functions related to registering resources other than tables in the World. */ contract WorldRegistrationSystem is System, IWorldErrors, LimitedCallContext { @@ -109,7 +110,7 @@ contract WorldRegistrationSystem is System, IWorldErrors, LimitedCallContext { AccessControl.requireOwner(systemId, _msgSender()); // Remove the hook from the list of hooks for this system in the system hooks table - HookLib.filterListByAddress(SystemHooksTableId, systemId, address(hookAddress)); + HookLib.filterListByAddress(SystemHooks._tableId, systemId, address(hookAddress)); } /** diff --git a/packages/world/src/modules/init/types.sol b/packages/world/src/modules/init/types.sol index a8bf5b91e8..d04a845615 100644 --- a/packages/world/src/modules/init/types.sol +++ b/packages/world/src/modules/init/types.sol @@ -5,6 +5,7 @@ import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; /** * @title System Call Data Structure + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Holds data for making system calls. * @dev Used to represent a call to a specific system identified by a ResourceId. */ @@ -17,6 +18,7 @@ struct SystemCallData { /** * @title System Call From Data Structure + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice Holds data for making system calls with a specific sender. * @dev Used to represent a call from a specific address to a specific system. */ diff --git a/packages/world/src/requireInterface.sol b/packages/world/src/requireInterface.sol index 5486a5918a..f3f6f1c12e 100644 --- a/packages/world/src/requireInterface.sol +++ b/packages/world/src/requireInterface.sol @@ -6,9 +6,7 @@ import { ERC165Checker } from "./ERC165Checker.sol"; import { IWorldErrors } from "./IWorldErrors.sol"; /** - * @title Interface Validator - * @notice Utility function to validate interface support on a given contract using ERC-165. - * @dev This function uses the ERC-165 standard's `supportsInterface` to check if a given contract supports a specific interface. + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) */ /** diff --git a/packages/world/src/requireNamespace.sol b/packages/world/src/requireNamespace.sol index 64efcbe821..ee68ed4571 100644 --- a/packages/world/src/requireNamespace.sol +++ b/packages/world/src/requireNamespace.sol @@ -7,6 +7,10 @@ import { IWorldErrors } from "./IWorldErrors.sol"; using WorldResourceIdInstance for ResourceId; +/** + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ + /** * @notice Checks if a given `resourceId` is a namespace. * @dev Reverts with `IWorldErrors.World_InvalidResourceType` if the ID does not have the correct components. diff --git a/packages/world/src/requireValidNamespace.sol b/packages/world/src/requireValidNamespace.sol index 485032c869..97d22dc4b5 100644 --- a/packages/world/src/requireValidNamespace.sol +++ b/packages/world/src/requireValidNamespace.sol @@ -8,6 +8,10 @@ import { IWorldErrors } from "./IWorldErrors.sol"; using WorldResourceIdInstance for ResourceId; +/** + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + */ + /** * @notice Checks if a given `resourceId` is a valid namespace. * @dev Reverts with `IWorldErrors.World_InvalidNamespace` if the namespace includes the reserved `__` separator string or ends with `_`. diff --git a/packages/world/src/revertWithBytes.sol b/packages/world/src/revertWithBytes.sol index 044e5f73f1..a482509613 100644 --- a/packages/world/src/revertWithBytes.sol +++ b/packages/world/src/revertWithBytes.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.24; /** - * @title Raw Bytes Reverter - * @notice Utility function to revert transactions with raw bytes. - * @dev This can be especially useful when reverting with a message obtained from a low-level call or a pre-encoded error. + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) */ /** diff --git a/packages/world/src/systemHookTypes.sol b/packages/world/src/systemHookTypes.sol index b1567d296f..1220f67bc7 100644 --- a/packages/world/src/systemHookTypes.sol +++ b/packages/world/src/systemHookTypes.sol @@ -3,6 +3,7 @@ pragma solidity >=0.8.24; /** * @title System Hook Types + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This file provides constants for defining the different types of system hooks. * System hooks can be used to execute additional logic before or after system actions. */ diff --git a/packages/world/src/test/tables/AddressArray.sol b/packages/world/src/test/tables/AddressArray.sol deleted file mode 100644 index 1ab5c9c3fb..0000000000 --- a/packages/world/src/test/tables/AddressArray.sol +++ /dev/null @@ -1,566 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.24; - -/* Autogenerated file. Do not edit manually. */ - -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - -// Import store internals -import { IStore } from "@latticexyz/store/src/IStore.sol"; -import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; -import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; -import { Bytes } from "@latticexyz/store/src/Bytes.sol"; -import { Memory } from "@latticexyz/store/src/Memory.sol"; -import { SliceLib } from "@latticexyz/store/src/Slice.sol"; -import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; -import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; -import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "@latticexyz/store/src/storeResourceTypes.sol"; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - -library AddressArray { - /** Get the table values' field layout */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** Get the table's key schema */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } - - /** Get the table's value schema */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS_ARRAY; - - return SchemaLib.encode(_valueSchema); - } - - /** Get the table's key names */ - function getKeyNames() internal pure returns (string[] memory keyNames) { - keyNames = new string[](1); - keyNames[0] = "key"; - } - - /** Get the table's field names */ - function getFieldNames() internal pure returns (string[] memory fieldNames) { - fieldNames = new string[](1); - fieldNames[0] = "value"; - } - - /** Register the table with its config */ - function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config */ - function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config (using the specified store) */ - function register(IStore _store, ResourceId _tableId) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Get value */ - function getValue(ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = StoreSwitch.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Get value */ - function _getValue(ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = StoreCore.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Get value (using the specified store) */ - function getValue(IStore _store, ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = _store.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Get value */ - function get(ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = StoreSwitch.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Get value */ - function _get(ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = StoreCore.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Get value (using the specified store) */ - function get(IStore _store, ResourceId _tableId, bytes32 key) internal view returns (address[] memory value) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - bytes memory _blob = _store.getDynamicField(_tableId, _keyTuple, 0); - return (SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_address()); - } - - /** Set value */ - function setValue(ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Set value */ - function _setValue(ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Set value (using the specified store) */ - function setValue(IStore _store, ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Set value */ - function set(ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Set value */ - function _set(ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Set value (using the specified store) */ - function set(IStore _store, ResourceId _tableId, bytes32 key, address[] memory value) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.setDynamicField(_tableId, _keyTuple, 0, EncodeArray.encode((value))); - } - - /** Get the length of value */ - function lengthValue(ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = StoreSwitch.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** Get the length of value */ - function _lengthValue(ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = StoreCore.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** Get the length of value (using the specified store) */ - function lengthValue(IStore _store, ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = _store.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** Get the length of value */ - function length(ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = StoreSwitch.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** Get the length of value */ - function _length(ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = StoreCore.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** Get the length of value (using the specified store) */ - function length(IStore _store, ResourceId _tableId, bytes32 key) internal view returns (uint256) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - uint256 _byteLength = _store.getDynamicFieldLength(_tableId, _keyTuple, 0); - unchecked { - return _byteLength / 20; - } - } - - /** - * Get an item of value - * (unchecked, returns invalid data if index overflows) - */ - function getItemValue(ResourceId _tableId, bytes32 key, uint256 _index) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = StoreSwitch.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** - * Get an item of value - * (unchecked, returns invalid data if index overflows) - */ - function _getItemValue(ResourceId _tableId, bytes32 key, uint256 _index) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = StoreCore.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** - * Get an item of value (using the specified store) - * (unchecked, returns invalid data if index overflows) - */ - function getItemValue( - IStore _store, - ResourceId _tableId, - bytes32 key, - uint256 _index - ) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = _store.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** - * Get an item of value - * (unchecked, returns invalid data if index overflows) - */ - function getItem(ResourceId _tableId, bytes32 key, uint256 _index) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = StoreSwitch.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** - * Get an item of value - * (unchecked, returns invalid data if index overflows) - */ - function _getItem(ResourceId _tableId, bytes32 key, uint256 _index) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = StoreCore.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** - * Get an item of value (using the specified store) - * (unchecked, returns invalid data if index overflows) - */ - function getItem(IStore _store, ResourceId _tableId, bytes32 key, uint256 _index) internal view returns (address) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _blob = _store.getDynamicFieldSlice(_tableId, _keyTuple, 0, _index * 20, (_index + 1) * 20); - return (address(bytes20(_blob))); - } - } - - /** Push an element to value */ - function pushValue(ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Push an element to value */ - function _pushValue(ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Push an element to value (using the specified store) */ - function pushValue(IStore _store, ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Push an element to value */ - function push(ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Push an element to value */ - function _push(ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Push an element to value (using the specified store) */ - function push(IStore _store, ResourceId _tableId, bytes32 key, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.pushToDynamicField(_tableId, _keyTuple, 0, abi.encodePacked((_element))); - } - - /** Pop an element from value */ - function popValue(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** Pop an element from value */ - function _popValue(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** Pop an element from value (using the specified store) */ - function popValue(IStore _store, ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** Pop an element from value */ - function pop(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** Pop an element from value */ - function _pop(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** Pop an element from value (using the specified store) */ - function pop(IStore _store, ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.popFromDynamicField(_tableId, _keyTuple, 0, 20); - } - - /** - * Update an element of value at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function updateValue(ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - StoreSwitch.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** - * Update an element of value at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function _updateValue(ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - StoreCore.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** - * Update an element of value (using the specified store) at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function updateValue(IStore _store, ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - _store.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** - * Update an element of value at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function update(ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - StoreSwitch.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** - * Update an element of value at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function _update(ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - StoreCore.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** - * Update an element of value (using the specified store) at `_index` - * (checked only to prevent modifying other tables; can corrupt own data if index overflows) - */ - function update(IStore _store, ResourceId _tableId, bytes32 key, uint256 _index, address _element) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - unchecked { - bytes memory _encoded = abi.encodePacked((_element)); - _store.spliceDynamicData(_tableId, _keyTuple, 0, uint40(_index * 20), uint40(_encoded.length), _encoded); - } - } - - /** Delete all data for given keys */ - function deleteRecord(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreSwitch.deleteRecord(_tableId, _keyTuple); - } - - /** Delete all data for given keys */ - function _deleteRecord(ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - StoreCore.deleteRecord(_tableId, _keyTuple, _fieldLayout); - } - - /** Delete all data for given keys (using the specified store) */ - function deleteRecord(IStore _store, ResourceId _tableId, bytes32 key) internal { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - _store.deleteRecord(_tableId, _keyTuple); - } - - /** Tightly pack dynamic data using this table's schema */ - function encodeLengths(address[] memory value) internal pure returns (PackedCounter _encodedLengths) { - // Lengths are effectively checked during copy by 2**40 bytes exceeding gas limits - unchecked { - _encodedLengths = PackedCounterLib.pack(value.length * 20); - } - } - - /** Tightly pack dynamic data using this table's schema */ - function encodeDynamic(address[] memory value) internal pure returns (bytes memory) { - return abi.encodePacked(EncodeArray.encode((value))); - } - - /** Tightly pack full data using this table's field layout */ - function encode(address[] memory value) internal pure returns (bytes memory, PackedCounter, bytes memory) { - bytes memory _staticData; - PackedCounter _encodedLengths = encodeLengths(value); - bytes memory _dynamicData = encodeDynamic(value); - - return (_staticData, _encodedLengths, _dynamicData); - } - - /** Encode keys as a bytes32 array using this table's field layout */ - function encodeKeyTuple(bytes32 key) internal pure returns (bytes32[] memory) { - bytes32[] memory _keyTuple = new bytes32[](1); - _keyTuple[0] = key; - - return _keyTuple; - } -} diff --git a/packages/world/src/test/tables/Bool.sol b/packages/world/src/test/tables/Bool.sol deleted file mode 100644 index 7b69c6377e..0000000000 --- a/packages/world/src/test/tables/Bool.sol +++ /dev/null @@ -1,212 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.24; - -/* Autogenerated file. Do not edit manually. */ - -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - -// Import store internals -import { IStore } from "@latticexyz/store/src/IStore.sol"; -import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; -import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; -import { Bytes } from "@latticexyz/store/src/Bytes.sol"; -import { Memory } from "@latticexyz/store/src/Memory.sol"; -import { SliceLib } from "@latticexyz/store/src/Slice.sol"; -import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; -import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; -import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "@latticexyz/store/src/storeResourceTypes.sol"; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - -library Bool { - /** Get the table values' field layout */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** Get the table's key schema */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } - - /** Get the table's value schema */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } - - /** Get the table's key names */ - function getKeyNames() internal pure returns (string[] memory keyNames) { - keyNames = new string[](0); - } - - /** Get the table's field names */ - function getFieldNames() internal pure returns (string[] memory fieldNames) { - fieldNames = new string[](1); - fieldNames[0] = "value"; - } - - /** Register the table with its config */ - function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config */ - function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config (using the specified store) */ - function register(IStore _store, ResourceId _tableId) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Get value */ - function getValue(ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreSwitch.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value */ - function _getValue(ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreCore.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value (using the specified store) */ - function getValue(IStore _store, ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = _store.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value */ - function get(ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreSwitch.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value */ - function _get(ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreCore.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value (using the specified store) */ - function get(IStore _store, ResourceId _tableId) internal view returns (bool value) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = _store.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Set value */ - function setValue(ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Set value */ - function _setValue(ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Set value (using the specified store) */ - function setValue(IStore _store, ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Set value */ - function set(ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Set value */ - function _set(ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Set value (using the specified store) */ - function set(IStore _store, ResourceId _tableId, bool value) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value)), _fieldLayout); - } - - /** Delete all data for given keys */ - function deleteRecord(ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.deleteRecord(_tableId, _keyTuple); - } - - /** Delete all data for given keys */ - function _deleteRecord(ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.deleteRecord(_tableId, _keyTuple, _fieldLayout); - } - - /** Delete all data for given keys (using the specified store) */ - function deleteRecord(IStore _store, ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.deleteRecord(_tableId, _keyTuple); - } - - /** Tightly pack static data using this table's schema */ - function encodeStatic(bool value) internal pure returns (bytes memory) { - return abi.encodePacked(value); - } - - /** Tightly pack full data using this table's field layout */ - function encode(bool value) internal pure returns (bytes memory, PackedCounter, bytes memory) { - bytes memory _staticData = encodeStatic(value); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - return (_staticData, _encodedLengths, _dynamicData); - } - - /** Encode keys as a bytes32 array using this table's field layout */ - function encodeKeyTuple() internal pure returns (bytes32[] memory) { - bytes32[] memory _keyTuple = new bytes32[](0); - - return _keyTuple; - } -} - -function _toBool(uint8 value) pure returns (bool result) { - assembly { - result := value - } -} diff --git a/packages/world/src/test/tables/TwoFields.sol b/packages/world/src/test/tables/TwoFields.sol deleted file mode 100644 index 15d5559187..0000000000 --- a/packages/world/src/test/tables/TwoFields.sol +++ /dev/null @@ -1,349 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.24; - -/* Autogenerated file. Do not edit manually. */ - -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - -// Import store internals -import { IStore } from "@latticexyz/store/src/IStore.sol"; -import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; -import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; -import { Bytes } from "@latticexyz/store/src/Bytes.sol"; -import { Memory } from "@latticexyz/store/src/Memory.sol"; -import { SliceLib } from "@latticexyz/store/src/Slice.sol"; -import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; -import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; -import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "@latticexyz/store/src/storeResourceTypes.sol"; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0002020001010000000000000000000000000000000000000000000000000000 -); - -struct TwoFieldsData { - bool value1; - bool value2; -} - -library TwoFields { - /** Get the table values' field layout */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** Get the table's key schema */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } - - /** Get the table's value schema */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.BOOL; - _valueSchema[1] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } - - /** Get the table's key names */ - function getKeyNames() internal pure returns (string[] memory keyNames) { - keyNames = new string[](0); - } - - /** Get the table's field names */ - function getFieldNames() internal pure returns (string[] memory fieldNames) { - fieldNames = new string[](2); - fieldNames[0] = "value1"; - fieldNames[1] = "value2"; - } - - /** Register the table with its config */ - function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config */ - function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Register the table with its config (using the specified store) */ - function register(IStore _store, ResourceId _tableId) internal { - _store.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); - } - - /** Get value1 */ - function getValue1(ResourceId _tableId) internal view returns (bool value1) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreSwitch.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value1 */ - function _getValue1(ResourceId _tableId) internal view returns (bool value1) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreCore.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value1 (using the specified store) */ - function getValue1(IStore _store, ResourceId _tableId) internal view returns (bool value1) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = _store.getStaticField(_tableId, _keyTuple, 0, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Set value1 */ - function setValue1(ResourceId _tableId, bool value1) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value1)), _fieldLayout); - } - - /** Set value1 */ - function _setValue1(ResourceId _tableId, bool value1) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value1)), _fieldLayout); - } - - /** Set value1 (using the specified store) */ - function setValue1(IStore _store, ResourceId _tableId, bool value1) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setStaticField(_tableId, _keyTuple, 0, abi.encodePacked((value1)), _fieldLayout); - } - - /** Get value2 */ - function getValue2(ResourceId _tableId) internal view returns (bool value2) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreSwitch.getStaticField(_tableId, _keyTuple, 1, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value2 */ - function _getValue2(ResourceId _tableId) internal view returns (bool value2) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = StoreCore.getStaticField(_tableId, _keyTuple, 1, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Get value2 (using the specified store) */ - function getValue2(IStore _store, ResourceId _tableId) internal view returns (bool value2) { - bytes32[] memory _keyTuple = new bytes32[](0); - - bytes32 _blob = _store.getStaticField(_tableId, _keyTuple, 1, _fieldLayout); - return (_toBool(uint8(bytes1(_blob)))); - } - - /** Set value2 */ - function setValue2(ResourceId _tableId, bool value2) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setStaticField(_tableId, _keyTuple, 1, abi.encodePacked((value2)), _fieldLayout); - } - - /** Set value2 */ - function _setValue2(ResourceId _tableId, bool value2) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setStaticField(_tableId, _keyTuple, 1, abi.encodePacked((value2)), _fieldLayout); - } - - /** Set value2 (using the specified store) */ - function setValue2(IStore _store, ResourceId _tableId, bool value2) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setStaticField(_tableId, _keyTuple, 1, abi.encodePacked((value2)), _fieldLayout); - } - - /** Get the full data */ - function get(ResourceId _tableId) internal view returns (TwoFieldsData memory _table) { - bytes32[] memory _keyTuple = new bytes32[](0); - - (bytes memory _staticData, PackedCounter _encodedLengths, bytes memory _dynamicData) = StoreSwitch.getRecord( - _tableId, - _keyTuple, - _fieldLayout - ); - return decode(_staticData, _encodedLengths, _dynamicData); - } - - /** Get the full data */ - function _get(ResourceId _tableId) internal view returns (TwoFieldsData memory _table) { - bytes32[] memory _keyTuple = new bytes32[](0); - - (bytes memory _staticData, PackedCounter _encodedLengths, bytes memory _dynamicData) = StoreCore.getRecord( - _tableId, - _keyTuple, - _fieldLayout - ); - return decode(_staticData, _encodedLengths, _dynamicData); - } - - /** Get the full data (using the specified store) */ - function get(IStore _store, ResourceId _tableId) internal view returns (TwoFieldsData memory _table) { - bytes32[] memory _keyTuple = new bytes32[](0); - - (bytes memory _staticData, PackedCounter _encodedLengths, bytes memory _dynamicData) = _store.getRecord( - _tableId, - _keyTuple, - _fieldLayout - ); - return decode(_staticData, _encodedLengths, _dynamicData); - } - - /** Set the full data using individual values */ - function set(ResourceId _tableId, bool value1, bool value2) internal { - bytes memory _staticData = encodeStatic(value1, value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData); - } - - /** Set the full data using individual values */ - function _set(ResourceId _tableId, bool value1, bool value2) internal { - bytes memory _staticData = encodeStatic(value1, value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData, _fieldLayout); - } - - /** Set the full data using individual values (using the specified store) */ - function set(IStore _store, ResourceId _tableId, bool value1, bool value2) internal { - bytes memory _staticData = encodeStatic(value1, value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData); - } - - /** Set the full data using the data struct */ - function set(ResourceId _tableId, TwoFieldsData memory _table) internal { - bytes memory _staticData = encodeStatic(_table.value1, _table.value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData); - } - - /** Set the full data using the data struct */ - function _set(ResourceId _tableId, TwoFieldsData memory _table) internal { - bytes memory _staticData = encodeStatic(_table.value1, _table.value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData, _fieldLayout); - } - - /** Set the full data using the data struct (using the specified store) */ - function set(IStore _store, ResourceId _tableId, TwoFieldsData memory _table) internal { - bytes memory _staticData = encodeStatic(_table.value1, _table.value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.setRecord(_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData); - } - - /** - * Decode the tightly packed blob of static data using this table's field layout - * Undefined behaviour for invalid blobs - */ - function decodeStatic(bytes memory _blob) internal pure returns (bool value1, bool value2) { - value1 = (_toBool(uint8(Bytes.slice1(_blob, 0)))); - - value2 = (_toBool(uint8(Bytes.slice1(_blob, 1)))); - } - - /** - * Decode the tightly packed blob using this table's field layout. - * Undefined behaviour for invalid blobs. - */ - function decode( - bytes memory _staticData, - PackedCounter, - bytes memory - ) internal pure returns (TwoFieldsData memory _table) { - (_table.value1, _table.value2) = decodeStatic(_staticData); - } - - /** Delete all data for given keys */ - function deleteRecord(ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreSwitch.deleteRecord(_tableId, _keyTuple); - } - - /** Delete all data for given keys */ - function _deleteRecord(ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - StoreCore.deleteRecord(_tableId, _keyTuple, _fieldLayout); - } - - /** Delete all data for given keys (using the specified store) */ - function deleteRecord(IStore _store, ResourceId _tableId) internal { - bytes32[] memory _keyTuple = new bytes32[](0); - - _store.deleteRecord(_tableId, _keyTuple); - } - - /** Tightly pack static data using this table's schema */ - function encodeStatic(bool value1, bool value2) internal pure returns (bytes memory) { - return abi.encodePacked(value1, value2); - } - - /** Tightly pack full data using this table's field layout */ - function encode(bool value1, bool value2) internal pure returns (bytes memory, PackedCounter, bytes memory) { - bytes memory _staticData = encodeStatic(value1, value2); - - PackedCounter _encodedLengths; - bytes memory _dynamicData; - - return (_staticData, _encodedLengths, _dynamicData); - } - - /** Encode keys as a bytes32 array using this table's field layout */ - function encodeKeyTuple() internal pure returns (bytes32[] memory) { - bytes32[] memory _keyTuple = new bytes32[](0); - - return _keyTuple; - } -} - -function _toBool(uint8 value) pure returns (bool result) { - assembly { - result := value - } -} diff --git a/packages/world/src/version.sol b/packages/world/src/version.sol index 1b316042fe..44dfc1f624 100644 --- a/packages/world/src/version.sol +++ b/packages/world/src/version.sol @@ -2,9 +2,10 @@ pragma solidity >=0.8.24; /** - * @dev World Version Constant - * Defines the version identifier for the World contract or module. - * This version identifier can be used for version checks, logging, and more. + * @title World version + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) + * @notice Contains a constant representing the version of the World. */ +/// @dev Identifier for the current World version. bytes32 constant WORLD_VERSION = "1.0.0-unaudited"; diff --git a/packages/world/src/worldResourceTypes.sol b/packages/world/src/worldResourceTypes.sol index 34e3538485..0d820b3e99 100644 --- a/packages/world/src/worldResourceTypes.sol +++ b/packages/world/src/worldResourceTypes.sol @@ -4,9 +4,7 @@ pragma solidity >=0.8.24; import { RESOURCE_TABLE, RESOURCE_OFFCHAIN_TABLE } from "@latticexyz/store/src/storeResourceTypes.sol"; /** - * @dev World Resource Types - * @dev Constants related to World Resource Types and Masks. - * @dev These constants are used to represent various resource types within the system. + * @dev Constants used to work with world resource types. */ // Resource that identifies a namespace, a container belonging to a diff --git a/packages/world/test/World.t.sol b/packages/world/test/World.t.sol index 9995d26988..c1149e28db 100644 --- a/packages/world/test/World.t.sol +++ b/packages/world/test/World.t.sol @@ -15,7 +15,7 @@ import { FieldLayoutEncodeHelper } from "@latticexyz/store/test/FieldLayoutEncod import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter } from "@latticexyz/store/src/PackedCounter.sol"; import { SchemaEncodeHelper } from "@latticexyz/store/test/SchemaEncodeHelper.sol"; -import { Tables, ResourceIds, TablesTableId } from "@latticexyz/store/src/codegen/index.sol"; +import { Tables, ResourceIds } from "@latticexyz/store/src/codegen/index.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; import { ALL, BEFORE_SET_RECORD, AFTER_SET_RECORD, BEFORE_SPLICE_STATIC_DATA, AFTER_SPLICE_STATIC_DATA, BEFORE_SPLICE_DYNAMIC_DATA, AFTER_SPLICE_DYNAMIC_DATA, BEFORE_DELETE_RECORD, AFTER_DELETE_RECORD } from "@latticexyz/store/src/storeHookTypes.sol"; import { RevertSubscriber } from "@latticexyz/store/test/RevertSubscriber.sol"; @@ -32,7 +32,7 @@ import { SystemHook } from "../src/SystemHook.sol"; import { BEFORE_CALL_SYSTEM, AFTER_CALL_SYSTEM } from "../src/systemHookTypes.sol"; import { Module, IModule } from "../src/Module.sol"; -import { NamespaceOwner, NamespaceOwnerTableId } from "../src/codegen/tables/NamespaceOwner.sol"; +import { NamespaceOwner } from "../src/codegen/tables/NamespaceOwner.sol"; import { ResourceAccess } from "../src/codegen/tables/ResourceAccess.sol"; import { AccessManagementSystem } from "../src/modules/init/implementations/AccessManagementSystem.sol"; @@ -259,17 +259,17 @@ contract WorldTest is Test, GasReporter { } // Should have registered the table data table (fka schema table) - assertEq(FieldLayout.unwrap(Tables.getFieldLayout(TablesTableId)), FieldLayout.unwrap(Tables.getFieldLayout())); - assertEq(Tables.getAbiEncodedKeyNames(TablesTableId), abi.encode(Tables.getKeyNames())); - assertEq(Tables.getAbiEncodedFieldNames(TablesTableId), abi.encode(Tables.getFieldNames())); + assertEq(FieldLayout.unwrap(Tables.getFieldLayout(Tables._tableId)), FieldLayout.unwrap(Tables._fieldLayout)); + assertEq(Tables.getAbiEncodedKeyNames(Tables._tableId), abi.encode(Tables.getKeyNames())); + assertEq(Tables.getAbiEncodedFieldNames(Tables._tableId), abi.encode(Tables.getFieldNames())); // Should have registered the namespace owner table assertEq( - FieldLayout.unwrap(Tables.getFieldLayout(NamespaceOwnerTableId)), - FieldLayout.unwrap(NamespaceOwner.getFieldLayout()) + FieldLayout.unwrap(Tables.getFieldLayout(NamespaceOwner._tableId)), + FieldLayout.unwrap(NamespaceOwner._fieldLayout) ); - assertEq(Tables.getAbiEncodedKeyNames(NamespaceOwnerTableId), abi.encode(NamespaceOwner.getKeyNames())); - assertEq(Tables.getAbiEncodedFieldNames(NamespaceOwnerTableId), abi.encode(NamespaceOwner.getFieldNames())); + assertEq(Tables.getAbiEncodedKeyNames(NamespaceOwner._tableId), abi.encode(NamespaceOwner.getKeyNames())); + assertEq(Tables.getAbiEncodedFieldNames(NamespaceOwner._tableId), abi.encode(NamespaceOwner.getFieldNames())); // Expect it to not be possible to initialize the World again vm.expectRevert(abi.encodeWithSelector(IWorldErrors.World_AlreadyInitialized.selector)); @@ -595,9 +595,9 @@ contract WorldTest is Test, GasReporter { ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: "", name: "testTable" }); world.registerTable( tableId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); @@ -704,9 +704,9 @@ contract WorldTest is Test, GasReporter { ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: "namespace", name: "name" }); world.registerTable( tableId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); @@ -740,9 +740,9 @@ contract WorldTest is Test, GasReporter { ); world.registerTable( systemId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); @@ -753,9 +753,9 @@ contract WorldTest is Test, GasReporter { ); world.registerTable( tableId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); @@ -779,9 +779,9 @@ contract WorldTest is Test, GasReporter { // Register a new table world.registerTable( tableId, - TwoFields.getFieldLayout(), - TwoFields.getKeySchema(), - TwoFields.getValueSchema(), + TwoFields._fieldLayout, + TwoFields._keySchema, + TwoFields._valueSchema, new string[](0), new string[](2) ); @@ -809,8 +809,8 @@ contract WorldTest is Test, GasReporter { bytes14 namespace = "testSetField"; bytes16 name = "testTable"; ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: namespace, name: name }); - FieldLayout fieldLayout = Bool.getFieldLayout(); - Schema valueSchema = Bool.getValueSchema(); + FieldLayout fieldLayout = Bool._fieldLayout; + Schema valueSchema = Bool._valueSchema; world.registerNamespace(tableId.getNamespaceId()); // Register a new table @@ -839,8 +839,8 @@ contract WorldTest is Test, GasReporter { bytes14 namespace = "testPushField"; bytes16 name = "testTable"; ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: namespace, name: name }); - FieldLayout fieldLayout = AddressArray.getFieldLayout(); - Schema valueSchema = AddressArray.getValueSchema(); + FieldLayout fieldLayout = AddressArray._fieldLayout; + Schema valueSchema = AddressArray._valueSchema; // Register a new table world.registerNamespace(tableId.getNamespaceId()); @@ -885,8 +885,8 @@ contract WorldTest is Test, GasReporter { bytes14 namespace = "testDeleteReco"; bytes16 name = "testTable"; ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: namespace, name: name }); - FieldLayout fieldLayout = Bool.getFieldLayout(); - Schema valueSchema = Bool.getValueSchema(); + FieldLayout fieldLayout = Bool._fieldLayout; + Schema valueSchema = Bool._valueSchema; // Register a new table world.registerNamespace(tableId.getNamespaceId()); @@ -1268,8 +1268,8 @@ contract WorldTest is Test, GasReporter { } function testRegisterStoreHook() public { - FieldLayout fieldLayout = Bool.getFieldLayout(); - Schema valueSchema = Bool.getValueSchema(); + FieldLayout fieldLayout = Bool._fieldLayout; + Schema valueSchema = Bool._valueSchema; ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: "", name: "testTable" }); // Register a new table @@ -1335,8 +1335,8 @@ contract WorldTest is Test, GasReporter { } function testUnregisterStoreHook() public { - FieldLayout fieldLayout = Bool.getFieldLayout(); - Schema valueSchema = Bool.getValueSchema(); + FieldLayout fieldLayout = Bool._fieldLayout; + Schema valueSchema = Bool._valueSchema; ResourceId tableId = WorldResourceIdLib.encode({ typeId: RESOURCE_TABLE, namespace: "", name: "testTable" }); // Register a new table @@ -1522,9 +1522,9 @@ contract WorldTest is Test, GasReporter { world.registerNamespace(tableId.getNamespaceId()); world.registerTable( tableId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); @@ -1551,9 +1551,9 @@ contract WorldTest is Test, GasReporter { world.registerNamespace(tableId.getNamespaceId()); world.registerTable( tableId, - Bool.getFieldLayout(), + Bool._fieldLayout, defaultKeySchema, - Bool.getValueSchema(), + Bool._valueSchema, new string[](1), new string[](1) ); diff --git a/packages/world/test/WorldDynamicUpdate.t.sol b/packages/world/test/WorldDynamicUpdate.t.sol index 3dff138231..cead1a8d96 100644 --- a/packages/world/test/WorldDynamicUpdate.t.sol +++ b/packages/world/test/WorldDynamicUpdate.t.sol @@ -53,8 +53,8 @@ contract UpdateInDynamicFieldTest is Test, GasReporter { keyTuple = new bytes32[](1); keyTuple[0] = key; singletonKey = new bytes32[](0); - FieldLayout fieldLayout = AddressArray.getFieldLayout(); - Schema valueSchema = AddressArray.getValueSchema(); + FieldLayout fieldLayout = AddressArray._fieldLayout; + Schema valueSchema = AddressArray._valueSchema; // Initialize the data in setUp so that slots aren't warm in tests (to test cold update) @@ -83,7 +83,7 @@ contract UpdateInDynamicFieldTest is Test, GasReporter { } function testPopFromDynamicField() public { - FieldLayout fieldLayout = AddressArray.getFieldLayout(); + FieldLayout fieldLayout = AddressArray._fieldLayout; // Expect the data to be written assertEq(AddressArray.get(tableId, key), initData); diff --git a/packages/world/test/codegen/tables/AddressArray.sol b/packages/world/test/codegen/tables/AddressArray.sol index 406f83d870..c34bcb9b8b 100644 --- a/packages/world/test/codegen/tables/AddressArray.sol +++ b/packages/world/test/codegen/tables/AddressArray.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,45 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0000000100000000000000000000000000000000000000000000000000000000 -); - library AddressArray { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0000000100000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.ADDRESS_ARRAY; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (address[]) + Schema constant _valueSchema = Schema.wrap(0x00000001c3000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -76,14 +47,14 @@ library AddressArray { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/test/codegen/tables/Bool.sol b/packages/world/test/codegen/tables/Bool.sol index 43d6b8fca3..913347c8b6 100644 --- a/packages/world/test/codegen/tables/Bool.sol +++ b/packages/world/test/codegen/tables/Bool.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,44 +11,19 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0001010001000000000000000000000000000000000000000000000000000000 -); - library Bool { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0001010001000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool) + Schema constant _valueSchema = Schema.wrap(0x0001010060000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -74,14 +46,14 @@ library Bool { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/test/codegen/tables/TwoFields.sol b/packages/world/test/codegen/tables/TwoFields.sol index da4b7035a8..23221674fc 100644 --- a/packages/world/test/codegen/tables/TwoFields.sol +++ b/packages/world/test/codegen/tables/TwoFields.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,50 +11,24 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0002020001010000000000000000000000000000000000000000000000000000 -); - struct TwoFieldsData { bool value1; bool value2; } library TwoFields { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); - - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0002020001010000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](2); - _valueSchema[0] = SchemaType.BOOL; - _valueSchema[1] = SchemaType.BOOL; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (bool, bool) + Schema constant _valueSchema = Schema.wrap(0x0002020060600000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -81,14 +52,14 @@ library TwoFields { * @notice Register the table with its config. */ function register(ResourceId _tableId) internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register(ResourceId _tableId) internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/packages/world/ts/config/resolveWorldConfig.ts b/packages/world/ts/config/resolveWorldConfig.ts index d2b3830d19..db54d6f0f5 100644 --- a/packages/world/ts/config/resolveWorldConfig.ts +++ b/packages/world/ts/config/resolveWorldConfig.ts @@ -28,7 +28,7 @@ export function resolveWorldConfig(config: StoreConfig & WorldConfig, existingCo // Combine the default and overridden system names and filter out excluded systems const systemNames = [...new Set([...defaultSystemNames, ...overriddenSystemNames])].filter( - (name) => !config.excludeSystems.includes(name) + (name) => !config.excludeSystems.includes(name), ); // Resolve the config diff --git a/packages/world/ts/config/types.ts b/packages/world/ts/config/types.ts index 5cb70b6910..3a590229f0 100644 --- a/packages/world/ts/config/types.ts +++ b/packages/world/ts/config/types.ts @@ -5,30 +5,29 @@ import { zWorldConfig } from "./worldConfig"; import { SYSTEM_DEFAULTS } from "./defaults"; // zod doesn't preserve doc comments -export type SystemUserConfig = +export type SystemUserConfig = { + /** The full resource selector consists of namespace and name */ + name?: string; + /** + * Register function selectors for the system in the World. + * Defaults to true. + * Note: + * - For root systems all World function selectors will correspond to the system's function selectors. + * - For non-root systems, the World function selectors will be __. + */ + registerFunctionSelectors?: boolean; +} & ( | { - /** The full resource selector consists of namespace and name */ - name?: string; - /** - * Register function selectors for the system in the World. - * Defaults to true. - * Note: - * - For root systems all World function selectors will correspond to the system's function selectors. - * - For non-root systems, the World function selectors will be __. - */ - registerFunctionSelectors?: boolean; - } & ( - | { - /** If openAccess is true, any address can call the system */ - openAccess?: true; - } - | { - /** If openAccess is false, only the addresses or systems in `access` can call the system */ - openAccess: false; - /** An array of addresses or system names that can access the system */ - accessList: string[]; - } - ); + /** If openAccess is true, any address can call the system */ + openAccess?: true; + } + | { + /** If openAccess is false, only the addresses or systems in `access` can call the system */ + openAccess: false; + /** An array of addresses or system names that can access the system */ + accessList: string[]; + } +); export interface ExpandSystemConfig extends OrDefaults< diff --git a/packages/world/ts/config/worldConfig.ts b/packages/world/ts/config/worldConfig.ts index ecd579ac7f..71d56c8de7 100644 --- a/packages/world/ts/config/worldConfig.ts +++ b/packages/world/ts/config/worldConfig.ts @@ -20,7 +20,7 @@ const zSystemConfig = z.intersection( openAccess: z.literal(false), accessList: zSystemAccessList, }), - ]) + ]), ); const zValueWithType = z.object({ diff --git a/packages/world/ts/encodeSystemCalls.ts b/packages/world/ts/encodeSystemCalls.ts index fe027924da..f93301da43 100644 --- a/packages/world/ts/encodeSystemCalls.ts +++ b/packages/world/ts/encodeSystemCalls.ts @@ -6,7 +6,7 @@ import type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from "abitype" /** Encode system calls to be passed as arguments into `World.batchCall` */ export function encodeSystemCalls>( abi: abi, - systemCalls: readonly Omit, "abi">[] + systemCalls: readonly Omit, "abi">[], ): AbiParametersToPrimitiveTypes["inputs"]>[] { return systemCalls.map((systemCall) => encodeSystemCall({ ...systemCall, abi } as SystemCall)); } diff --git a/packages/world/ts/encodeSystemCallsFrom.ts b/packages/world/ts/encodeSystemCallsFrom.ts index f5c9bf548e..0e0b40d0da 100644 --- a/packages/world/ts/encodeSystemCallsFrom.ts +++ b/packages/world/ts/encodeSystemCallsFrom.ts @@ -7,9 +7,9 @@ import type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from "abitype" export function encodeSystemCallsFrom>( abi: abi, from: Address, - systemCalls: readonly Omit, "abi" | "from">[] + systemCalls: readonly Omit, "abi" | "from">[], ): AbiParametersToPrimitiveTypes["inputs"]>[] { return systemCalls.map((systemCall) => - encodeSystemCallFrom({ ...systemCall, abi, from } as SystemCallFrom) + encodeSystemCallFrom({ ...systemCall, abi, from } as SystemCallFrom), ); } diff --git a/packages/world/ts/node/render-solidity/renderSystemInterface.ts b/packages/world/ts/node/render-solidity/renderSystemInterface.ts index b3a6ce7a92..ceb3be23da 100644 --- a/packages/world/ts/node/render-solidity/renderSystemInterface.ts +++ b/packages/world/ts/node/render-solidity/renderSystemInterface.ts @@ -10,7 +10,8 @@ export function renderSystemInterface(options: RenderSystemInterfaceOptions) { ${renderImports(imports)} /** - * @title ${name} + * @title ${name} + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface ${name} { @@ -22,7 +23,7 @@ export function renderSystemInterface(options: RenderSystemInterfaceOptions) { function ${functionPrefix}${name}( ${renderArguments(parameters)} ) external ${stateMutability} ${renderReturnParameters(returnParameters)}; - ` + `, )} } `; diff --git a/packages/world/ts/node/render-solidity/renderWorldInterface.ts b/packages/world/ts/node/render-solidity/renderWorldInterface.ts index e5e4eaee16..3391bec587 100644 --- a/packages/world/ts/node/render-solidity/renderWorldInterface.ts +++ b/packages/world/ts/node/render-solidity/renderWorldInterface.ts @@ -31,7 +31,8 @@ export function renderWorldInterface(options: RenderWorldOptions) { ${renderRelativeImports(imports)} /** - * @title ${interfaceName} + * @title ${interfaceName} + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. diff --git a/packages/world/ts/node/render-solidity/worldgen.ts b/packages/world/ts/node/render-solidity/worldgen.ts index f9dbf77d37..af5313ead3 100644 --- a/packages/world/ts/node/render-solidity/worldgen.ts +++ b/packages/world/ts/node/render-solidity/worldgen.ts @@ -10,11 +10,11 @@ import { WorldConfig } from "../../config/types"; export async function worldgen( config: StoreConfig & WorldConfig, existingContracts: { path: string; basename: string }[], - outputBaseDirectory: string + outputBaseDirectory: string, ) { const resolvedConfig = resolveWorldConfig( config, - existingContracts.map(({ basename }) => basename) + existingContracts.map(({ basename }) => basename), ); const worldgenBaseDirectory = path.join(outputBaseDirectory, config.worldgenDirectory); diff --git a/packages/world/ts/worldEvents.test.ts b/packages/world/ts/worldEvents.test.ts index 080a1740fa..477e61127e 100644 --- a/packages/world/ts/worldEvents.test.ts +++ b/packages/world/ts/worldEvents.test.ts @@ -19,7 +19,7 @@ function normalizeAbiEvent(event: AbiEvent) { describe("WorldFactory events", () => { it("should match the ABI", () => { const forgeAbiItem = IWorldFactoryAbi.find( - (item) => item.type === "event" && item.name === "WorldDeployed" + (item) => item.type === "event" && item.name === "WorldDeployed", ) as AbiEvent; expect(normalizeAbiEvent(parseAbiItem(worldDeployedEvent))).toMatchObject(normalizeAbiEvent(forgeAbiItem)); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ebfc36e2f1..32fd2a7753 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,11 +39,11 @@ importers: specifier: '>=10' version: 10.0.0 prettier: - specifier: ^2.8.4 - version: 2.8.4 + specifier: 3.2.5 + version: 3.2.5 prettier-plugin-solidity: - specifier: 1.1.3 - version: 1.1.3(prettier@2.8.4) + specifier: 1.3.1 + version: 1.3.1(prettier@3.2.5) rimraf: specifier: ^3.0.2 version: 3.0.2 @@ -282,11 +282,11 @@ importers: specifier: ^5.1.2 version: 5.1.2 prettier: - specifier: ^2.8.4 - version: 2.8.4 + specifier: 3.2.5 + version: 3.2.5 prettier-plugin-solidity: - specifier: 1.1.3 - version: 1.1.3(prettier@2.8.4) + specifier: 1.3.1 + version: 1.3.1(prettier@3.2.5) viem: specifier: 2.7.12 version: 2.7.12(typescript@5.1.6)(zod@3.21.4) @@ -729,6 +729,9 @@ importers: '@latticexyz/config': specifier: workspace:* version: link:../config + '@latticexyz/protocol-parser': + specifier: workspace:* + version: link:../protocol-parser '@latticexyz/schema-type': specifier: workspace:* version: link:../schema-type @@ -3092,6 +3095,10 @@ packages: resolution: {integrity: sha512-ESipEcHyRHg4Np4SqBCfcXwyxxna1DgFVz69bgpLV8vzl/NP1DtcKsJ4dJZXWQhY/Z4J2LeKBiOkOVZn9ct33Q==} dependencies: antlr4ts: 0.5.0-alpha.4 + dev: false + + /@solidity-parser/parser@0.17.0: + resolution: {integrity: sha512-Nko8R0/kUo391jsEHHxrGM07QFdnPGvlmox4rmH0kNiNAashItAilhy4Mv4pK5gQmW5f4sXAF58fwJbmlkGcVw==} /@testing-library/react-hooks@8.0.1(@types/react@18.2.22)(react-test-renderer@18.2.0)(react@18.2.0): resolution: {integrity: sha512-Aqhl2IVmLt8IovEVarNDFuJDVWVvhnr9/GCU6UUnrYXwgDFF9h2L2o2P9KBni1AST5sT6riAyoukFLyjQUgD/g==} @@ -3381,8 +3388,8 @@ packages: resolution: {integrity: sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==} dev: true - /@types/prettier@2.7.2: - resolution: {integrity: sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==} + /@types/prettier@2.7.3: + resolution: {integrity: sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==} dev: true /@types/prop-types@15.7.5: @@ -7308,7 +7315,7 @@ packages: '@jest/transform': 29.5.0 '@jest/types': 29.5.0 '@types/babel__traverse': 7.18.3 - '@types/prettier': 2.7.2 + '@types/prettier': 2.7.3 babel-preset-current-node-syntax: 1.0.1(@babel/core@7.21.4) chalk: 4.1.2 expect: 29.5.0 @@ -8911,16 +8918,16 @@ packages: engines: {node: '>= 0.8.0'} dev: true - /prettier-plugin-solidity@1.1.3(prettier@2.8.4): - resolution: {integrity: sha512-fQ9yucPi2sBbA2U2Xjh6m4isUTJ7S7QLc/XDDsktqqxYfTwdYKJ0EnnywXHwCGAaYbQNK+HIYPL1OemxuMsgeg==} - engines: {node: '>=12'} + /prettier-plugin-solidity@1.3.1(prettier@3.2.5): + resolution: {integrity: sha512-MN4OP5I2gHAzHZG1wcuJl0FsLS3c4Cc5494bbg+6oQWBPuEamjwDvmGfFMZ6NFzsh3Efd9UUxeT7ImgjNH4ozA==} + engines: {node: '>=16'} peerDependencies: - prettier: '>=2.3.0 || >=3.0.0-alpha.0' + prettier: '>=2.3.0' dependencies: - '@solidity-parser/parser': 0.16.0 - prettier: 2.8.4 - semver: 7.5.0 - solidity-comments-extractor: 0.0.7 + '@solidity-parser/parser': 0.17.0 + prettier: 3.2.5 + semver: 7.6.0 + solidity-comments-extractor: 0.0.8 /prettier@1.19.1: resolution: {integrity: sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==} @@ -8934,6 +8941,12 @@ packages: resolution: {integrity: sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw==} engines: {node: '>=10.13.0'} hasBin: true + dev: true + + /prettier@3.2.5: + resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==} + engines: {node: '>=14'} + hasBin: true /pretty-format@27.5.1: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} @@ -9538,6 +9551,13 @@ packages: dependencies: lru-cache: 6.0.0 + /semver@7.6.0: + resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} + engines: {node: '>=10'} + hasBin: true + dependencies: + lru-cache: 6.0.0 + /set-blocking@2.0.0: resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} @@ -9694,8 +9714,8 @@ packages: - supports-color dev: true - /solidity-comments-extractor@0.0.7: - resolution: {integrity: sha512-wciNMLg/Irp8OKGrh3S2tfvZiZ0NEyILfcRCXCD4mp7SgK/i9gzLfhY2hY7VMCQJ3kH9UB9BzNdibIVMchzyYw==} + /solidity-comments-extractor@0.0.8: + resolution: {integrity: sha512-htM7Vn6LhHreR+EglVMd2s+sZhcXAirB1Zlyrv5zBuTxieCvjfnRpd7iZk75m/u6NOlEyQ94C6TWbBn2cY7w8g==} /sonic-boom@3.3.0: resolution: {integrity: sha512-LYxp34KlZ1a2Jb8ZQgFCK3niIHzibdwtwNUWKg0qQRzsDoJ3Gfgkf8KdBTFU3SkejDEIlWwnSnpVdOZIhFMl/g==} diff --git a/scripts/changelog.ts b/scripts/changelog.ts index 9daee85ea1..42e4c61049 100644 --- a/scripts/changelog.ts +++ b/scripts/changelog.ts @@ -116,7 +116,7 @@ async function getChanges(include: "diff" | "all") { const changeset = readFileSync(changesetPath).toString(); const gitLog = (await execa("git", ["log", changesetPath])).stdout; return { ...parseChangeset(changeset), ...parseGitLog(gitLog) }; - }) + }), ); // Sort the changesets into patch, minor and major updates diff --git a/scripts/render-api-docs.ts b/scripts/render-api-docs.ts index 24cb0b6d3d..f0925af297 100644 --- a/scripts/render-api-docs.ts +++ b/scripts/render-api-docs.ts @@ -20,6 +20,7 @@ const PUBLIC_APIS: PublicApis = { { source: "store/src/StoreSwitch.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "store"); content = fixInheritence(content); @@ -42,6 +43,7 @@ const PUBLIC_APIS: PublicApis = { { source: "store/src/IStoreRegistration.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "store"); content = fixInheritence(content); @@ -58,6 +60,7 @@ const PUBLIC_APIS: PublicApis = { }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "store"); content = fixInheritence(content); @@ -86,6 +89,7 @@ const PUBLIC_APIS: PublicApis = { { source: "store/src/version.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "store"); content = fixInheritence(content); @@ -106,6 +110,7 @@ const PUBLIC_APIS: PublicApis = { }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -116,6 +121,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/internal/create.mdx": { inputFiles: [{ source: "world/src/Create2.sol" }, { source: "world/src/Create2Factory.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -125,6 +131,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/internal/delegation.mdx": { inputFiles: [{ source: "world/src/Delegation.sol" }, { source: "world/src/DelegationControl.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -134,6 +141,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/delegation-external.mdx": { inputFiles: [{ source: "world/src/IDelegationControl.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -145,6 +153,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/internal/erc165.mdx": { inputFiles: [{ source: "world/src/ERC165Checker.sol" }, { source: "world/src/requireInterface.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -156,6 +165,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/internal/erc165-external.mdx": { inputFiles: [{ source: "world/src/IERC165.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -165,6 +175,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/module.mdx": { inputFiles: [{ source: "world/src/Module.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -175,6 +186,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/module-external.mdx": { inputFiles: [{ source: "world/src/IModule.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -188,6 +200,7 @@ const PUBLIC_APIS: PublicApis = { { source: "world/src/systemHookTypes.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -197,6 +210,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/internal/systemcall.mdx": { inputFiles: [{ source: "world/src/SystemCall.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -208,6 +222,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/system-external.mdx": { inputFiles: [{ source: "world/src/ISystemHook.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -217,6 +232,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/world.mdx": { inputFiles: [{ source: "world/src/World.sol" }, { source: "world/src/WorldFactory.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -248,18 +264,19 @@ const PUBLIC_APIS: PublicApis = { { source: "world/src/IWorldFactory.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); content = addSampleCodeFunction( content, "grantAccess", - "/world/namespaces-access-control#modifying-access-control" + "/world/namespaces-access-control#modifying-access-control", ); content = addSampleCodeFunction( content, "revokeAccess", - "/world/namespaces-access-control#modifying-access-control" + "/world/namespaces-access-control#modifying-access-control", ); content = addSampleCodeFunction(content, "registerTable", "/store/tables#manually-register-a-table"); content = addSampleCodeFunction(content, "call", "/world/systems#using-call"); @@ -268,7 +285,7 @@ const PUBLIC_APIS: PublicApis = { content = addSampleCodeFunction( content, "registerRootFunctionSelector", - "/world/function-selectors#root-function-selectors" + "/world/function-selectors#root-function-selectors", ); content = addSampleCodeFunction(content, "transferBalanceToAddress", "/world/balance"); @@ -277,7 +294,7 @@ const PUBLIC_APIS: PublicApis = { .replaceAll("This is an autogenerated file; do not edit manually", "") .replaceAll( "*This interface is automatically generated from the corresponding system contract. Do not edit manually.*", - "" + "", ) .replace(/## StoreData((.|\n)*?)### Functions/m, "### Functions") .replace(/#### constructor((.|\n)*?)#### storeVersion/m, "#### storeVersion") @@ -294,6 +311,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/world-context.mdx": { inputFiles: [{ source: "world/src/WorldContext.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -303,6 +321,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/world-context-external.mdx": { inputFiles: [{ source: "world/src/IWorldContextConsumer.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -312,6 +331,7 @@ const PUBLIC_APIS: PublicApis = { "world/reference/resource-ids.mdx": { inputFiles: [{ source: "world/src/WorldResourceId.sol" }, { source: "world/src/worldResourceTypes.sol" }], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -330,6 +350,7 @@ const PUBLIC_APIS: PublicApis = { { source: "world/src/version.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -345,6 +366,7 @@ const PUBLIC_APIS: PublicApis = { { source: "world/src/modules/init/types.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -361,6 +383,7 @@ const PUBLIC_APIS: PublicApis = { { source: "world/src/modules/init/implementations/WorldRegistrationSystem.sol" }, ], processContent: (content) => { + content = removeAuthor(content); content = formatHeadings(content); content = fixGithubLinks(content, "world"); content = fixInheritence(content); @@ -370,7 +393,7 @@ const PUBLIC_APIS: PublicApis = { content = addSampleCodeFunction( content, "registerRootFunctionSelector", - "/world/function-selectors#root-function-selectors" + "/world/function-selectors#root-function-selectors", ); content = addSampleCodeFunction(content, "transferBalanceToAddress", "/world/balance"); @@ -404,6 +427,10 @@ function fixInheritence(content: string) { return newContent; } +function removeAuthor(content: string) { + return content.replace(/\*\*Author:\*\*\n[^\n]+\n/g, ""); +} + // The inheritence links that need to be fixed const inheritence = [ { contract: "StoreRead", link: "/store/reference/store-core#storeread" }, @@ -457,9 +484,9 @@ function addSampleCodeContract(content: string, contract: string, url: string): .replace( ")", `) | - | - | - |` + | - | - |`, ) - .replace("[Git Source](", `| [Usage Sample](${url}) | [Git Source](`) + .replace("[Git Source](", `| [Usage Sample](${url}) | [Git Source](`), ); } @@ -470,8 +497,8 @@ function addSampleCodeFunction(content: string, heading: string, url: string): s "\n", ` [Usage Sample](${url}) - ` - ) + `, + ), ); } @@ -498,7 +525,7 @@ function getPackages() { Object.values(PUBLIC_APIS) .map(({ inputFiles }) => inputFiles) .flat() - .map((input) => input.source.split("/")[0]) + .map((input) => input.source.split("/")[0]), ), ]; } @@ -548,11 +575,11 @@ async function renderDocs() { .map((fileName) => readFileSync(path.join(docsPath, fileName), { encoding: "utf8" })); }) .flat() - .join("\n") + .join("\n"), ); // Write the output file - writeFileSync(path.join(DOCS_ROOT, outputFile), formatMarkdown(content)); + writeFileSync(path.join(DOCS_ROOT, outputFile), await formatMarkdown(content)); } } diff --git a/templates/phaser/package.json b/templates/phaser/package.json index bef09b4664..f50980f9a7 100644 --- a/templates/phaser/package.json +++ b/templates/phaser/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/templates/phaser/packages/client/src/mud/createSystemCalls.ts b/templates/phaser/packages/client/src/mud/createSystemCalls.ts index f3c72c4e9f..fef3e78936 100644 --- a/templates/phaser/packages/client/src/mud/createSystemCalls.ts +++ b/templates/phaser/packages/client/src/mud/createSystemCalls.ts @@ -37,7 +37,7 @@ export function createSystemCalls( * (https://github.com/latticexyz/mud/blob/main/templates/phaser/packages/client/src/mud/setupNetwork.ts#L75-L81). */ { worldContract, waitForTransaction }: SetupNetworkResult, - { Counter }: ClientComponents + { Counter }: ClientComponents, ) { const increment = async () => { /* diff --git a/templates/phaser/packages/client/src/mud/setupNetwork.ts b/templates/phaser/packages/client/src/mud/setupNetwork.ts index 573f059d38..dc58cfb1e5 100644 --- a/templates/phaser/packages/client/src/mud/setupNetwork.ts +++ b/templates/phaser/packages/client/src/mud/setupNetwork.ts @@ -3,13 +3,24 @@ * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ -import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig } from "viem"; +import { + createPublicClient, + fallback, + webSocket, + http, + createWalletClient, + Hex, + parseEther, + ClientConfig, + getContract, +} from "viem"; import { createFaucetService } from "@latticexyz/services/faucet"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; -import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; +import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; +import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; /* @@ -39,6 +50,12 @@ export async function setupNetwork() { const publicClient = createPublicClient(clientOptions); + /* + * Create an observable for contract writes that we can + * pass into MUD dev tools for transaction observability. + */ + const write$ = new Subject(); + /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). @@ -47,13 +64,9 @@ export async function setupNetwork() { const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, - }); - - /* - * Create an observable for contract writes that we can - * pass into MUD dev tools for transaction observability. - */ - const write$ = new Subject(); + }) + .extend(transactionQueue()) + .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. @@ -62,7 +75,6 @@ export async function setupNetwork() { address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, - onWrite: (write) => write$.next(write), }); /* diff --git a/templates/phaser/packages/client/src/ui/App.tsx b/templates/phaser/packages/client/src/ui/App.tsx index a61f2ba87e..7dd4d29641 100644 --- a/templates/phaser/packages/client/src/ui/App.tsx +++ b/templates/phaser/packages/client/src/ui/App.tsx @@ -26,7 +26,7 @@ export const App = () => { worldAbi: networkLayer.network.worldContract.abi, write$: networkLayer.network.write$, recsWorld: networkLayer.world, - }) + }), ); } }, [networkLayer]); diff --git a/templates/phaser/packages/client/src/ui/hooks/usePhaserLayer.tsx b/templates/phaser/packages/client/src/ui/hooks/usePhaserLayer.tsx index ff47610f2c..2d428b0c24 100644 --- a/templates/phaser/packages/client/src/ui/hooks/usePhaserLayer.tsx +++ b/templates/phaser/packages/client/src/ui/hooks/usePhaserLayer.tsx @@ -80,7 +80,7 @@ export const usePhaserLayer = ({ networkLayer }: Props) => { } } }, - [container] + [container], ); return useMemo(() => ({ ref, phaserLayer }), [ref, phaserLayer]); diff --git a/templates/phaser/packages/contracts/package.json b/templates/phaser/packages/contracts/package.json index aa7c055744..b2640d68cd 100644 --- a/templates/phaser/packages/contracts/package.json +++ b/templates/phaser/packages/contracts/package.json @@ -25,8 +25,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", "solhint-plugin-mud": "file:../../../../packages/solhint-plugin-mud" diff --git a/templates/phaser/packages/contracts/src/codegen/index.sol b/templates/phaser/packages/contracts/src/codegen/index.sol index 6364dfc884..2c7020d821 100644 --- a/templates/phaser/packages/contracts/src/codegen/index.sol +++ b/templates/phaser/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Counter, CounterTableId } from "./tables/Counter.sol"; +import { Counter } from "./tables/Counter.sol"; diff --git a/templates/phaser/packages/contracts/src/codegen/tables/Counter.sol b/templates/phaser/packages/contracts/src/codegen/tables/Counter.sol index 40a1f45dcf..829e0b68f4 100644 --- a/templates/phaser/packages/contracts/src/codegen/tables/Counter.sol +++ b/templates/phaser/packages/contracts/src/codegen/tables/Counter.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); -ResourceId constant CounterTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library Counter { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library Counter { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/templates/phaser/packages/contracts/src/codegen/world/IIncrementSystem.sol b/templates/phaser/packages/contracts/src/codegen/world/IIncrementSystem.sol index 14ceb85613..6a1a4db250 100644 --- a/templates/phaser/packages/contracts/src/codegen/world/IIncrementSystem.sol +++ b/templates/phaser/packages/contracts/src/codegen/world/IIncrementSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IIncrementSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IIncrementSystem { diff --git a/templates/phaser/packages/contracts/src/codegen/world/IWorld.sol b/templates/phaser/packages/contracts/src/codegen/world/IWorld.sol index 938ff3572a..34615b56ae 100644 --- a/templates/phaser/packages/contracts/src/codegen/world/IWorld.sol +++ b/templates/phaser/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { IIncrementSystem } from "./IIncrementSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, IIncrementSystem { - -} +interface IWorld is IBaseWorld, IIncrementSystem {} diff --git a/templates/phaser/packages/contracts/test/CounterTest.t.sol b/templates/phaser/packages/contracts/test/CounterTest.t.sol index 2c76d7b300..4946ef57ff 100644 --- a/templates/phaser/packages/contracts/test/CounterTest.t.sol +++ b/templates/phaser/packages/contracts/test/CounterTest.t.sol @@ -6,7 +6,7 @@ import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { Counter, CounterTableId } from "../src/codegen/index.sol"; +import { Counter } from "../src/codegen/index.sol"; contract CounterTest is MudTest { function testWorldExists() public { diff --git a/templates/react-ecs/package.json b/templates/react-ecs/package.json index 80edea1359..58440578e0 100644 --- a/templates/react-ecs/package.json +++ b/templates/react-ecs/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/templates/react-ecs/packages/client/src/index.tsx b/templates/react-ecs/packages/client/src/index.tsx index da8d70f020..1b005dc561 100644 --- a/templates/react-ecs/packages/client/src/index.tsx +++ b/templates/react-ecs/packages/client/src/index.tsx @@ -13,7 +13,7 @@ setup().then(async (result) => { root.render( - + , ); // https://vitejs.dev/guide/env-and-mode.html diff --git a/templates/react-ecs/packages/client/src/mud/createSystemCalls.ts b/templates/react-ecs/packages/client/src/mud/createSystemCalls.ts index 09e7807c6f..30b4f7f6b7 100644 --- a/templates/react-ecs/packages/client/src/mud/createSystemCalls.ts +++ b/templates/react-ecs/packages/client/src/mud/createSystemCalls.ts @@ -31,7 +31,7 @@ export function createSystemCalls( * (https://github.com/latticexyz/mud/blob/main/templates/react/packages/client/src/mud/setupNetwork.ts#L77-L83). */ { worldContract, waitForTransaction }: SetupNetworkResult, - { Counter }: ClientComponents + { Counter }: ClientComponents, ) { const increment = async () => { /* diff --git a/templates/react-ecs/packages/client/src/mud/setupNetwork.ts b/templates/react-ecs/packages/client/src/mud/setupNetwork.ts index 60dfc7bdda..0d1c6ef75b 100644 --- a/templates/react-ecs/packages/client/src/mud/setupNetwork.ts +++ b/templates/react-ecs/packages/client/src/mud/setupNetwork.ts @@ -3,14 +3,25 @@ * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ -import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig } from "viem"; +import { + createPublicClient, + fallback, + webSocket, + http, + createWalletClient, + Hex, + parseEther, + ClientConfig, + getContract, +} from "viem"; import { createFaucetService } from "@latticexyz/services/faucet"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; -import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; +import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; +import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; @@ -41,6 +52,12 @@ export async function setupNetwork() { const publicClient = createPublicClient(clientOptions); + /* + * Create an observable for contract writes that we can + * pass into MUD dev tools for transaction observability. + */ + const write$ = new Subject(); + /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). @@ -49,13 +66,9 @@ export async function setupNetwork() { const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, - }); - - /* - * Create an observable for contract writes that we can - * pass into MUD dev tools for transaction observability. - */ - const write$ = new Subject(); + }) + .extend(transactionQueue()) + .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. @@ -64,7 +77,6 @@ export async function setupNetwork() { address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, - onWrite: (write) => write$.next(write), }); /* diff --git a/templates/react-ecs/packages/contracts/package.json b/templates/react-ecs/packages/contracts/package.json index aa7c055744..b2640d68cd 100644 --- a/templates/react-ecs/packages/contracts/package.json +++ b/templates/react-ecs/packages/contracts/package.json @@ -25,8 +25,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", "solhint-plugin-mud": "file:../../../../packages/solhint-plugin-mud" diff --git a/templates/react-ecs/packages/contracts/src/codegen/index.sol b/templates/react-ecs/packages/contracts/src/codegen/index.sol index 6364dfc884..2c7020d821 100644 --- a/templates/react-ecs/packages/contracts/src/codegen/index.sol +++ b/templates/react-ecs/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Counter, CounterTableId } from "./tables/Counter.sol"; +import { Counter } from "./tables/Counter.sol"; diff --git a/templates/react-ecs/packages/contracts/src/codegen/tables/Counter.sol b/templates/react-ecs/packages/contracts/src/codegen/tables/Counter.sol index 40a1f45dcf..829e0b68f4 100644 --- a/templates/react-ecs/packages/contracts/src/codegen/tables/Counter.sol +++ b/templates/react-ecs/packages/contracts/src/codegen/tables/Counter.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); -ResourceId constant CounterTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library Counter { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library Counter { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/templates/react-ecs/packages/contracts/src/codegen/world/IIncrementSystem.sol b/templates/react-ecs/packages/contracts/src/codegen/world/IIncrementSystem.sol index 14ceb85613..6a1a4db250 100644 --- a/templates/react-ecs/packages/contracts/src/codegen/world/IIncrementSystem.sol +++ b/templates/react-ecs/packages/contracts/src/codegen/world/IIncrementSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IIncrementSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IIncrementSystem { diff --git a/templates/react-ecs/packages/contracts/src/codegen/world/IWorld.sol b/templates/react-ecs/packages/contracts/src/codegen/world/IWorld.sol index 938ff3572a..34615b56ae 100644 --- a/templates/react-ecs/packages/contracts/src/codegen/world/IWorld.sol +++ b/templates/react-ecs/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { IIncrementSystem } from "./IIncrementSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, IIncrementSystem { - -} +interface IWorld is IBaseWorld, IIncrementSystem {} diff --git a/templates/react-ecs/packages/contracts/test/CounterTest.t.sol b/templates/react-ecs/packages/contracts/test/CounterTest.t.sol index 2c76d7b300..4946ef57ff 100644 --- a/templates/react-ecs/packages/contracts/test/CounterTest.t.sol +++ b/templates/react-ecs/packages/contracts/test/CounterTest.t.sol @@ -6,7 +6,7 @@ import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { Counter, CounterTableId } from "../src/codegen/index.sol"; +import { Counter } from "../src/codegen/index.sol"; contract CounterTest is MudTest { function testWorldExists() public { diff --git a/templates/react/package.json b/templates/react/package.json index 16893bf7de..9e94423c4d 100644 --- a/templates/react/package.json +++ b/templates/react/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/templates/react/packages/client/src/index.tsx b/templates/react/packages/client/src/index.tsx index 3ba2a44052..c9b662c9f0 100644 --- a/templates/react/packages/client/src/index.tsx +++ b/templates/react/packages/client/src/index.tsx @@ -13,7 +13,7 @@ setup().then(async (result) => { root.render( - + , ); // https://vitejs.dev/guide/env-and-mode.html diff --git a/templates/react/packages/client/src/mud/createSystemCalls.ts b/templates/react/packages/client/src/mud/createSystemCalls.ts index 7f9cb42e04..d7714ec453 100644 --- a/templates/react/packages/client/src/mud/createSystemCalls.ts +++ b/templates/react/packages/client/src/mud/createSystemCalls.ts @@ -28,7 +28,7 @@ export function createSystemCalls( * syncToRecs * (https://github.com/latticexyz/mud/blob/main/templates/react/packages/client/src/mud/setupNetwork.ts#L77-L83). */ - { tables, useStore, worldContract, waitForTransaction }: SetupNetworkResult + { tables, useStore, worldContract, waitForTransaction }: SetupNetworkResult, ) { const addTask = async (label: string) => { const tx = await worldContract.write.addTask([label]); diff --git a/templates/react/packages/client/src/mud/setupNetwork.ts b/templates/react/packages/client/src/mud/setupNetwork.ts index f401de4702..c9b54e4094 100644 --- a/templates/react/packages/client/src/mud/setupNetwork.ts +++ b/templates/react/packages/client/src/mud/setupNetwork.ts @@ -3,12 +3,23 @@ * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ -import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig } from "viem"; +import { + createPublicClient, + fallback, + webSocket, + http, + createWalletClient, + Hex, + parseEther, + ClientConfig, + getContract, +} from "viem"; import { createFaucetService } from "@latticexyz/services/faucet"; import { syncToZustand } from "@latticexyz/store-sync/zustand"; import { getNetworkConfig } from "./getNetworkConfig"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; -import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; +import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; +import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; /* @@ -38,6 +49,12 @@ export async function setupNetwork() { const publicClient = createPublicClient(clientOptions); + /* + * Create an observable for contract writes that we can + * pass into MUD dev tools for transaction observability. + */ + const write$ = new Subject(); + /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). @@ -46,13 +63,9 @@ export async function setupNetwork() { const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, - }); - - /* - * Create an observable for contract writes that we can - * pass into MUD dev tools for transaction observability. - */ - const write$ = new Subject(); + }) + .extend(transactionQueue()) + .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. @@ -61,7 +74,6 @@ export async function setupNetwork() { address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, - onWrite: (write) => write$.next(write), }); /* diff --git a/templates/react/packages/contracts/package.json b/templates/react/packages/contracts/package.json index aa7c055744..b2640d68cd 100644 --- a/templates/react/packages/contracts/package.json +++ b/templates/react/packages/contracts/package.json @@ -25,8 +25,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", "solhint-plugin-mud": "file:../../../../packages/solhint-plugin-mud" diff --git a/templates/react/packages/contracts/src/codegen/index.sol b/templates/react/packages/contracts/src/codegen/index.sol index 541ff3b552..6337bbbc62 100644 --- a/templates/react/packages/contracts/src/codegen/index.sol +++ b/templates/react/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Tasks, TasksData, TasksTableId } from "./tables/Tasks.sol"; +import { Tasks, TasksData } from "./tables/Tasks.sol"; diff --git a/templates/react/packages/contracts/src/codegen/tables/Tasks.sol b/templates/react/packages/contracts/src/codegen/tables/Tasks.sol index dd0f1cad01..9acd84366f 100644 --- a/templates/react/packages/contracts/src/codegen/tables/Tasks.sol +++ b/templates/react/packages/contracts/src/codegen/tables/Tasks.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,19 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Tasks", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000005461736b730000000000000000000000); -ResourceId constant TasksTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0040020120200000000000000000000000000000000000000000000000000000 -); - struct TasksData { uint256 createdAt; uint256 completedAt; @@ -34,37 +23,16 @@ struct TasksData { } library Tasks { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Tasks", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x746200000000000000000000000000005461736b730000000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0040020120200000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](3); - _valueSchema[0] = SchemaType.UINT256; - _valueSchema[1] = SchemaType.UINT256; - _valueSchema[2] = SchemaType.STRING; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint256, uint256, string) + Schema constant _valueSchema = Schema.wrap(0x004002011f1fc500000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -90,14 +58,14 @@ library Tasks { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/templates/react/packages/contracts/src/codegen/world/ITasksSystem.sol b/templates/react/packages/contracts/src/codegen/world/ITasksSystem.sol index 81127a78eb..4a18791ccf 100644 --- a/templates/react/packages/contracts/src/codegen/world/ITasksSystem.sol +++ b/templates/react/packages/contracts/src/codegen/world/ITasksSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title ITasksSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface ITasksSystem { diff --git a/templates/react/packages/contracts/src/codegen/world/IWorld.sol b/templates/react/packages/contracts/src/codegen/world/IWorld.sol index d3a48bdf1e..b3848a4577 100644 --- a/templates/react/packages/contracts/src/codegen/world/IWorld.sol +++ b/templates/react/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { ITasksSystem } from "./ITasksSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, ITasksSystem { - -} +interface IWorld is IBaseWorld, ITasksSystem {} diff --git a/templates/threejs/package.json b/templates/threejs/package.json index 0faad70ae7..010dc5af8a 100644 --- a/templates/threejs/package.json +++ b/templates/threejs/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/templates/threejs/packages/client/src/index.tsx b/templates/threejs/packages/client/src/index.tsx index da8d70f020..1b005dc561 100644 --- a/templates/threejs/packages/client/src/index.tsx +++ b/templates/threejs/packages/client/src/index.tsx @@ -13,7 +13,7 @@ setup().then(async (result) => { root.render( - + , ); // https://vitejs.dev/guide/env-and-mode.html diff --git a/templates/threejs/packages/client/src/mud/createSystemCalls.ts b/templates/threejs/packages/client/src/mud/createSystemCalls.ts index 145e2ef1e5..d537c578fb 100644 --- a/templates/threejs/packages/client/src/mud/createSystemCalls.ts +++ b/templates/threejs/packages/client/src/mud/createSystemCalls.ts @@ -30,7 +30,7 @@ export function createSystemCalls( * (https://github.com/latticexyz/mud/blob/main/templates/threejs/packages/client/src/mud/setupNetwork.ts#L75-L81). */ { worldContract, waitForTransaction, playerEntity }: SetupNetworkResult, - { Position }: ClientComponents + { Position }: ClientComponents, ) { const moveTo = async (x: number, y: number, z: number) => { /* diff --git a/templates/threejs/packages/client/src/mud/setupNetwork.ts b/templates/threejs/packages/client/src/mud/setupNetwork.ts index 20a639ceca..1d98c384ac 100644 --- a/templates/threejs/packages/client/src/mud/setupNetwork.ts +++ b/templates/threejs/packages/client/src/mud/setupNetwork.ts @@ -3,13 +3,24 @@ * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ -import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig } from "viem"; +import { + createPublicClient, + fallback, + webSocket, + http, + createWalletClient, + Hex, + parseEther, + ClientConfig, + getContract, +} from "viem"; import { createFaucetService } from "@latticexyz/services/faucet"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; -import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; +import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; +import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; /* @@ -39,6 +50,12 @@ export async function setupNetwork() { const publicClient = createPublicClient(clientOptions); + /* + * Create an observable for contract writes that we can + * pass into MUD dev tools for transaction observability. + */ + const write$ = new Subject(); + /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). @@ -47,13 +64,9 @@ export async function setupNetwork() { const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, - }); - - /* - * Create an observable for contract writes that we can - * pass into MUD dev tools for transaction observability. - */ - const write$ = new Subject(); + }) + .extend(transactionQueue()) + .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. @@ -62,7 +75,6 @@ export async function setupNetwork() { address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, - onWrite: (write) => write$.next(write), }); /* diff --git a/templates/threejs/packages/contracts/package.json b/templates/threejs/packages/contracts/package.json index eaf3a8b0b8..f5c5dc1be2 100644 --- a/templates/threejs/packages/contracts/package.json +++ b/templates/threejs/packages/contracts/package.json @@ -24,8 +24,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", "solhint-plugin-mud": "file:../../../../packages/solhint-plugin-mud" diff --git a/templates/threejs/packages/contracts/src/codegen/index.sol b/templates/threejs/packages/contracts/src/codegen/index.sol index 02e9432e11..b72005c189 100644 --- a/templates/threejs/packages/contracts/src/codegen/index.sol +++ b/templates/threejs/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Position, PositionData, PositionTableId } from "./tables/Position.sol"; +import { Position, PositionData } from "./tables/Position.sol"; diff --git a/templates/threejs/packages/contracts/src/codegen/tables/Position.sol b/templates/threejs/packages/contracts/src/codegen/tables/Position.sol index ee7e364497..cbcd371198 100644 --- a/templates/threejs/packages/contracts/src/codegen/tables/Position.sol +++ b/templates/threejs/packages/contracts/src/codegen/tables/Position.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,19 +11,11 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Position", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000506f736974696f6e0000000000000000); -ResourceId constant PositionTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x000c030004040400000000000000000000000000000000000000000000000000 -); - struct PositionData { int32 x; int32 y; @@ -34,37 +23,16 @@ struct PositionData { } library Position { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](1); - _keySchema[0] = SchemaType.BYTES32; + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Position", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000506f736974696f6e0000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x000c030004040400000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](3); - _valueSchema[0] = SchemaType.INT32; - _valueSchema[1] = SchemaType.INT32; - _valueSchema[2] = SchemaType.INT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of (bytes32) + Schema constant _keySchema = Schema.wrap(0x002001005f000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (int32, int32, int32) + Schema constant _valueSchema = Schema.wrap(0x000c030023232300000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -90,14 +58,14 @@ library Position { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/templates/threejs/packages/contracts/src/codegen/world/IMoveSystem.sol b/templates/threejs/packages/contracts/src/codegen/world/IMoveSystem.sol index 2a41302f7e..4311d0cb72 100644 --- a/templates/threejs/packages/contracts/src/codegen/world/IMoveSystem.sol +++ b/templates/threejs/packages/contracts/src/codegen/world/IMoveSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IMoveSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IMoveSystem { diff --git a/templates/threejs/packages/contracts/src/codegen/world/IWorld.sol b/templates/threejs/packages/contracts/src/codegen/world/IWorld.sol index b9395b8273..d27f33eb9a 100644 --- a/templates/threejs/packages/contracts/src/codegen/world/IWorld.sol +++ b/templates/threejs/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { IMoveSystem } from "./IMoveSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, IMoveSystem { - -} +interface IWorld is IBaseWorld, IMoveSystem {} diff --git a/templates/vanilla/package.json b/templates/vanilla/package.json index d3affb9b3e..6d8b2d9f34 100644 --- a/templates/vanilla/package.json +++ b/templates/vanilla/package.json @@ -14,7 +14,6 @@ "devDependencies": { "@latticexyz/cli": "link:../../packages/cli", "@types/debug": "4.1.7", - "@types/prettier": "2.7.2", "@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/parser": "5.46.1", "eslint": "8.29.0", diff --git a/templates/vanilla/packages/client/src/mud/createSystemCalls.ts b/templates/vanilla/packages/client/src/mud/createSystemCalls.ts index ebff84233d..f153b51e86 100644 --- a/templates/vanilla/packages/client/src/mud/createSystemCalls.ts +++ b/templates/vanilla/packages/client/src/mud/createSystemCalls.ts @@ -31,7 +31,7 @@ export function createSystemCalls( * (https://github.com/latticexyz/mud/blob/main/templates/vanilla/packages/client/src/mud/setupNetwork.ts#L77-L83). */ { worldContract, waitForTransaction }: SetupNetworkResult, - { Counter }: ClientComponents + { Counter }: ClientComponents, ) { const increment = async () => { /* diff --git a/templates/vanilla/packages/client/src/mud/setupNetwork.ts b/templates/vanilla/packages/client/src/mud/setupNetwork.ts index 60dfc7bdda..0d1c6ef75b 100644 --- a/templates/vanilla/packages/client/src/mud/setupNetwork.ts +++ b/templates/vanilla/packages/client/src/mud/setupNetwork.ts @@ -3,14 +3,25 @@ * (https://viem.sh/docs/getting-started.html). * This line imports the functions we need from it. */ -import { createPublicClient, fallback, webSocket, http, createWalletClient, Hex, parseEther, ClientConfig } from "viem"; +import { + createPublicClient, + fallback, + webSocket, + http, + createWalletClient, + Hex, + parseEther, + ClientConfig, + getContract, +} from "viem"; import { createFaucetService } from "@latticexyz/services/faucet"; import { encodeEntity, syncToRecs } from "@latticexyz/store-sync/recs"; import { getNetworkConfig } from "./getNetworkConfig"; import { world } from "./world"; import IWorldAbi from "contracts/out/IWorld.sol/IWorld.abi.json"; -import { createBurnerAccount, getContract, transportObserver, ContractWrite } from "@latticexyz/common"; +import { createBurnerAccount, transportObserver, ContractWrite } from "@latticexyz/common"; +import { transactionQueue, writeObserver } from "@latticexyz/common/actions"; import { Subject, share } from "rxjs"; @@ -41,6 +52,12 @@ export async function setupNetwork() { const publicClient = createPublicClient(clientOptions); + /* + * Create an observable for contract writes that we can + * pass into MUD dev tools for transaction observability. + */ + const write$ = new Subject(); + /* * Create a temporary wallet and a viem client for it * (see https://viem.sh/docs/clients/wallet.html). @@ -49,13 +66,9 @@ export async function setupNetwork() { const burnerWalletClient = createWalletClient({ ...clientOptions, account: burnerAccount, - }); - - /* - * Create an observable for contract writes that we can - * pass into MUD dev tools for transaction observability. - */ - const write$ = new Subject(); + }) + .extend(transactionQueue()) + .extend(writeObserver({ onWrite: (write) => write$.next(write) })); /* * Create an object for communicating with the deployed World. @@ -64,7 +77,6 @@ export async function setupNetwork() { address: networkConfig.worldAddress as Hex, abi: IWorldAbi, client: { public: publicClient, wallet: burnerWalletClient }, - onWrite: (write) => write$.next(write), }); /* diff --git a/templates/vanilla/packages/contracts/package.json b/templates/vanilla/packages/contracts/package.json index aa7c055744..b2640d68cd 100644 --- a/templates/vanilla/packages/contracts/package.json +++ b/templates/vanilla/packages/contracts/package.json @@ -25,8 +25,8 @@ "@types/node": "^18.15.11", "ds-test": "https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0", "forge-std": "https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1", - "prettier": "^2.6.2", - "prettier-plugin-solidity": "1.1.3", + "prettier": "3.2.5", + "prettier-plugin-solidity": "1.3.1", "solhint": "^3.3.7", "solhint-config-mud": "file:../../../../packages/solhint-config-mud", "solhint-plugin-mud": "file:../../../../packages/solhint-plugin-mud" diff --git a/templates/vanilla/packages/contracts/src/codegen/index.sol b/templates/vanilla/packages/contracts/src/codegen/index.sol index 6364dfc884..2c7020d821 100644 --- a/templates/vanilla/packages/contracts/src/codegen/index.sol +++ b/templates/vanilla/packages/contracts/src/codegen/index.sol @@ -3,4 +3,4 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -import { Counter, CounterTableId } from "./tables/Counter.sol"; +import { Counter } from "./tables/Counter.sol"; diff --git a/templates/vanilla/packages/contracts/src/codegen/tables/Counter.sol b/templates/vanilla/packages/contracts/src/codegen/tables/Counter.sol index 40a1f45dcf..829e0b68f4 100644 --- a/templates/vanilla/packages/contracts/src/codegen/tables/Counter.sol +++ b/templates/vanilla/packages/contracts/src/codegen/tables/Counter.sol @@ -3,9 +3,6 @@ pragma solidity >=0.8.24; /* Autogenerated file. Do not edit manually. */ -// Import schema type -import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; - // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; @@ -14,48 +11,22 @@ import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; -import { FieldLayout, FieldLayoutLib } from "@latticexyz/store/src/FieldLayout.sol"; -import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; +import { FieldLayout } from "@latticexyz/store/src/FieldLayout.sol"; +import { Schema } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; import { ResourceId } from "@latticexyz/store/src/ResourceId.sol"; -// Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` -ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); -ResourceId constant CounterTableId = _tableId; - -FieldLayout constant _fieldLayout = FieldLayout.wrap( - 0x0004010004000000000000000000000000000000000000000000000000000000 -); - library Counter { - /** - * @notice Get the table values' field layout. - * @return _fieldLayout The field layout for the table. - */ - function getFieldLayout() internal pure returns (FieldLayout) { - return _fieldLayout; - } - - /** - * @notice Get the table's key schema. - * @return _keySchema The key schema for the table. - */ - function getKeySchema() internal pure returns (Schema) { - SchemaType[] memory _keySchema = new SchemaType[](0); + // Hex below is the result of `WorldResourceIdLib.encode({ namespace: "", name: "Counter", typeId: RESOURCE_TABLE });` + ResourceId constant _tableId = ResourceId.wrap(0x74620000000000000000000000000000436f756e746572000000000000000000); - return SchemaLib.encode(_keySchema); - } + FieldLayout constant _fieldLayout = + FieldLayout.wrap(0x0004010004000000000000000000000000000000000000000000000000000000); - /** - * @notice Get the table's value schema. - * @return _valueSchema The value schema for the table. - */ - function getValueSchema() internal pure returns (Schema) { - SchemaType[] memory _valueSchema = new SchemaType[](1); - _valueSchema[0] = SchemaType.UINT32; - - return SchemaLib.encode(_valueSchema); - } + // Hex-encoded key schema of () + Schema constant _keySchema = Schema.wrap(0x0000000000000000000000000000000000000000000000000000000000000000); + // Hex-encoded value schema of (uint32) + Schema constant _valueSchema = Schema.wrap(0x0004010003000000000000000000000000000000000000000000000000000000); /** * @notice Get the table's key field names. @@ -78,14 +49,14 @@ library Counter { * @notice Register the table with its config. */ function register() internal { - StoreSwitch.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreSwitch.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** * @notice Register the table with its config. */ function _register() internal { - StoreCore.registerTable(_tableId, _fieldLayout, getKeySchema(), getValueSchema(), getKeyNames(), getFieldNames()); + StoreCore.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames()); } /** diff --git a/templates/vanilla/packages/contracts/src/codegen/world/IIncrementSystem.sol b/templates/vanilla/packages/contracts/src/codegen/world/IIncrementSystem.sol index 14ceb85613..6a1a4db250 100644 --- a/templates/vanilla/packages/contracts/src/codegen/world/IIncrementSystem.sol +++ b/templates/vanilla/packages/contracts/src/codegen/world/IIncrementSystem.sol @@ -5,6 +5,7 @@ pragma solidity >=0.8.24; /** * @title IIncrementSystem + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @dev This interface is automatically generated from the corresponding system contract. Do not edit manually. */ interface IIncrementSystem { diff --git a/templates/vanilla/packages/contracts/src/codegen/world/IWorld.sol b/templates/vanilla/packages/contracts/src/codegen/world/IWorld.sol index 938ff3572a..34615b56ae 100644 --- a/templates/vanilla/packages/contracts/src/codegen/world/IWorld.sol +++ b/templates/vanilla/packages/contracts/src/codegen/world/IWorld.sol @@ -9,10 +9,9 @@ import { IIncrementSystem } from "./IIncrementSystem.sol"; /** * @title IWorld + * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz) * @notice This interface integrates all systems and associated function selectors * that are dynamically registered in the World during deployment. * @dev This is an autogenerated file; do not edit manually. */ -interface IWorld is IBaseWorld, IIncrementSystem { - -} +interface IWorld is IBaseWorld, IIncrementSystem {} diff --git a/templates/vanilla/packages/contracts/test/CounterTest.t.sol b/templates/vanilla/packages/contracts/test/CounterTest.t.sol index 2c76d7b300..4946ef57ff 100644 --- a/templates/vanilla/packages/contracts/test/CounterTest.t.sol +++ b/templates/vanilla/packages/contracts/test/CounterTest.t.sol @@ -6,7 +6,7 @@ import { MudTest } from "@latticexyz/world/test/MudTest.t.sol"; import { getKeysWithValue } from "@latticexyz/world-modules/src/modules/keyswithvalue/getKeysWithValue.sol"; import { IWorld } from "../src/codegen/world/IWorld.sol"; -import { Counter, CounterTableId } from "../src/codegen/index.sol"; +import { Counter } from "../src/codegen/index.sol"; contract CounterTest is MudTest { function testWorldExists() public {