@latticexyz/cli 2.0.0-alpha.94 → 2.0.0-foundry-js-c7b0289b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/chunk-22IIKR4S.js +4 -0
  2. package/dist/chunk-22IIKR4S.js.map +1 -0
  3. package/dist/commands-UYAATBY6.js +27 -0
  4. package/dist/commands-UYAATBY6.js.map +1 -0
  5. package/dist/errors-XGN6V2Y3.js +2 -0
  6. package/dist/errors-XGN6V2Y3.js.map +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/mud.js +2 -8340
  10. package/dist/mud.js.map +1 -0
  11. package/package.json +54 -46
  12. package/src/commands/deploy.ts +26 -0
  13. package/src/commands/dev-contracts.ts +114 -0
  14. package/src/commands/devnode.ts +7 -2
  15. package/src/commands/faucet.ts +1 -1
  16. package/src/commands/index.ts +19 -14
  17. package/src/commands/set-version.ts +103 -81
  18. package/src/commands/tablegen.ts +7 -5
  19. package/src/commands/test.ts +65 -0
  20. package/src/commands/trace.ts +118 -0
  21. package/src/commands/worldgen.ts +29 -28
  22. package/src/common.ts +1 -0
  23. package/src/debug.ts +3 -0
  24. package/src/deploy/assertNamespaceOwner.ts +42 -0
  25. package/src/deploy/common.ts +76 -0
  26. package/src/deploy/configToTables.ts +68 -0
  27. package/src/deploy/create2/README.md +9 -0
  28. package/src/deploy/create2/deployment.json +7 -0
  29. package/src/deploy/debug.ts +3 -0
  30. package/src/deploy/deploy.ts +108 -0
  31. package/src/deploy/deployWorld.ts +33 -0
  32. package/src/deploy/ensureContract.ts +61 -0
  33. package/src/deploy/ensureContractsDeployed.ts +25 -0
  34. package/src/deploy/ensureDeployer.ts +36 -0
  35. package/src/deploy/ensureFunctions.ts +86 -0
  36. package/src/deploy/ensureModules.ts +73 -0
  37. package/src/deploy/ensureSystems.ts +162 -0
  38. package/src/deploy/ensureTables.ts +65 -0
  39. package/src/deploy/ensureWorldFactory.ts +47 -0
  40. package/src/deploy/getFunctions.ts +58 -0
  41. package/src/deploy/getResourceAccess.ts +51 -0
  42. package/src/deploy/getResourceIds.ts +31 -0
  43. package/src/deploy/getSystems.ts +48 -0
  44. package/src/deploy/getTableValue.ts +30 -0
  45. package/src/deploy/getTables.ts +59 -0
  46. package/src/deploy/getWorldDeploy.ts +39 -0
  47. package/src/deploy/logsToWorldDeploy.ts +49 -0
  48. package/src/deploy/resolveConfig.ts +151 -0
  49. package/src/deploy/resourceLabel.ts +3 -0
  50. package/src/index.ts +1 -1
  51. package/src/modules.d.ts +11 -0
  52. package/src/mud.ts +38 -23
  53. package/src/mudPackages.ts +24 -0
  54. package/src/runDeploy.ts +128 -0
  55. package/src/utils/errors.ts +1 -1
  56. package/src/utils/getExistingContracts.ts +12 -0
  57. package/src/utils/modules/constants.ts +26 -0
  58. package/src/utils/printMUD.ts +14 -0
  59. package/src/utils/utils/getContractData.ts +32 -0
  60. package/src/utils/utils/postDeploy.ts +25 -0
  61. package/dist/chunk-6V563IAZ.js +0 -283
  62. package/dist/chunk-FPG73MVN.js +0 -71
  63. package/dist/chunk-L4YLJHLJ.js +0 -30
  64. package/dist/chunk-SKNB74MT.js +0 -726
  65. package/dist/chunk-T2YHSEJD.js +0 -3842
  66. package/dist/chunk-VQTZJIFF.js +0 -353
  67. package/dist/chunk-WZFXLDPK.js +0 -761
  68. package/dist/chunk-YL4GJLLL.js +0 -26139
  69. package/dist/index.d.ts +0 -2
  70. package/dist/mud.d.ts +0 -1
  71. package/dist/mud2.d.ts +0 -1
  72. package/dist/mud2.js +0 -25
  73. package/dist/render-solidity/index.d.ts +0 -171
  74. package/dist/render-solidity/index.js +0 -49
  75. package/dist/render-ts/index.d.ts +0 -26
  76. package/dist/render-ts/index.js +0 -14
  77. package/dist/utils/deprecated/index.d.ts +0 -76
  78. package/dist/utils/deprecated/index.js +0 -36
  79. package/dist/utils/index.d.ts +0 -88
  80. package/dist/utils/index.js +0 -39
  81. package/src/commands/deploy-v2.ts +0 -112
  82. package/src/commands/deprecated/bulkupload.ts +0 -50
  83. package/src/commands/deprecated/call-system.ts +0 -70
  84. package/src/commands/deprecated/codegen-libdeploy.ts +0 -29
  85. package/src/commands/deprecated/deploy-contracts.ts +0 -120
  86. package/src/commands/deprecated/index.ts +0 -22
  87. package/src/commands/deprecated/system-types.ts +0 -29
  88. package/src/commands/deprecated/test.ts +0 -53
  89. package/src/commands/deprecated/trace.ts +0 -81
  90. package/src/commands/deprecated/types.ts +0 -33
  91. package/src/commands/gas-report.ts +0 -219
  92. package/src/commands/test-v2.ts +0 -71
  93. package/src/commands/tsgen.ts +0 -33
  94. package/src/contracts/BulkUpload.sol +0 -174
  95. package/src/contracts/Deploy.sol +0 -23
  96. package/src/contracts/LibDeploy.ejs +0 -121
  97. package/src/contracts/LibDeploy.sol +0 -23
  98. package/src/contracts/LibDeployStub.sol +0 -23
  99. package/src/mud2.ts +0 -29
  100. package/src/render-solidity/common.ts +0 -138
  101. package/src/render-solidity/field.ts +0 -160
  102. package/src/render-solidity/index.ts +0 -10
  103. package/src/render-solidity/record.ts +0 -158
  104. package/src/render-solidity/renderSystemInterface.ts +0 -31
  105. package/src/render-solidity/renderTable.ts +0 -164
  106. package/src/render-solidity/renderTableIndex.ts +0 -15
  107. package/src/render-solidity/renderTypeHelpers.ts +0 -99
  108. package/src/render-solidity/renderTypes.ts +0 -19
  109. package/src/render-solidity/renderTypesFromConfig.ts +0 -13
  110. package/src/render-solidity/renderWorld.ts +0 -24
  111. package/src/render-solidity/tableOptions.ts +0 -107
  112. package/src/render-solidity/tablegen.ts +0 -35
  113. package/src/render-solidity/types.ts +0 -111
  114. package/src/render-solidity/userType.ts +0 -131
  115. package/src/render-solidity/worldgen.ts +0 -59
  116. package/src/render-ts/index.ts +0 -5
  117. package/src/render-ts/recsV1TableOptions.ts +0 -39
  118. package/src/render-ts/renderRecsV1Tables.ts +0 -31
  119. package/src/render-ts/schemaTypesToRecsTypeStrings.ts +0 -202
  120. package/src/render-ts/tsgen.ts +0 -12
  121. package/src/render-ts/types.ts +0 -13
  122. package/src/utils/contractToInterface.ts +0 -132
  123. package/src/utils/deploy-v2.ts +0 -518
  124. package/src/utils/deprecated/build.ts +0 -55
  125. package/src/utils/deprecated/codegen.ts +0 -42
  126. package/src/utils/deprecated/constants.ts +0 -2
  127. package/src/utils/deprecated/deploy.ts +0 -111
  128. package/src/utils/deprecated/exec.ts +0 -18
  129. package/src/utils/deprecated/findLog.ts +0 -8
  130. package/src/utils/deprecated/hsr.ts +0 -71
  131. package/src/utils/deprecated/ids.ts +0 -14
  132. package/src/utils/deprecated/index.ts +0 -8
  133. package/src/utils/deprecated/typegen.ts +0 -133
  134. package/src/utils/execLog.ts +0 -22
  135. package/src/utils/format.ts +0 -39
  136. package/src/utils/formatAndWrite.ts +0 -21
  137. package/src/utils/foundry.ts +0 -103
  138. package/src/utils/getChainId.ts +0 -10
  139. package/src/utils/index.ts +0 -5
package/src/mud2.ts DELETED
@@ -1,29 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import yargs from "yargs";
4
- import { hideBin } from "yargs/helpers";
5
- import { commands } from "./commands/index.js";
6
- import { logError } from "./utils/errors.js";
7
-
8
- // Load .env file into process.env
9
- import * as dotenv from "dotenv";
10
- dotenv.config();
11
-
12
- yargs(hideBin(process.argv))
13
- // Explicit name to display in help (by default it's the entry file, which may not be "mud" for e.g. ts-node)
14
- .scriptName("mud")
15
- // Use the commands directory to scaffold
16
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- command array overload isn't typed, see https://github.com/yargs/yargs/blob/main/docs/advanced.md#esm-hierarchy
17
- .command(commands as any)
18
- // Enable strict mode.
19
- .strict()
20
- // Custom error handler
21
- .fail((msg, err) => {
22
- console.log("");
23
- logError(err);
24
- console.log("");
25
-
26
- process.exit(1);
27
- })
28
- // Useful aliases.
29
- .alias({ h: "help" }).argv;
@@ -1,138 +0,0 @@
1
- import path from "path";
2
- import { ImportDatum, RenderTableOptions, RenderTableType, StaticResourceData } from "./types.js";
3
-
4
- export const renderedSolidityHeader = `// SPDX-License-Identifier: MIT
5
- pragma solidity >=0.8.0;
6
-
7
- /* Autogenerated file. Do not edit manually. */`;
8
-
9
- /**
10
- * Renders a list of lines
11
- */
12
- export function renderList<T>(list: T[], renderItem: (item: T, index: number) => string) {
13
- return internalRenderList("", list, renderItem);
14
- }
15
-
16
- /**
17
- * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones
18
- */
19
- export function renderArguments(args: (string | undefined)[]) {
20
- const filteredArgs = args.filter((arg) => arg !== undefined && arg !== "") as string[];
21
- return internalRenderList(",", filteredArgs, (arg) => arg);
22
- }
23
-
24
- export function renderCommonData({
25
- staticResourceData,
26
- primaryKeys,
27
- }: Pick<RenderTableOptions, "staticResourceData" | "primaryKeys">) {
28
- // static resource means static tableId as well, and no tableId arguments
29
- const _tableId = staticResourceData ? "" : "_tableId";
30
- const _typedTableId = staticResourceData ? "" : "bytes32 _tableId";
31
-
32
- const _keyArgs = renderArguments(primaryKeys.map(({ name }) => name));
33
- const _typedKeyArgs = renderArguments(primaryKeys.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
34
-
35
- const _primaryKeysDefinition = `
36
- bytes32[] memory _primaryKeys = new bytes32[](${primaryKeys.length});
37
- ${renderList(
38
- primaryKeys,
39
- (primaryKey, index) => `_primaryKeys[${index}] = ${renderValueTypeToBytes32(primaryKey.name, primaryKey)};`
40
- )}
41
- `;
42
-
43
- return {
44
- _tableId,
45
- _typedTableId,
46
- _keyArgs,
47
- _typedKeyArgs,
48
- _primaryKeysDefinition,
49
- };
50
- }
51
-
52
- /** For 2 paths which are relative to a common root, create a relative import path from one to another */
53
- export function solidityRelativeImportPath(fromPath: string, usedInPath: string) {
54
- // 1st "./" must be added because path strips it,
55
- // but solidity expects it unless there's "../" ("./../" is fine).
56
- // 2nd and 3rd "./" forcefully avoid absolute paths (everything is relative to `src`).
57
- return "./" + path.relative("./" + usedInPath, "./" + fromPath);
58
- }
59
-
60
- /**
61
- * Aggregates, deduplicates and renders imports for symbols per path.
62
- * Identical symbols from different paths are NOT handled, they should be checked before rendering.
63
- */
64
- export function renderImports(imports: ImportDatum[]) {
65
- // Aggregate symbols by import path, also deduplicating them
66
- const aggregatedImports = new Map<string, Set<string>>();
67
- for (const { symbol, fromPath, usedInPath } of imports) {
68
- const path = solidityRelativeImportPath(fromPath, usedInPath);
69
- if (!aggregatedImports.has(path)) {
70
- aggregatedImports.set(path, new Set());
71
- }
72
- aggregatedImports.get(path)?.add(symbol);
73
- }
74
- // Render imports
75
- const renderedImports = [];
76
- for (const [path, symbols] of aggregatedImports) {
77
- const renderedSymbols = [...symbols].join(", ");
78
- renderedImports.push(`import { ${renderedSymbols} } from "${path}";`);
79
- }
80
- return renderedImports.join("\n");
81
- }
82
-
83
- export function renderWithStore(
84
- storeArgument: boolean,
85
- callback: (
86
- _typedStore: string | undefined,
87
- _store: string,
88
- _commentSuffix: string,
89
- _untypedStore: string | undefined
90
- ) => string
91
- ) {
92
- let result = "";
93
- result += callback(undefined, "StoreSwitch", "", undefined);
94
-
95
- if (storeArgument) {
96
- result += "\n" + callback("IStore _store", "_store", " (using the specified store)", "_store");
97
- }
98
-
99
- return result;
100
- }
101
-
102
- export function renderTableId(staticResourceData: StaticResourceData) {
103
- const hardcodedTableId = `bytes32(abi.encodePacked(bytes16("${staticResourceData.namespace}"), bytes16("${staticResourceData.name}")))`;
104
-
105
- const tableIdDefinition = `
106
- bytes32 constant _tableId = ${hardcodedTableId};
107
- bytes32 constant ${staticResourceData.tableIdName} = _tableId;
108
- `;
109
- return {
110
- hardcodedTableId,
111
- tableIdDefinition,
112
- };
113
- }
114
-
115
- function renderValueTypeToBytes32(name: string, { staticByteLength, typeUnwrap, internalTypeId }: RenderTableType) {
116
- const bits = staticByteLength * 8;
117
- const innerText = `${typeUnwrap}(${name})`;
118
-
119
- if (internalTypeId.match(/^uint\d{1,3}$/)) {
120
- return `bytes32(uint256(${innerText}))`;
121
- } else if (internalTypeId.match(/^int\d{1,3}$/)) {
122
- return `bytes32(uint256(uint${bits}(${innerText})))`;
123
- } else if (internalTypeId.match(/^bytes\d{1,2}$/)) {
124
- return `bytes32(${innerText})`;
125
- } else if (internalTypeId === "address") {
126
- return `bytes32(bytes20(${innerText}))`;
127
- } else if (internalTypeId === "bool") {
128
- return `_boolToBytes32(${innerText})`;
129
- } else {
130
- throw new Error(`Unknown value type id ${internalTypeId}`);
131
- }
132
- }
133
-
134
- function internalRenderList<T>(lineTerminator: string, list: T[], renderItem: (item: T, index: number) => string) {
135
- return list
136
- .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? "" : lineTerminator))
137
- .join("\n");
138
- }
@@ -1,160 +0,0 @@
1
- import { renderArguments, renderCommonData, renderWithStore } from "./common.js";
2
- import { RenderTableField, RenderTableOptions, RenderTableType } from "./types.js";
3
-
4
- export function renderFieldMethods(options: RenderTableOptions) {
5
- const storeArgument = options.storeArgument;
6
- const { _typedTableId, _typedKeyArgs, _primaryKeysDefinition } = renderCommonData(options);
7
-
8
- let result = "";
9
- for (const [index, field] of options.fields.entries()) {
10
- const _typedFieldName = `${field.typeWithLocation} ${field.name}`;
11
-
12
- result += renderWithStore(
13
- storeArgument,
14
- (_typedStore, _store, _commentSuffix) => `
15
- /** Get ${field.name}${_commentSuffix} */
16
- function get${field.methodNameSuffix}(${renderArguments([
17
- _typedStore,
18
- _typedTableId,
19
- _typedKeyArgs,
20
- ])}) internal view returns (${_typedFieldName}) {
21
- ${_primaryKeysDefinition}
22
- bytes memory _blob = ${_store}.getField(_tableId, _primaryKeys, ${index});
23
- return ${renderDecodeFieldSingle(field)};
24
- }
25
- `
26
- );
27
-
28
- result += renderWithStore(
29
- storeArgument,
30
- (_typedStore, _store, _commentSuffix) => `
31
- /** Set ${field.name}${_commentSuffix} */
32
- function set${field.methodNameSuffix}(${renderArguments([
33
- _typedStore,
34
- _typedTableId,
35
- _typedKeyArgs,
36
- _typedFieldName,
37
- ])}) internal {
38
- ${_primaryKeysDefinition}
39
- ${_store}.setField(_tableId, _primaryKeys, ${index}, ${renderEncodeField(field)});
40
- }
41
- `
42
- );
43
-
44
- if (field.isDynamic) {
45
- const portionData = fieldPortionData(field);
46
-
47
- result += renderWithStore(
48
- storeArgument,
49
- (_typedStore, _store, _commentSuffix) => `
50
- /** Push ${portionData.title} to ${field.name}${_commentSuffix} */
51
- function push${field.methodNameSuffix}(${renderArguments([
52
- _typedStore,
53
- _typedTableId,
54
- _typedKeyArgs,
55
- `${portionData.typeWithLocation} ${portionData.name}`,
56
- ])}) internal {
57
- ${_primaryKeysDefinition}
58
- ${_store}.pushToField(_tableId, _primaryKeys, ${index}, ${portionData.encoded});
59
- }
60
- `
61
- );
62
-
63
- result += renderWithStore(
64
- storeArgument,
65
- (_typedStore, _store, _commentSuffix) => `
66
- /** Update ${portionData.title} of ${field.name}${_commentSuffix} at \`_index\` */
67
- function update${field.methodNameSuffix}(${renderArguments([
68
- _typedStore,
69
- _typedTableId,
70
- _typedKeyArgs,
71
- "uint256 _index",
72
- `${portionData.typeWithLocation} ${portionData.name}`,
73
- ])}) internal {
74
- ${_primaryKeysDefinition}
75
- ${_store}.updateInField(
76
- _tableId,
77
- _primaryKeys,
78
- ${index},
79
- _index * ${portionData.elementLength},
80
- ${portionData.encoded}
81
- );
82
- }
83
- `
84
- );
85
- }
86
- }
87
- return result;
88
- }
89
-
90
- export function renderEncodeField(field: RenderTableField) {
91
- let func;
92
- if (field.arrayElement) {
93
- func = "EncodeArray.encode";
94
- } else if (field.isDynamic) {
95
- func = "bytes";
96
- } else {
97
- func = "abi.encodePacked";
98
- }
99
- return `${func}(${field.typeUnwrap}(${field.name}))`;
100
- }
101
-
102
- export function renderDecodeValueType(field: RenderTableType, offset: number) {
103
- const { staticByteLength, internalTypeId } = field;
104
-
105
- const innerSlice = `Bytes.slice${staticByteLength}(_blob, ${offset})`;
106
- const bits = staticByteLength * 8;
107
-
108
- let result;
109
- if (internalTypeId.match(/^uint\d{1,3}$/) || internalTypeId === "address") {
110
- result = `${internalTypeId}(${innerSlice})`;
111
- } else if (internalTypeId.match(/^int\d{1,3}$/)) {
112
- result = `${internalTypeId}(uint${bits}(${innerSlice}))`;
113
- } else if (internalTypeId.match(/^bytes\d{1,2}$/)) {
114
- result = innerSlice;
115
- } else if (internalTypeId === "bool") {
116
- result = `_toBool(uint8(${innerSlice}))`;
117
- } else {
118
- throw new Error(`Unknown value type id ${internalTypeId}`);
119
- }
120
- return `${field.typeWrap}(${result})`;
121
- }
122
-
123
- /** bytes/string are dynamic, but aren't really arrays */
124
- function fieldPortionData(field: RenderTableField) {
125
- const methodNameSuffix = "";
126
- if (field.arrayElement) {
127
- const name = "_element";
128
- return {
129
- typeWithLocation: field.arrayElement.typeWithLocation,
130
- name: "_element",
131
- encoded: renderEncodeField({ ...field.arrayElement, arrayElement: undefined, name, methodNameSuffix }),
132
- title: "an element",
133
- elementLength: field.arrayElement.staticByteLength,
134
- };
135
- } else {
136
- const name = "_slice";
137
- return {
138
- typeWithLocation: `${field.typeId} memory`,
139
- name,
140
- encoded: renderEncodeField({ ...field, name, methodNameSuffix }),
141
- title: "a slice",
142
- elementLength: 1,
143
- };
144
- }
145
- }
146
-
147
- function renderDecodeFieldSingle(field: RenderTableField) {
148
- const { isDynamic, arrayElement } = field;
149
- if (arrayElement) {
150
- // arrays
151
- return `${field.typeWrap}(
152
- SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_${arrayElement.internalTypeId}()
153
- )`;
154
- } else if (isDynamic) {
155
- // bytes/string
156
- return `${field.typeWrap}(${field.internalTypeId}(_blob))`;
157
- } else {
158
- return renderDecodeValueType(field, 0);
159
- }
160
- }
@@ -1,10 +0,0 @@
1
- export * from "./common.js";
2
- export * from "./field.js";
3
- export * from "./record.js";
4
- export * from "./renderTable.js";
5
- export * from "./renderTypes.js";
6
- export * from "./renderTypesFromConfig.js";
7
- export * from "./tablegen.js";
8
- export * from "./tableOptions.js";
9
- export * from "./types.js";
10
- export * from "./userType.js";
@@ -1,158 +0,0 @@
1
- import { renderList, renderArguments, renderCommonData, renderWithStore } from "./common.js";
2
- import { renderDecodeValueType } from "./field.js";
3
- import { RenderTableDynamicField, RenderTableOptions } from "./types.js";
4
-
5
- export function renderRecordMethods(options: RenderTableOptions) {
6
- const { structName, storeArgument } = options;
7
- const { _tableId, _typedTableId, _keyArgs, _typedKeyArgs, _primaryKeysDefinition } = renderCommonData(options);
8
-
9
- let result = renderWithStore(
10
- storeArgument,
11
- (_typedStore, _store, _commentSuffix) => `
12
- /** Get the full data${_commentSuffix} */
13
- function get(${renderArguments([
14
- _typedStore,
15
- _typedTableId,
16
- _typedKeyArgs,
17
- ])}) internal view returns (${renderDecodedRecord(options)}) {
18
- ${_primaryKeysDefinition}
19
- bytes memory _blob = ${_store}.getRecord(_tableId, _primaryKeys, getSchema());
20
- return decode(_blob);
21
- }
22
- `
23
- );
24
-
25
- result += renderWithStore(
26
- storeArgument,
27
- (_typedStore, _store, _commentSuffix) => `
28
- /** Set the full data using individual values${_commentSuffix} */
29
- function set(${renderArguments([
30
- _typedStore,
31
- _typedTableId,
32
- _typedKeyArgs,
33
- renderArguments(options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)),
34
- ])}) internal {
35
- bytes memory _data = encode(${renderArguments(options.fields.map(({ name }) => name))});
36
-
37
- ${_primaryKeysDefinition}
38
-
39
- ${_store}.setRecord(_tableId, _primaryKeys, _data);
40
- }
41
- `
42
- );
43
-
44
- if (structName !== undefined) {
45
- result += renderWithStore(
46
- storeArgument,
47
- (_typedStore, _store, _commentSuffix, _untypedStore) => `
48
- /** Set the full data using the data struct${_commentSuffix} */
49
- function set(${renderArguments([
50
- _typedStore,
51
- _typedTableId,
52
- _typedKeyArgs,
53
- `${structName} memory _table`,
54
- ])}) internal {
55
- set(${renderArguments([
56
- _untypedStore,
57
- _tableId,
58
- _keyArgs,
59
- renderArguments(options.fields.map(({ name }) => `_table.${name}`)),
60
- ])});
61
- }
62
- `
63
- );
64
- }
65
-
66
- result += renderDecodeFunction(options);
67
-
68
- return result;
69
- }
70
-
71
- // Renders the `decode` function that parses a bytes blob into the table data
72
- function renderDecodeFunction({ structName, fields, staticFields, dynamicFields }: RenderTableOptions) {
73
- // either set struct properties, or just variables
74
- const renderedDecodedRecord = structName
75
- ? `${structName} memory _table`
76
- : renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
77
- const fieldNamePrefix = structName ? "_table." : "";
78
-
79
- // Static field offsets
80
- const staticOffsets = staticFields.map(() => 0);
81
- let _acc = 0;
82
- for (const [index, field] of staticFields.entries()) {
83
- staticOffsets[index] = _acc;
84
- _acc += field.staticByteLength;
85
- }
86
-
87
- if (dynamicFields.length > 0) {
88
- const totalStaticLength = staticFields.reduce((acc, { staticByteLength }) => acc + staticByteLength, 0);
89
- // decode static (optionally) and dynamic data
90
- return `
91
- /** Decode the tightly packed blob using this table's schema */
92
- function decode(bytes memory _blob) internal view returns (${renderedDecodedRecord}) {
93
- // ${totalStaticLength} is the total byte length of static data
94
- PackedCounter _encodedLengths = PackedCounter.wrap(Bytes.slice32(_blob, ${totalStaticLength}));
95
-
96
- ${renderList(
97
- staticFields,
98
- (field, index) => `
99
- ${fieldNamePrefix}${field.name} = ${renderDecodeValueType(field, staticOffsets[index])};
100
- `
101
- )}
102
- // Store trims the blob if dynamic fields are all empty
103
- if (_blob.length > ${totalStaticLength}) {
104
- uint256 _start;
105
- // skip static data length + dynamic lengths word
106
- uint256 _end = ${totalStaticLength + 32};
107
- ${renderList(
108
- dynamicFields,
109
- (field, index) => `
110
- _start = _end;
111
- _end += _encodedLengths.atIndex(${index});
112
- ${fieldNamePrefix}${field.name} = ${renderDecodeDynamicFieldPartial(field)};
113
- `
114
- )}
115
- }
116
- }
117
- `;
118
- } else {
119
- // decode only static data
120
- return `
121
- /** Decode the tightly packed blob using this table's schema */
122
- function decode(bytes memory _blob) internal pure returns (${renderedDecodedRecord}) {
123
- ${renderList(
124
- staticFields,
125
- (field, index) => `
126
- ${fieldNamePrefix}${field.name} = ${renderDecodeValueType(field, staticOffsets[index])};
127
- `
128
- )}
129
- }
130
- `;
131
- }
132
- }
133
-
134
- // contents of `returns (...)` for record getter/decoder
135
- function renderDecodedRecord({ structName, fields }: RenderTableOptions) {
136
- if (structName) {
137
- return `${structName} memory _table`;
138
- } else {
139
- return renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
140
- }
141
- }
142
-
143
- function renderDecodeDynamicFieldPartial(field: RenderTableDynamicField) {
144
- const { typeId, arrayElement, typeWrap } = field;
145
- if (arrayElement) {
146
- // arrays
147
- return `${typeWrap}(
148
- SliceLib.getSubslice(_blob, _start, _end).decodeArray_${arrayElement.typeId}()
149
- )`;
150
- } else {
151
- // bytes/string
152
- return `${typeWrap}(
153
- ${typeId}(
154
- SliceLib.getSubslice(_blob, _start, _end).toBytes()
155
- )
156
- )`;
157
- }
158
- }
@@ -1,31 +0,0 @@
1
- import { renderArguments, renderList, renderedSolidityHeader, renderImports } from "./common.js";
2
- import { RenderSystemInterfaceOptions } from "./types.js";
3
-
4
- export function renderSystemInterface(options: RenderSystemInterfaceOptions) {
5
- const { imports, name, functionPrefix, functions } = options;
6
-
7
- return `${renderedSolidityHeader}
8
-
9
- ${renderImports(imports)}
10
-
11
- interface ${name} {
12
- ${renderList(
13
- functions,
14
- ({ name, parameters, stateMutability, returnParameters }) => `
15
- function ${functionPrefix}${name}(
16
- ${renderArguments(parameters)}
17
- ) external ${stateMutability} ${renderReturnParameters(returnParameters)};
18
- `
19
- )}
20
- }
21
-
22
- `;
23
- }
24
-
25
- function renderReturnParameters(returnParameters: string[]) {
26
- if (returnParameters.length > 0) {
27
- return `returns (${renderArguments(returnParameters)})`;
28
- } else {
29
- return "";
30
- }
31
- }
@@ -1,164 +0,0 @@
1
- import {
2
- renderArguments,
3
- renderCommonData,
4
- renderList,
5
- renderedSolidityHeader,
6
- renderImports,
7
- renderTableId,
8
- renderWithStore,
9
- } from "./common.js";
10
- import { renderEncodeField, renderFieldMethods } from "./field.js";
11
- import { renderRecordMethods } from "./record.js";
12
- import { renderTypeHelpers } from "./renderTypeHelpers.js";
13
- import { RenderTableDynamicField, RenderTableOptions } from "./types.js";
14
-
15
- export function renderTable(options: RenderTableOptions) {
16
- const {
17
- imports,
18
- libraryName,
19
- structName,
20
- staticResourceData,
21
- storeImportPath,
22
- fields,
23
- staticFields,
24
- dynamicFields,
25
- withRecordMethods,
26
- storeArgument,
27
- primaryKeys,
28
- } = options;
29
-
30
- const { _typedTableId, _typedKeyArgs, _primaryKeysDefinition } = renderCommonData(options);
31
-
32
- return `${renderedSolidityHeader}
33
-
34
- // Import schema type
35
- import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol";
36
-
37
- // Import store internals
38
- import { IStore } from "${storeImportPath}IStore.sol";
39
- import { StoreSwitch } from "${storeImportPath}StoreSwitch.sol";
40
- import { StoreCore } from "${storeImportPath}StoreCore.sol";
41
- import { Bytes } from "${storeImportPath}Bytes.sol";
42
- import { Memory } from "${storeImportPath}Memory.sol";
43
- import { SliceLib } from "${storeImportPath}Slice.sol";
44
- import { EncodeArray } from "${storeImportPath}tightcoder/EncodeArray.sol";
45
- import { Schema, SchemaLib } from "${storeImportPath}Schema.sol";
46
- import { PackedCounter, PackedCounterLib } from "${storeImportPath}PackedCounter.sol";
47
-
48
- ${
49
- imports.length > 0
50
- ? `
51
- // Import user types
52
- ${renderImports(imports)}
53
- `
54
- : ""
55
- }
56
-
57
- ${staticResourceData ? renderTableId(staticResourceData).tableIdDefinition : ""}
58
-
59
- ${
60
- !structName
61
- ? ""
62
- : `
63
- struct ${structName} {
64
- ${renderList(fields, ({ name, typeId }) => `${typeId} ${name};`)}
65
- }
66
- `
67
- }
68
-
69
- library ${libraryName} {
70
- /** Get the table's schema */
71
- function getSchema() internal pure returns (Schema) {
72
- SchemaType[] memory _schema = new SchemaType[](${fields.length});
73
- ${renderList(fields, ({ enumName }, index) => `_schema[${index}] = SchemaType.${enumName};`)}
74
-
75
- return SchemaLib.encode(_schema);
76
- }
77
-
78
- function getKeySchema() internal pure returns (Schema) {
79
- SchemaType[] memory _schema = new SchemaType[](${primaryKeys.length});
80
- ${renderList(primaryKeys, ({ enumName }, index) => `_schema[${index}] = SchemaType.${enumName};`)}
81
-
82
- return SchemaLib.encode(_schema);
83
- }
84
-
85
- /** Get the table's metadata */
86
- function getMetadata() internal pure returns (string memory, string[] memory) {
87
- string[] memory _fieldNames = new string[](${fields.length});
88
- ${renderList(fields, (field, index) => `_fieldNames[${index}] = "${field.name}";`)}
89
- return ("${libraryName}", _fieldNames);
90
- }
91
-
92
- ${renderWithStore(
93
- storeArgument,
94
- (_typedStore, _store, _commentSuffix) => `
95
- /** Register the table's schema${_commentSuffix} */
96
- function registerSchema(${renderArguments([_typedStore, _typedTableId])}) internal {
97
- ${_store}.registerSchema(_tableId, getSchema(), getKeySchema());
98
- }
99
- `
100
- )}
101
- ${renderWithStore(
102
- storeArgument,
103
- (_typedStore, _store, _commentSuffix) => `
104
- /** Set the table's metadata${_commentSuffix} */
105
- function setMetadata(${renderArguments([_typedStore, _typedTableId])}) internal {
106
- (string memory _tableName, string[] memory _fieldNames) = getMetadata();
107
- ${_store}.setMetadata(_tableId, _tableName, _fieldNames);
108
- }
109
- `
110
- )}
111
-
112
- ${renderFieldMethods(options)}
113
-
114
- ${withRecordMethods ? renderRecordMethods(options) : ""}
115
-
116
- /** Tightly pack full data using this table's schema */
117
- function encode(${renderArguments(
118
- options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
119
- )}) internal view returns (bytes memory) {
120
- ${renderEncodedLengths(dynamicFields)}
121
- return abi.encodePacked(${renderArguments([
122
- renderArguments(staticFields.map(({ name }) => name)),
123
- // TODO try gas optimization (preallocate for all, encodePacked statics, and direct encode dynamics)
124
- // (see https://github.com/latticexyz/mud/issues/444)
125
- ...(dynamicFields.length === 0
126
- ? []
127
- : ["_encodedLengths.unwrap()", renderArguments(dynamicFields.map((field) => renderEncodeField(field)))]),
128
- ])});
129
- }
130
-
131
- ${renderWithStore(
132
- storeArgument,
133
- (_typedStore, _store, _commentSuffix) => `
134
- /* Delete all data for given keys${_commentSuffix} */
135
- function deleteRecord(${renderArguments([_typedStore, _typedTableId, _typedKeyArgs])}) internal {
136
- ${_primaryKeysDefinition}
137
- ${_store}.deleteRecord(_tableId, _primaryKeys);
138
- }
139
- `
140
- )}
141
- }
142
-
143
- ${renderTypeHelpers(options)}
144
-
145
- `;
146
- }
147
-
148
- function renderEncodedLengths(dynamicFields: RenderTableDynamicField[]) {
149
- if (dynamicFields.length > 0) {
150
- return `
151
- uint16[] memory _counters = new uint16[](${dynamicFields.length});
152
- ${renderList(dynamicFields, ({ name, arrayElement }, index) => {
153
- if (arrayElement) {
154
- return `_counters[${index}] = uint16(${name}.length * ${arrayElement.staticByteLength});`;
155
- } else {
156
- return `_counters[${index}] = uint16(bytes(${name}).length);`;
157
- }
158
- })}
159
- PackedCounter _encodedLengths = PackedCounterLib.pack(_counters);
160
- `;
161
- } else {
162
- return "";
163
- }
164
- }