@latticexyz/store 2.2.18-9fa07c8489f1fbf167d0db01cd9aaa645a29c8e2 → 2.2.18-c2ad22c7feb566e1731ff16e8be291746bdffb3e

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.
package/dist/codegen.js CHANGED
@@ -1,669 +1,262 @@
1
- // ts/codegen/field.ts
2
- import {
3
- renderArguments,
4
- renderCommonData,
5
- renderWithFieldSuffix,
6
- renderWithStore
7
- } from "@latticexyz/common/codegen";
8
- function renderFieldMethods(options) {
9
- const storeArgument = options.storeArgument;
10
- const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);
11
- let result = "";
12
- for (const [schemaIndex, field] of options.fields.entries()) {
13
- if (!options.withDynamicFieldMethods && field.isDynamic) {
14
- continue;
15
- }
16
- const _typedFieldName = `${field.typeWithLocation} ${field.name}`;
17
- if (options.withGetters) {
18
- result += renderWithFieldSuffix(
19
- options.withSuffixlessFieldMethods,
20
- field.name,
21
- (_methodNameSuffix) => renderWithStore(
22
- storeArgument,
23
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
1
+ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,renderWithStore as D}from"@latticexyz/common/codegen";function K(e){let t=e.storeArgument,{_typedTableId:n,_typedKeyArgs:r,_keyTupleDefinition:s}=se(e),i="";for(let[a,d]of e.fields.entries()){if(!e.withDynamicFieldMethods&&d.isDynamic)continue;let y=`${d.typeWithLocation} ${d.name}`;if(e.withGetters&&(i+=_(e.withSuffixlessFieldMethods,d.name,o=>D(t,({_typedStore:c,_store:l,_commentSuffix:u,_methodNamePrefix:h})=>`
24
2
  /**
25
- * @notice Get ${field.name}${_commentSuffix}.
3
+ * @notice Get ${d.name}${u}.
26
4
  */
27
- function ${_methodNamePrefix}get${_methodNameSuffix}(${renderArguments([
28
- _typedStore,
29
- _typedTableId,
30
- _typedKeyArgs
31
- ])}) internal view returns (${_typedFieldName}) {
32
- ${_keyTupleDefinition}
33
- ${field.isDynamic ? `bytes memory _blob = ${_store}.getDynamicField(
5
+ function ${h}get${o}(${S([c,n,r])}) internal view returns (${y}) {
6
+ ${s}
7
+ ${d.isDynamic?`bytes memory _blob = ${l}.getDynamicField(
34
8
  _tableId,
35
9
  _keyTuple,
36
- ${schemaIndex - options.staticFields.length}
37
- );` : `bytes32 _blob = ${_store}.getStaticField(
10
+ ${a-e.staticFields.length}
11
+ );`:`bytes32 _blob = ${l}.getStaticField(
38
12
  _tableId,
39
13
  _keyTuple,
40
- ${schemaIndex},
14
+ ${a},
41
15
  _fieldLayout
42
16
  );`}
43
- return ${renderDecodeFieldSingle(field)};
17
+ return ${N(d)};
44
18
  }
45
- `
46
- )
47
- );
48
- }
49
- result += renderWithFieldSuffix(
50
- options.withSuffixlessFieldMethods,
51
- field.name,
52
- (_methodNameSuffix) => renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {
53
- const externalArguments = renderArguments([_typedStore, _typedTableId, _typedKeyArgs, _typedFieldName]);
54
- const setFieldMethod = field.isDynamic ? "setDynamicField" : "setStaticField";
55
- const encodeFieldSingle = renderEncodeFieldSingle(field);
56
- const internalArguments = field.isDynamic ? `_tableId, _keyTuple, ${schemaIndex - options.staticFields.length}, ${encodeFieldSingle}` : `_tableId, _keyTuple, ${schemaIndex}, ${encodeFieldSingle}, _fieldLayout`;
57
- return `
19
+ `))),i+=_(e.withSuffixlessFieldMethods,d.name,o=>D(t,({_typedStore:c,_store:l,_commentSuffix:u,_methodNamePrefix:h})=>{let f=S([c,n,r,y]),m=d.isDynamic?"setDynamicField":"setStaticField",p=E(d),L=d.isDynamic?`_tableId, _keyTuple, ${a-e.staticFields.length}, ${p}`:`_tableId, _keyTuple, ${a}, ${p}, _fieldLayout`;return`
58
20
  /**
59
- * @notice Set ${field.name}${_commentSuffix}.
21
+ * @notice Set ${d.name}${u}.
60
22
  */
61
- function ${_methodNamePrefix}set${_methodNameSuffix}(${externalArguments}) internal {
62
- ${_keyTupleDefinition}
63
- ${_store}.${setFieldMethod}(${internalArguments});
23
+ function ${h}set${o}(${f}) internal {
24
+ ${s}
25
+ ${l}.${m}(${L});
64
26
  }
65
- `;
66
- })
67
- );
68
- if (field.isDynamic) {
69
- const portionData = fieldPortionData(field);
70
- const dynamicSchemaIndex = schemaIndex - options.staticFields.length;
71
- const { typeWrappingData } = field;
72
- if (options.withGetters) {
73
- if (typeWrappingData && typeWrappingData.kind === "staticArray") {
74
- result += renderWithFieldSuffix(
75
- options.withSuffixlessFieldMethods,
76
- field.name,
77
- (_methodNameSuffix) => `
78
- // The length of ${field.name}
79
- uint256 constant length${_methodNameSuffix} = ${typeWrappingData.staticLength};
80
- `
81
- );
82
- } else {
83
- result += renderWithFieldSuffix(
84
- options.withSuffixlessFieldMethods,
85
- field.name,
86
- (_methodNameSuffix) => renderWithStore(
87
- storeArgument,
88
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
27
+ `})),d.isDynamic){let o=ce(d),c=a-e.staticFields.length,{typeWrappingData:l}=d;e.withGetters&&(l&&l.kind==="staticArray"?i+=_(e.withSuffixlessFieldMethods,d.name,u=>`
28
+ // The length of ${d.name}
29
+ uint256 constant length${u} = ${l.staticLength};
30
+ `):i+=_(e.withSuffixlessFieldMethods,d.name,u=>D(t,({_typedStore:h,_store:f,_commentSuffix:m,_methodNamePrefix:p})=>`
89
31
  /**
90
- * @notice Get the length of ${field.name}${_commentSuffix}.
32
+ * @notice Get the length of ${d.name}${m}.
91
33
  */
92
- function ${_methodNamePrefix}length${_methodNameSuffix}(${renderArguments([
93
- _typedStore,
94
- _typedTableId,
95
- _typedKeyArgs
96
- ])}) internal view returns (uint256) {
97
- ${_keyTupleDefinition}
98
- uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});
34
+ function ${p}length${u}(${S([h,n,r])}) internal view returns (uint256) {
35
+ ${s}
36
+ uint256 _byteLength = ${f}.getDynamicFieldLength(_tableId, _keyTuple, ${c});
99
37
  unchecked {
100
- return _byteLength / ${portionData.elementLength};
38
+ return _byteLength / ${o.elementLength};
101
39
  }
102
40
  }
103
- `
104
- )
105
- );
106
- }
107
- result += renderWithFieldSuffix(
108
- options.withSuffixlessFieldMethods,
109
- field.name,
110
- (_methodNameSuffix) => renderWithStore(
111
- storeArgument,
112
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
41
+ `)),i+=_(e.withSuffixlessFieldMethods,d.name,u=>D(t,({_typedStore:h,_store:f,_commentSuffix:m,_methodNamePrefix:p})=>`
113
42
  /**
114
- * @notice Get an item of ${field.name}${_commentSuffix}.
43
+ * @notice Get an item of ${d.name}${m}.
115
44
  * @dev Reverts with Store_IndexOutOfBounds if \`_index\` is out of bounds for the array.
116
45
  */
117
- function ${_methodNamePrefix}getItem${_methodNameSuffix}(${renderArguments([
118
- _typedStore,
119
- _typedTableId,
120
- _typedKeyArgs,
121
- "uint256 _index"
122
- ])}) internal view returns (${portionData.typeWithLocation}) {
123
- ${_keyTupleDefinition}
46
+ function ${p}getItem${u}(${S([h,n,r,"uint256 _index"])}) internal view returns (${o.typeWithLocation}) {
47
+ ${s}
124
48
 
125
- ${// If the index is within the static length,
126
- // but ahead of the dynamic length, return zero
127
- typeWrappingData && typeWrappingData.kind === "staticArray" && field.arrayElement ? `
128
- uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});
129
- uint256 dynamicLength = _byteLength / ${portionData.elementLength};
130
- uint256 staticLength = ${typeWrappingData.staticLength};
49
+ ${l&&l.kind==="staticArray"&&d.arrayElement?`
50
+ uint256 _byteLength = ${f}.getDynamicFieldLength(_tableId, _keyTuple, ${c});
51
+ uint256 dynamicLength = _byteLength / ${o.elementLength};
52
+ uint256 staticLength = ${l.staticLength};
131
53
 
132
54
  if (_index < staticLength && _index >= dynamicLength) {
133
- return ${renderCastStaticBytesToType(field.arrayElement, `bytes${field.arrayElement.staticByteLength}(new bytes(0))`)};
134
- }` : ``}
55
+ return ${W(d.arrayElement,`bytes${d.arrayElement.staticByteLength}(new bytes(0))`)};
56
+ }`:""}
135
57
 
136
58
  unchecked {
137
- bytes memory _blob = ${_store}.getDynamicFieldSlice(
59
+ bytes memory _blob = ${f}.getDynamicFieldSlice(
138
60
  _tableId,
139
61
  _keyTuple,
140
- ${dynamicSchemaIndex},
141
- _index * ${portionData.elementLength},
142
- (_index + 1) * ${portionData.elementLength}
62
+ ${c},
63
+ _index * ${o.elementLength},
64
+ (_index + 1) * ${o.elementLength}
143
65
  );
144
- return ${portionData.decoded};
66
+ return ${o.decoded};
145
67
  }
146
68
  }
147
- `
148
- )
149
- );
150
- }
151
- if (!typeWrappingData || typeWrappingData.kind !== "staticArray") {
152
- result += renderWithFieldSuffix(
153
- options.withSuffixlessFieldMethods,
154
- field.name,
155
- (_methodNameSuffix) => renderWithStore(
156
- storeArgument,
157
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
69
+ `))),(!l||l.kind!=="staticArray")&&(i+=_(e.withSuffixlessFieldMethods,d.name,u=>D(t,({_typedStore:h,_store:f,_commentSuffix:m,_methodNamePrefix:p})=>`
158
70
  /**
159
- * @notice Push ${portionData.title} to ${field.name}${_commentSuffix}.
71
+ * @notice Push ${o.title} to ${d.name}${m}.
160
72
  */
161
- function ${_methodNamePrefix}push${_methodNameSuffix}(${renderArguments([
162
- _typedStore,
163
- _typedTableId,
164
- _typedKeyArgs,
165
- `${portionData.typeWithLocation} ${portionData.name}`
166
- ])}) internal {
167
- ${_keyTupleDefinition}
168
- ${_store}.pushToDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.encoded});
73
+ function ${p}push${u}(${S([h,n,r,`${o.typeWithLocation} ${o.name}`])}) internal {
74
+ ${s}
75
+ ${f}.pushToDynamicField(_tableId, _keyTuple, ${c}, ${o.encoded});
169
76
  }
170
- `
171
- )
172
- );
173
- result += renderWithFieldSuffix(
174
- options.withSuffixlessFieldMethods,
175
- field.name,
176
- (_methodNameSuffix) => renderWithStore(
177
- storeArgument,
178
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
77
+ `)),i+=_(e.withSuffixlessFieldMethods,d.name,u=>D(t,({_typedStore:h,_store:f,_commentSuffix:m,_methodNamePrefix:p})=>`
179
78
  /**
180
- * @notice Pop ${portionData.title} from ${field.name}${_commentSuffix}.
79
+ * @notice Pop ${o.title} from ${d.name}${m}.
181
80
  */
182
- function ${_methodNamePrefix}pop${_methodNameSuffix}(${renderArguments([
183
- _typedStore,
184
- _typedTableId,
185
- _typedKeyArgs
186
- ])}) internal {
187
- ${_keyTupleDefinition}
188
- ${_store}.popFromDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.elementLength});
81
+ function ${p}pop${u}(${S([h,n,r])}) internal {
82
+ ${s}
83
+ ${f}.popFromDynamicField(_tableId, _keyTuple, ${c}, ${o.elementLength});
189
84
  }
190
- `
191
- )
192
- );
193
- }
194
- result += renderWithFieldSuffix(
195
- options.withSuffixlessFieldMethods,
196
- field.name,
197
- (_methodNameSuffix) => renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {
198
- const externalArguments = renderArguments([
199
- _typedStore,
200
- _typedTableId,
201
- _typedKeyArgs,
202
- "uint256 _index",
203
- `${portionData.typeWithLocation} ${portionData.name}`
204
- ]);
205
- const internalArguments = `
85
+ `))),i+=_(e.withSuffixlessFieldMethods,d.name,u=>D(t,({_typedStore:h,_store:f,_commentSuffix:m,_methodNamePrefix:p})=>{let L=S([h,n,r,"uint256 _index",`${o.typeWithLocation} ${o.name}`]),x=`
206
86
  _tableId,
207
87
  _keyTuple,
208
- ${dynamicSchemaIndex},
209
- uint40(_index * ${portionData.elementLength}),
88
+ ${c},
89
+ uint40(_index * ${o.elementLength}),
210
90
  uint40(_encoded.length),
211
91
  _encoded
212
- `;
213
- return `
92
+ `;return`
214
93
  /**
215
- * @notice Update ${portionData.title} of ${field.name}${_commentSuffix} at \`_index\`.
94
+ * @notice Update ${o.title} of ${d.name}${m} at \`_index\`.
216
95
  */
217
- function ${_methodNamePrefix}update${_methodNameSuffix}(${externalArguments}) internal {
218
- ${_keyTupleDefinition}
96
+ function ${p}update${u}(${L}) internal {
97
+ ${s}
219
98
  unchecked {
220
- bytes memory _encoded = ${portionData.encoded};
221
- ${_store}.spliceDynamicData(${internalArguments});
99
+ bytes memory _encoded = ${o.encoded};
100
+ ${f}.spliceDynamicData(${x});
222
101
  }
223
102
  }
224
- `;
225
- })
226
- );
227
- }
228
- }
229
- return result;
230
- }
231
- function renderEncodeFieldSingle(field) {
232
- let func;
233
- if (field.arrayElement) {
234
- func = "EncodeArray.encode";
235
- } else if (field.isDynamic) {
236
- func = "bytes";
237
- } else {
238
- func = "abi.encodePacked";
239
- }
240
- return `${func}(${field.typeUnwrap}(${field.name}))`;
241
- }
242
- function renderDecodeValueType(field, offset) {
243
- const { staticByteLength } = field;
244
- const innerSlice = `Bytes.getBytes${staticByteLength}(_blob, ${offset})`;
245
- return renderCastStaticBytesToType(field, innerSlice);
246
- }
247
- function renderCastStaticBytesToType(field, staticBytes) {
248
- const { staticByteLength, internalTypeId } = field;
249
- const bits = staticByteLength * 8;
250
- let result;
251
- if (internalTypeId.match(/^uint\d{1,3}$/) || internalTypeId === "address") {
252
- result = `${internalTypeId}(${staticBytes})`;
253
- } else if (internalTypeId.match(/^int\d{1,3}$/)) {
254
- result = `${internalTypeId}(uint${bits}(${staticBytes}))`;
255
- } else if (internalTypeId.match(/^bytes\d{1,2}$/)) {
256
- result = staticBytes;
257
- } else if (internalTypeId === "bool") {
258
- result = `_toBool(uint8(${staticBytes}))`;
259
- } else {
260
- throw new Error(`Unknown value type id ${internalTypeId}`);
261
- }
262
- return `${field.typeWrap}(${result})`;
263
- }
264
- function fieldPortionData(field) {
265
- if (field.arrayElement) {
266
- const name = "_element";
267
- const elementFieldData = { ...field.arrayElement, arrayElement: void 0, name };
268
- return {
269
- typeWithLocation: field.arrayElement.typeWithLocation,
270
- name,
271
- encoded: renderEncodeFieldSingle(elementFieldData),
272
- decoded: renderDecodeFieldSingle(elementFieldData),
273
- title: "an element",
274
- elementLength: field.arrayElement.staticByteLength
275
- };
276
- } else {
277
- const name = "_slice";
278
- const elementFieldData = { ...field, name };
279
- return {
280
- typeWithLocation: `${field.typeId} memory`,
281
- name,
282
- encoded: renderEncodeFieldSingle(elementFieldData),
283
- decoded: renderDecodeFieldSingle(elementFieldData),
284
- title: "a slice",
285
- elementLength: 1
286
- };
287
- }
288
- }
289
- function renderDecodeFieldSingle(field) {
290
- const { isDynamic, arrayElement } = field;
291
- if (arrayElement) {
292
- return `${field.typeWrap}(
293
- SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_${arrayElement.internalTypeId}()
294
- )`;
295
- } else if (isDynamic) {
296
- return `${field.typeWrap}(${field.internalTypeId}(_blob))`;
297
- } else {
298
- return renderCastStaticBytesToType(field, `bytes${field.staticByteLength}(_blob)`);
299
- }
300
- }
301
-
302
- // ts/codegen/record.ts
303
- import {
304
- renderArguments as renderArguments2,
305
- renderCommonData as renderCommonData2,
306
- renderList,
307
- renderWithStore as renderWithStore2
308
- } from "@latticexyz/common/codegen";
309
- function renderRecordMethods(options) {
310
- const { structName, storeArgument } = options;
311
- const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData2(options);
312
- let result = "";
313
- if (options.withGetters) {
314
- result += renderWithStore2(
315
- storeArgument,
316
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
103
+ `}))}}return i}function E(e){let t;return e.arrayElement?t="EncodeArray.encode":e.isDynamic?t="bytes":t="abi.encodePacked",`${t}(${e.typeUnwrap}(${e.name}))`}function q(e,t){let{staticByteLength:n}=e,r=`Bytes.getBytes${n}(_blob, ${t})`;return W(e,r)}function W(e,t){let{staticByteLength:n,internalTypeId:r}=e,s=n*8,i;if(r.match(/^uint\d{1,3}$/)||r==="address")i=`${r}(${t})`;else if(r.match(/^int\d{1,3}$/))i=`${r}(uint${s}(${t}))`;else if(r.match(/^bytes\d{1,2}$/))i=t;else if(r==="bool")i=`_toBool(uint8(${t}))`;else throw new Error(`Unknown value type id ${r}`);return`${e.typeWrap}(${i})`}function ce(e){if(e.arrayElement){let t="_element",n={...e.arrayElement,arrayElement:void 0,name:t};return{typeWithLocation:e.arrayElement.typeWithLocation,name:t,encoded:E(n),decoded:N(n),title:"an element",elementLength:e.arrayElement.staticByteLength}}else{let t="_slice",n={...e,name:t};return{typeWithLocation:`${e.typeId} memory`,name:t,encoded:E(n),decoded:N(n),title:"a slice",elementLength:1}}}function N(e){let{isDynamic:t,arrayElement:n}=e;return n?`${e.typeWrap}(
104
+ SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_${n.internalTypeId}()
105
+ )`:t?`${e.typeWrap}(${e.internalTypeId}(_blob))`:W(e,`bytes${e.staticByteLength}(_blob)`)}import{renderArguments as g,renderCommonData as V,renderList as Y,renderWithStore as w}from"@latticexyz/common/codegen";function Z(e){let{structName:t,storeArgument:n}=e,{_typedTableId:r,_typedKeyArgs:s,_keyTupleDefinition:i}=V(e),a="";return e.withGetters&&(a+=w(n,({_typedStore:d,_store:y,_commentSuffix:o,_methodNamePrefix:c})=>`
317
106
  /**
318
- * @notice Get the full data${_commentSuffix}.
107
+ * @notice Get the full data${o}.
319
108
  */
320
- function ${_methodNamePrefix}get(${renderArguments2([
321
- _typedStore,
322
- _typedTableId,
323
- _typedKeyArgs
324
- ])}) internal view returns (${renderDecodedRecord(options)}) {
325
- ${_keyTupleDefinition}
109
+ function ${c}get(${g([d,r,s])}) internal view returns (${le(e)}) {
110
+ ${i}
326
111
 
327
112
  (
328
113
  bytes memory _staticData,
329
114
  EncodedLengths _encodedLengths,
330
115
  bytes memory _dynamicData
331
- ) = ${_store}.getRecord(_tableId, _keyTuple, _fieldLayout);
116
+ ) = ${y}.getRecord(_tableId, _keyTuple, _fieldLayout);
332
117
  return decode(_staticData, _encodedLengths, _dynamicData);
333
118
  }
334
- `
335
- );
336
- }
337
- result += renderWithStore2(
338
- storeArgument,
339
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {
340
- const externalArguments = renderArguments2([
341
- _typedStore,
342
- _typedTableId,
343
- _typedKeyArgs,
344
- renderArguments2(options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`))
345
- ]);
346
- const internalArguments = "_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData" + (_useExplicitFieldLayout ? ", _fieldLayout" : "");
347
- return `
119
+ `)),a+=w(n,({_typedStore:d,_store:y,_commentSuffix:o,_methodNamePrefix:c,_useExplicitFieldLayout:l})=>{let u=g([d,r,s,g(e.fields.map(({name:f,typeWithLocation:m})=>`${m} ${f}`))]),h="_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData"+(l?", _fieldLayout":"");return`
348
120
  /**
349
- * @notice Set the full data using individual values${_commentSuffix}.
121
+ * @notice Set the full data using individual values${o}.
350
122
  */
351
- function ${_methodNamePrefix}set(${externalArguments}) internal {
352
- ${renderRecordData(options)}
123
+ function ${c}set(${u}) internal {
124
+ ${O(e)}
353
125
 
354
- ${_keyTupleDefinition}
126
+ ${i}
355
127
 
356
- ${_store}.setRecord(${internalArguments});
128
+ ${y}.setRecord(${h});
357
129
  }
358
- `;
359
- }
360
- );
361
- if (structName !== void 0) {
362
- result += renderWithStore2(
363
- storeArgument,
364
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {
365
- const externalArguments = renderArguments2([
366
- _typedStore,
367
- _typedTableId,
368
- _typedKeyArgs,
369
- `${structName} memory _table`
370
- ]);
371
- const internalArguments = "_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData" + (_useExplicitFieldLayout ? ", _fieldLayout" : "");
372
- return `
130
+ `}),t!==void 0&&(a+=w(n,({_typedStore:d,_store:y,_commentSuffix:o,_methodNamePrefix:c,_useExplicitFieldLayout:l})=>{let u=g([d,r,s,`${t} memory _table`]),h="_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData"+(l?", _fieldLayout":"");return`
373
131
  /**
374
- * @notice Set the full data using the data struct${_commentSuffix}.
132
+ * @notice Set the full data using the data struct${o}.
375
133
  */
376
- function ${_methodNamePrefix}set(${externalArguments}) internal {
377
- ${renderRecordData(options, "_table.")}
134
+ function ${c}set(${u}) internal {
135
+ ${O(e,"_table.")}
378
136
 
379
- ${_keyTupleDefinition}
137
+ ${i}
380
138
 
381
- ${_store}.setRecord(${internalArguments});
139
+ ${y}.setRecord(${h});
382
140
  }
383
- `;
384
- }
385
- );
386
- }
387
- result += renderDecodeFunctions(options);
388
- return result;
389
- }
390
- function renderRecordData(options, namePrefix = "") {
391
- let result = "";
392
- if (options.staticFields.length > 0) {
393
- result += `
141
+ `})),a+=me(e),a}function O(e,t=""){let n="";return e.staticFields.length>0?n+=`
394
142
  bytes memory _staticData = encodeStatic(
395
- ${renderArguments2(options.staticFields.map(({ name }) => `${namePrefix}${name}`))}
143
+ ${g(e.staticFields.map(({name:r})=>`${t}${r}`))}
396
144
  );
397
- `;
398
- } else {
399
- result += `bytes memory _staticData;`;
400
- }
401
- if (options.dynamicFields.length > 0) {
402
- result += `
145
+ `:n+="bytes memory _staticData;",e.dynamicFields.length>0?n+=`
403
146
  EncodedLengths _encodedLengths = encodeLengths(
404
- ${renderArguments2(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}
147
+ ${g(e.dynamicFields.map(({name:r})=>`${t}${r}`))}
405
148
  );
406
149
  bytes memory _dynamicData = encodeDynamic(
407
- ${renderArguments2(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}
150
+ ${g(e.dynamicFields.map(({name:r})=>`${t}${r}`))}
408
151
  );
409
- `;
410
- } else {
411
- result += `
152
+ `:n+=`
412
153
  EncodedLengths _encodedLengths;
413
154
  bytes memory _dynamicData;
414
- `;
415
- }
416
- return result;
417
- }
418
- function renderDeleteRecordMethods(options) {
419
- const { storeArgument } = options;
420
- const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData2(options);
421
- return renderWithStore2(
422
- storeArgument,
423
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {
424
- const externalArguments = renderArguments2([_typedStore, _typedTableId, _typedKeyArgs]);
425
- const internalArguments = "_tableId, _keyTuple" + (_useExplicitFieldLayout ? ", _fieldLayout" : "");
426
- return `
155
+ `,n}function z(e){let{storeArgument:t}=e,{_typedTableId:n,_typedKeyArgs:r,_keyTupleDefinition:s}=V(e);return w(t,({_typedStore:i,_store:a,_commentSuffix:d,_methodNamePrefix:y,_useExplicitFieldLayout:o})=>{let c=g([i,n,r]),l="_tableId, _keyTuple"+(o?", _fieldLayout":"");return`
427
156
  /**
428
- * @notice Delete all data for given keys${_commentSuffix}.
157
+ * @notice Delete all data for given keys${d}.
429
158
  */
430
- function ${_methodNamePrefix}deleteRecord(${externalArguments}) internal {
431
- ${_keyTupleDefinition}
432
- ${_store}.deleteRecord(${internalArguments});
159
+ function ${y}deleteRecord(${c}) internal {
160
+ ${s}
161
+ ${a}.deleteRecord(${l});
433
162
  }
434
- `;
435
- }
436
- );
437
- }
438
- function renderDecodeFunctions({ structName, fields, staticFields, dynamicFields }) {
439
- const renderedDecodedRecord = structName ? `${structName} memory _table` : renderArguments2(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
440
- const fieldNamePrefix = structName ? "_table." : "";
441
- const staticOffsets = staticFields.map(() => 0);
442
- let _acc = 0;
443
- for (const [index, field] of staticFields.entries()) {
444
- staticOffsets[index] = _acc;
445
- _acc += field.staticByteLength;
446
- }
447
- let result = "";
448
- if (staticFields.length > 0) {
449
- result += `
163
+ `})}function me({structName:e,fields:t,staticFields:n,dynamicFields:r}){let s=e?`${e} memory _table`:g(t.map(({name:o,typeWithLocation:c})=>`${c} ${o}`)),i=e?"_table.":"",a=n.map(()=>0),d=0;for(let[o,c]of n.entries())a[o]=d,d+=c.staticByteLength;let y="";return n.length>0&&(y+=`
450
164
  /**
451
165
  * @notice Decode the tightly packed blob of static data using this table's field layout.
452
166
  */
453
- function decodeStatic(bytes memory _blob) internal pure returns (${renderArguments2(
454
- staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
455
- )}) {
456
- ${renderList(
457
- staticFields,
458
- (field, index) => `
459
- ${field.name} = ${renderDecodeValueType(field, staticOffsets[index])};
460
- `
461
- )}
167
+ function decodeStatic(bytes memory _blob) internal pure returns (${g(n.map(({name:o,typeWithLocation:c})=>`${c} ${o}`))}) {
168
+ ${Y(n,(o,c)=>`
169
+ ${o.name} = ${q(o,a[c])};
170
+ `)}
462
171
  }
463
- `;
464
- }
465
- if (dynamicFields.length > 0) {
466
- result += `
172
+ `),r.length>0&&(y+=`
467
173
  /**
468
174
  * @notice Decode the tightly packed blob of dynamic data using the encoded lengths.
469
175
  */
470
- function decodeDynamic(EncodedLengths _encodedLengths, bytes memory _blob) internal pure returns (${renderArguments2(
471
- dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
472
- )}) {
473
- ${renderList(
474
- dynamicFields,
475
- // unchecked is only dangerous if _encodedLengths (and _blob) is invalid,
476
- // but it's assumed to be valid, and this function is meant to be mostly used internally
477
- (field, index) => {
478
- if (index === 0) {
479
- return `
176
+ function decodeDynamic(EncodedLengths _encodedLengths, bytes memory _blob) internal pure returns (${g(r.map(({name:o,typeWithLocation:c})=>`${c} ${o}`))}) {
177
+ ${Y(r,(o,c)=>c===0?`
480
178
  uint256 _start;
481
179
  uint256 _end;
482
180
  unchecked {
483
- _end = _encodedLengths.atIndex(${index});
181
+ _end = _encodedLengths.atIndex(${c});
484
182
  }
485
- ${field.name} = ${renderDecodeDynamicFieldPartial(field)};
486
- `;
487
- } else {
488
- return `
183
+ ${o.name} = ${X(o)};
184
+ `:`
489
185
  _start = _end;
490
186
  unchecked {
491
- _end += _encodedLengths.atIndex(${index});
187
+ _end += _encodedLengths.atIndex(${c});
492
188
  }
493
- ${field.name} = ${renderDecodeDynamicFieldPartial(field)};
494
- `;
495
- }
496
- }
497
- )}
189
+ ${o.name} = ${X(o)};
190
+ `)}
498
191
  }
499
- `;
500
- }
501
- result += `
192
+ `),y+=`
502
193
  /**
503
194
  * @notice Decode the tightly packed blobs using this table's field layout.
504
- * ${staticFields.length > 0 ? "@param _staticData Tightly packed static fields." : ""}
505
- * ${dynamicFields.length > 0 ? "@param _encodedLengths Encoded lengths of dynamic fields." : ""}
506
- * ${dynamicFields.length > 0 ? "@param _dynamicData Tightly packed dynamic fields." : ""}
195
+ * ${n.length>0?"@param _staticData Tightly packed static fields.":""}
196
+ * ${r.length>0?"@param _encodedLengths Encoded lengths of dynamic fields.":""}
197
+ * ${r.length>0?"@param _dynamicData Tightly packed dynamic fields.":""}
507
198
  */
508
199
  function decode(
509
- bytes memory ${staticFields.length > 0 ? "_staticData" : ""},
510
- EncodedLengths ${dynamicFields.length > 0 ? "_encodedLengths" : ""},
511
- bytes memory ${dynamicFields.length > 0 ? "_dynamicData" : ""}
512
- ) internal pure returns (${renderedDecodedRecord}) {
513
- `;
514
- if (staticFields.length > 0) {
515
- result += `
516
- (${renderArguments2(staticFields.map((field) => `${fieldNamePrefix}${field.name}`))}) = decodeStatic(_staticData);
517
- `;
518
- }
519
- if (dynamicFields.length > 0) {
520
- result += `
521
- (${renderArguments2(
522
- dynamicFields.map((field) => `${fieldNamePrefix}${field.name}`)
523
- )}) = decodeDynamic(_encodedLengths, _dynamicData);
524
- `;
525
- }
526
- result += `
200
+ bytes memory ${n.length>0?"_staticData":""},
201
+ EncodedLengths ${r.length>0?"_encodedLengths":""},
202
+ bytes memory ${r.length>0?"_dynamicData":""}
203
+ ) internal pure returns (${s}) {
204
+ `,n.length>0&&(y+=`
205
+ (${g(n.map(o=>`${i}${o.name}`))}) = decodeStatic(_staticData);
206
+ `),r.length>0&&(y+=`
207
+ (${g(r.map(o=>`${i}${o.name}`))}) = decodeDynamic(_encodedLengths, _dynamicData);
208
+ `),y+=`
527
209
  }
528
- `;
529
- return result;
530
- }
531
- function renderDecodedRecord({ structName, fields }) {
532
- if (structName) {
533
- return `${structName} memory _table`;
534
- } else {
535
- return renderArguments2(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
536
- }
537
- }
538
- function renderDecodeDynamicFieldPartial(field) {
539
- const { typeId, arrayElement, typeWrap } = field;
540
- if (arrayElement) {
541
- return `${typeWrap}(
542
- SliceLib.getSubslice(_blob, _start, _end).decodeArray_${arrayElement.typeId}()
543
- )`;
544
- } else {
545
- return `${typeWrap}(
546
- ${typeId}(
210
+ `,y}function le({structName:e,fields:t}){return e?`${e} memory _table`:g(t.map(({name:n,typeWithLocation:r})=>`${r} ${n}`))}function X(e){let{typeId:t,arrayElement:n,typeWrap:r}=e;return n?`${r}(
211
+ SliceLib.getSubslice(_blob, _start, _end).decodeArray_${n.typeId}()
212
+ )`:`${r}(
213
+ ${t}(
547
214
  SliceLib.getSubslice(_blob, _start, _end).toBytes()
548
215
  )
549
- )`;
550
- }
551
- }
552
-
553
- // ts/codegen/renderTable.ts
554
- import {
555
- renderArguments as renderArguments3,
556
- renderCommonData as renderCommonData3,
557
- renderList as renderList2,
558
- renderImports,
559
- renderTableId,
560
- renderTypeHelpers,
561
- renderWithStore as renderWithStore3,
562
- renderedSolidityHeader,
563
- renderImportPath
564
- } from "@latticexyz/common/codegen";
565
-
566
- // ts/constants.ts
567
- var WORD_SIZE = 32;
568
- var WORD_LAST_INDEX = 31;
569
- var BYTE_TO_BITS = 8;
570
- var MAX_TOTAL_FIELDS = 28;
571
- var MAX_DYNAMIC_FIELDS = 5;
572
- var LayoutOffsets = {
573
- TOTAL_LENGTH: (WORD_SIZE - 2) * BYTE_TO_BITS,
574
- NUM_STATIC_FIELDS: (WORD_SIZE - 2 - 1) * BYTE_TO_BITS,
575
- NUM_DYNAMIC_FIELDS: (WORD_SIZE - 2 - 1 - 1) * BYTE_TO_BITS
576
- };
577
-
578
- // ts/codegen/renderFieldLayout.ts
579
- function renderFieldLayout(fields) {
580
- return `FieldLayout constant _fieldLayout = FieldLayout.wrap(${encodeFieldLayout(fields)});`;
581
- }
582
- function encodeFieldLayout(fields) {
583
- const staticFields = fields.filter(({ isDynamic }) => !isDynamic);
584
- const numDynamicFields = fields.length - staticFields.length;
585
- let fieldLayout = 0n;
586
- let totalLength = 0;
587
- const totalFields = fields.length;
588
- if (totalFields > MAX_TOTAL_FIELDS) throw new Error("FieldLayout: too many fields");
589
- if (numDynamicFields > MAX_DYNAMIC_FIELDS) throw new Error("FieldLayout: too many dynamic fields");
590
- for (let i = 0; i < staticFields.length; i++) {
591
- const { isDynamic, staticByteLength } = fields[i];
592
- if (isDynamic) throw new Error(`FieldLayout: static type after dynamic type`);
593
- totalLength += staticByteLength;
594
- fieldLayout |= BigInt(staticByteLength) << BigInt((WORD_LAST_INDEX - 4 - i) * BYTE_TO_BITS);
595
- }
596
- fieldLayout |= BigInt(totalLength) << BigInt(LayoutOffsets.TOTAL_LENGTH);
597
- fieldLayout |= BigInt(staticFields.length) << BigInt(LayoutOffsets.NUM_STATIC_FIELDS);
598
- fieldLayout |= BigInt(numDynamicFields) << BigInt(LayoutOffsets.NUM_DYNAMIC_FIELDS);
599
- return `0x${fieldLayout.toString(16).padStart(64, "0")}`;
600
- }
601
-
602
- // ts/codegen/renderTable.ts
603
- import { keySchemaToHex, valueSchemaToHex } from "@latticexyz/protocol-parser/internal";
604
- function renderTable(options) {
605
- const {
606
- imports,
607
- libraryName,
608
- structName,
609
- staticResourceData,
610
- storeImportPath,
611
- fields,
612
- staticFields,
613
- dynamicFields,
614
- withRecordMethods,
615
- storeArgument,
616
- keyTuple
617
- } = options;
618
- const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData3(options);
619
- return `
620
- ${renderedSolidityHeader}
216
+ )`}import{renderArguments as b,renderCommonData as $e,renderList as P,renderImports as ge,renderTableId as Te,renderTypeHelpers as be,renderWithStore as _e,renderedSolidityHeader as Le,renderImportPath as T}from"@latticexyz/common/codegen";var v={TOTAL_LENGTH:240,NUM_STATIC_FIELDS:232,NUM_DYNAMIC_FIELDS:224};function J(e){return`FieldLayout constant _fieldLayout = FieldLayout.wrap(${fe(e)});`}function fe(e){let t=e.filter(({isDynamic:a})=>!a),n=e.length-t.length,r=0n,s=0;if(e.length>28)throw new Error("FieldLayout: too many fields");if(n>5)throw new Error("FieldLayout: too many dynamic fields");for(let a=0;a<t.length;a++){let{isDynamic:d,staticByteLength:y}=e[a];if(d)throw new Error("FieldLayout: static type after dynamic type");s+=y,r|=BigInt(y)<<BigInt((27-a)*8)}return r|=BigInt(s)<<BigInt(v.TOTAL_LENGTH),r|=BigInt(t.length)<<BigInt(v.NUM_STATIC_FIELDS),r|=BigInt(n)<<BigInt(v.NUM_DYNAMIC_FIELDS),`0x${r.toString(16).padStart(64,"0")}`}import{keySchemaToHex as Se,valueSchemaToHex as De}from"@latticexyz/protocol-parser/internal";function Q(e){let{imports:t,libraryName:n,structName:r,staticResourceData:s,storeImportPath:i,fields:a,staticFields:d,dynamicFields:y,withRecordMethods:o,storeArgument:c,keyTuple:l}=e,{_typedTableId:u,_typedKeyArgs:h,_keyTupleDefinition:f}=$e(e);return`
217
+ ${Le}
621
218
 
622
219
  // Import store internals
623
- import { IStore } from "${renderImportPath(storeImportPath, "IStore.sol")}";
624
- import { StoreSwitch } from "${renderImportPath(storeImportPath, "StoreSwitch.sol")}";
625
- import { StoreCore } from "${renderImportPath(storeImportPath, "StoreCore.sol")}";
626
- import { Bytes } from "${renderImportPath(storeImportPath, "Bytes.sol")}";
627
- import { Memory } from "${renderImportPath(storeImportPath, "Memory.sol")}";
628
- import { SliceLib } from "${renderImportPath(storeImportPath, "Slice.sol")}";
629
- import { EncodeArray } from "${renderImportPath(storeImportPath, "tightcoder/EncodeArray.sol")}";
630
- import { FieldLayout } from "${renderImportPath(storeImportPath, "FieldLayout.sol")}";
631
- import { Schema } from "${renderImportPath(storeImportPath, "Schema.sol")}";
632
- import { EncodedLengths, EncodedLengthsLib } from "${renderImportPath(storeImportPath, "EncodedLengths.sol")}";
633
- import { ResourceId } from "${renderImportPath(storeImportPath, "ResourceId.sol")}";
634
-
635
- ${imports.length > 0 ? `
220
+ import { IStore } from "${T(i,"IStore.sol")}";
221
+ import { StoreSwitch } from "${T(i,"StoreSwitch.sol")}";
222
+ import { StoreCore } from "${T(i,"StoreCore.sol")}";
223
+ import { Bytes } from "${T(i,"Bytes.sol")}";
224
+ import { Memory } from "${T(i,"Memory.sol")}";
225
+ import { SliceLib } from "${T(i,"Slice.sol")}";
226
+ import { EncodeArray } from "${T(i,"tightcoder/EncodeArray.sol")}";
227
+ import { FieldLayout } from "${T(i,"FieldLayout.sol")}";
228
+ import { Schema } from "${T(i,"Schema.sol")}";
229
+ import { EncodedLengths, EncodedLengthsLib } from "${T(i,"EncodedLengths.sol")}";
230
+ import { ResourceId } from "${T(i,"ResourceId.sol")}";
231
+
232
+ ${t.length>0?`
636
233
  // Import user types
637
- ${renderImports(imports)}
638
- ` : ""}
234
+ ${ge(t)}
235
+ `:""}
639
236
 
640
- ${!structName ? "" : `
641
- struct ${structName} {
642
- ${renderList2(fields, ({ name, typeId }) => `${typeId} ${name};`)}
237
+ ${r?`
238
+ struct ${r} {
239
+ ${P(a,({name:m,typeId:p})=>`${p} ${m};`)}
643
240
  }
644
- `}
241
+ `:""}
645
242
 
646
- library ${libraryName} {
647
- ${staticResourceData ? renderTableId(staticResourceData) : ""}
243
+ library ${n} {
244
+ ${s?Te(s):""}
648
245
 
649
- ${renderFieldLayout(fields)}
246
+ ${J(a)}
650
247
 
651
- // Hex-encoded key schema of (${keyTuple.map((field) => field.internalTypeId).join(", ")})
652
- Schema constant _keySchema = Schema.wrap(${keySchemaToHex(
653
- Object.fromEntries(keyTuple.map((field) => [field.name, field.internalTypeId]))
654
- )});
655
- // Hex-encoded value schema of (${fields.map((field) => field.internalTypeId).join(", ")})
656
- Schema constant _valueSchema = Schema.wrap(${valueSchemaToHex(
657
- Object.fromEntries(fields.map((field) => [field.name, field.internalTypeId]))
658
- )});
248
+ // Hex-encoded key schema of (${l.map(m=>m.internalTypeId).join(", ")})
249
+ Schema constant _keySchema = Schema.wrap(${Se(Object.fromEntries(l.map(m=>[m.name,m.internalTypeId])))});
250
+ // Hex-encoded value schema of (${a.map(m=>m.internalTypeId).join(", ")})
251
+ Schema constant _valueSchema = Schema.wrap(${De(Object.fromEntries(a.map(m=>[m.name,m.internalTypeId])))});
659
252
 
660
253
  /**
661
254
  * @notice Get the table's key field names.
662
255
  * @return keyNames An array of strings with the names of key fields.
663
256
  */
664
257
  function getKeyNames() internal pure returns (string[] memory keyNames) {
665
- keyNames = new string[](${keyTuple.length});
666
- ${renderList2(keyTuple, (keyElement, index) => `keyNames[${index}] = "${keyElement.name}";`)}
258
+ keyNames = new string[](${l.length});
259
+ ${P(l,(m,p)=>`keyNames[${p}] = "${m.name}";`)}
667
260
  }
668
261
 
669
262
  /**
@@ -671,33 +264,30 @@ function renderTable(options) {
671
264
  * @return fieldNames An array of strings with the names of value fields.
672
265
  */
673
266
  function getFieldNames() internal pure returns (string[] memory fieldNames) {
674
- fieldNames = new string[](${fields.length});
675
- ${renderList2(fields, (field, index) => `fieldNames[${index}] = "${field.name}";`)}
267
+ fieldNames = new string[](${a.length});
268
+ ${P(a,(m,p)=>`fieldNames[${p}] = "${m.name}";`)}
676
269
  }
677
270
 
678
- ${renderWithStore3(
679
- storeArgument,
680
- ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `
271
+ ${_e(c,({_typedStore:m,_store:p,_commentSuffix:L,_methodNamePrefix:x})=>`
681
272
  /**
682
- * @notice Register the table with its config${_commentSuffix}.
273
+ * @notice Register the table with its config${L}.
683
274
  */
684
- function ${_methodNamePrefix}register(${renderArguments3([_typedStore, _typedTableId])}) internal {
685
- ${_store}.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames());
275
+ function ${x}register(${b([m,u])}) internal {
276
+ ${p}.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames());
686
277
  }
687
- `
688
- )}
278
+ `)}
689
279
 
690
- ${renderFieldMethods(options)}
280
+ ${K(e)}
691
281
 
692
- ${withRecordMethods ? renderRecordMethods(options) : ""}
282
+ ${o?Z(e):""}
693
283
 
694
- ${renderDeleteRecordMethods(options)}
284
+ ${z(e)}
695
285
 
696
- ${renderEncodeStatic(staticFields)}
286
+ ${Ie(d)}
697
287
 
698
- ${renderEncodeLengths(dynamicFields)}
288
+ ${xe(y)}
699
289
 
700
- ${renderEncodeDynamic(dynamicFields)}
290
+ ${Ae(y)}
701
291
 
702
292
  /**
703
293
  * @notice Encode all of a record's fields.
@@ -705,10 +295,8 @@ function renderTable(options) {
705
295
  * @return The lengths of the dynamic fields (packed into a single bytes32 value).
706
296
  * @return The dynamic (variable length) data, encoded into a sequence of bytes.
707
297
  */
708
- function encode(${renderArguments3(
709
- options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
710
- )}) internal pure returns (bytes memory, EncodedLengths, bytes memory) {
711
- ${renderRecordData(options)}
298
+ function encode(${b(e.fields.map(({name:m,typeWithLocation:p})=>`${p} ${m}`))}) internal pure returns (bytes memory, EncodedLengths, bytes memory) {
299
+ ${O(e)}
712
300
 
713
301
  return (_staticData, _encodedLengths, _dynamicData);
714
302
  }
@@ -716,423 +304,87 @@ function renderTable(options) {
716
304
  /**
717
305
  * @notice Encode keys as a bytes32 array using this table's field layout.
718
306
  */
719
- function encodeKeyTuple(${renderArguments3([_typedKeyArgs])}) internal pure returns (bytes32[] memory) {
720
- ${_keyTupleDefinition}
307
+ function encodeKeyTuple(${b([h])}) internal pure returns (bytes32[] memory) {
308
+ ${f}
721
309
  return _keyTuple;
722
310
  }
723
311
  }
724
312
 
725
- ${renderTypeHelpers(options)}
726
- `;
727
- }
728
- function renderEncodeStatic(staticFields) {
729
- if (staticFields.length === 0) return "";
730
- return `
313
+ ${be(e)}
314
+ `}function Ie(e){return e.length===0?"":`
731
315
  /**
732
316
  * @notice Tightly pack static (fixed length) data using this table's schema.
733
317
  * @return The static data, encoded into a sequence of bytes.
734
318
  */
735
- function encodeStatic(${renderArguments3(
736
- staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
737
- )}) internal pure returns (bytes memory) {
738
- return abi.encodePacked(${renderArguments3(staticFields.map(({ name }) => name))});
319
+ function encodeStatic(${b(e.map(({name:t,typeWithLocation:n})=>`${n} ${t}`))}) internal pure returns (bytes memory) {
320
+ return abi.encodePacked(${b(e.map(({name:t})=>t))});
739
321
  }
740
- `;
741
- }
742
- function renderEncodeLengths(dynamicFields) {
743
- if (dynamicFields.length === 0) return "";
744
- return `
322
+ `}function xe(e){return e.length===0?"":`
745
323
  /**
746
324
  * @notice Tightly pack dynamic data lengths using this table's schema.
747
325
  * @return _encodedLengths The lengths of the dynamic fields (packed into a single bytes32 value).
748
326
  */
749
- function encodeLengths(${renderArguments3(
750
- dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
751
- )}) internal pure returns (EncodedLengths _encodedLengths) {
327
+ function encodeLengths(${b(e.map(({name:t,typeWithLocation:n})=>`${n} ${t}`))}) internal pure returns (EncodedLengths _encodedLengths) {
752
328
  // Lengths are effectively checked during copy by 2**40 bytes exceeding gas limits
753
329
  unchecked {
754
330
  _encodedLengths = EncodedLengthsLib.pack(
755
- ${renderArguments3(
756
- dynamicFields.map(({ name, arrayElement }) => {
757
- if (arrayElement) {
758
- return `${name}.length * ${arrayElement.staticByteLength}`;
759
- } else {
760
- return `bytes(${name}).length`;
761
- }
762
- })
763
- )}
331
+ ${b(e.map(({name:t,arrayElement:n})=>n?`${t}.length * ${n.staticByteLength}`:`bytes(${t}).length`))}
764
332
  );
765
333
  }
766
334
  }
767
- `;
768
- }
769
- function renderEncodeDynamic(dynamicFields) {
770
- if (dynamicFields.length === 0) return "";
771
- return `
335
+ `}function Ae(e){return e.length===0?"":`
772
336
  /**
773
337
  * @notice Tightly pack dynamic (variable length) data using this table's schema.
774
338
  * @return The dynamic data, encoded into a sequence of bytes.
775
339
  */
776
- function encodeDynamic(${renderArguments3(
777
- dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)
778
- )}) internal pure returns (bytes memory) {
779
- return abi.encodePacked(${renderArguments3(dynamicFields.map((field) => renderEncodeFieldSingle(field)))});
780
- }
781
- `;
782
- }
783
-
784
- // ts/codegen/renderTypesFromConfig.ts
785
- import { renderEnums } from "@latticexyz/common/codegen";
786
- function renderTypesFromConfig(config) {
787
- return renderEnums(config.enums);
788
- }
789
-
790
- // ts/codegen/tablegen.ts
791
- import fs from "node:fs/promises";
792
- import path4 from "node:path";
793
- import { formatAndWriteSolidity, renderEnums as renderEnums2 } from "@latticexyz/common/codegen";
794
-
795
- // ts/codegen/renderTableIndex.ts
796
- import { renderImportPath as renderImportPath2, renderList as renderList3, renderedSolidityHeader as renderedSolidityHeader2 } from "@latticexyz/common/codegen";
797
- import path from "node:path";
798
- function renderTableIndex(codegenIndexPath, options) {
799
- return `
800
- ${renderedSolidityHeader2}
801
-
802
- ${renderList3(options, ({ outputPath, tableName, renderOptions: { structName } }) => {
803
- const imports = [tableName];
804
- if (structName) imports.push(structName);
805
- return `import { ${imports.join(", ")} } from "${renderImportPath2("./" + path.relative(path.dirname(codegenIndexPath), outputPath))}";`;
806
- })}
807
- `;
808
- }
809
-
810
- // ts/codegen/tablegen.ts
811
- import { uniqueBy } from "@latticexyz/common/utils";
812
-
813
- // ts/codegen/getUserTypesFilename.ts
814
- import path2 from "node:path";
815
- function getUserTypesFilename({ config }) {
816
- return path2.join(config.sourceDirectory, config.codegen.outputDirectory, config.codegen.userTypesFilename);
817
- }
818
-
819
- // ts/codegen/getUserTypes.ts
820
- import { groupBy } from "@latticexyz/common/utils";
821
- function getUserTypes({ config }) {
822
- const enums = Object.keys(config.enums).map(
823
- (name) => ({
824
- type: "enum",
825
- name,
826
- abiType: "uint8",
827
- importPath: "./" + getUserTypesFilename({ config })
828
- })
829
- );
830
- const userTypes = Object.entries(config.userTypes).map(
831
- ([name, userType]) => ({
832
- type: "userType",
833
- name,
834
- abiType: userType.type,
835
- // If `userType.filePath` starts with a `.`, it's relative to the root dir
836
- importPath: userType.filePath
837
- })
838
- );
839
- const result = [...enums, ...userTypes];
840
- const duplicates = Array.from(groupBy(result, (userType) => userType.name).entries()).filter(([, entries]) => entries.length > 1).map(([name]) => name);
841
- if (duplicates.length > 0) {
842
- throw new Error(`Found enums and user types sharing the same name: ${duplicates.join(", ")}`);
843
- }
844
- return result;
845
- }
846
-
847
- // ts/codegen/getTableOptions.ts
848
- import path3 from "path";
849
- import { SchemaTypeArrayToElement } from "@latticexyz/schema-type/deprecated";
850
-
851
- // ts/codegen/userType.ts
852
- import {
853
- AbiTypeToSchemaType,
854
- getStaticByteLength,
855
- SchemaType,
856
- SchemaTypeToAbiType
857
- } from "@latticexyz/schema-type/deprecated";
858
- function parseStaticArray(abiType) {
859
- const matches = abiType.match(/^(\w+)\[(\d+)\]$/);
860
- if (!matches) return null;
861
- return {
862
- elementType: matches[1],
863
- staticLength: Number.parseInt(matches[2])
864
- };
865
- }
866
- function resolveAbiOrUserType(abiOrUserType, userTypes) {
867
- if (abiOrUserType in AbiTypeToSchemaType) {
868
- const schemaType = AbiTypeToSchemaType[abiOrUserType];
869
- return {
870
- schemaType,
871
- renderType: getSchemaTypeInfo(schemaType)
872
- };
873
- }
874
- const staticArray = parseStaticArray(abiOrUserType);
875
- if (staticArray) {
876
- if (staticArray.elementType in AbiTypeToSchemaType) {
877
- return getStaticArrayTypeInfo(abiOrUserType, staticArray.elementType, staticArray.staticLength);
878
- } else {
879
- throw new Error("Static arrays of user types are not supported");
880
- }
881
- }
882
- const userType = userTypes.find((type) => type.name === abiOrUserType);
883
- if (!userType) {
884
- throw new Error(`User type "${abiOrUserType}" not found`);
885
- }
886
- return getUserTypeInfo(userType);
887
- }
888
- function getSchemaTypeInfo(schemaType) {
889
- const staticByteLength = getStaticByteLength(schemaType);
890
- const isDynamic = staticByteLength === 0;
891
- const typeId = SchemaTypeToAbiType[schemaType];
892
- return {
893
- typeId,
894
- typeWithLocation: isDynamic ? typeId + " memory" : typeId,
895
- enumName: SchemaType[schemaType],
896
- staticByteLength,
897
- isDynamic,
898
- typeWrap: "",
899
- typeUnwrap: "",
900
- internalTypeId: typeId
901
- };
902
- }
903
- function getUserTypeInfo(userType) {
904
- switch (userType.type) {
905
- case "enum": {
906
- const schemaType = SchemaType.UINT8;
907
- const staticByteLength = getStaticByteLength(schemaType);
908
- const isDynamic = staticByteLength === 0;
909
- return {
910
- schemaType,
911
- renderType: {
912
- typeId: userType.name,
913
- typeWithLocation: userType.name,
914
- enumName: SchemaType[schemaType],
915
- staticByteLength,
916
- isDynamic,
917
- typeWrap: userType.name,
918
- typeUnwrap: userType.abiType,
919
- internalTypeId: userType.abiType
920
- }
921
- };
922
- }
923
- case "userType": {
924
- const schemaType = AbiTypeToSchemaType[userType.abiType];
925
- return {
926
- schemaType,
927
- renderType: {
928
- typeId: userType.name,
929
- typeWithLocation: userType.name,
930
- enumName: SchemaType[schemaType],
931
- staticByteLength: getStaticByteLength(schemaType),
932
- isDynamic: false,
933
- typeWrap: `${userType.name}.wrap`,
934
- typeUnwrap: `${userType.name}.unwrap`,
935
- internalTypeId: userType.abiType
936
- }
937
- };
938
- }
939
- }
940
- }
941
- function getStaticArrayTypeInfo(abiType, elementType, staticLength) {
942
- const internalTypeId = elementType + "[]";
943
- const schemaType = AbiTypeToSchemaType[internalTypeId];
944
- return {
945
- schemaType,
946
- renderType: {
947
- typeId: abiType,
948
- typeWithLocation: `${abiType} memory`,
949
- enumName: SchemaType[schemaType],
950
- staticByteLength: 0,
951
- isDynamic: true,
952
- typeWrap: `toStaticArray_${elementType}_${staticLength}`,
953
- typeUnwrap: `fromStaticArray_${elementType}_${staticLength}`,
954
- typeWrappingData: {
955
- kind: "staticArray",
956
- elementType,
957
- staticLength
958
- },
959
- internalTypeId
340
+ function encodeDynamic(${b(e.map(({name:t,typeWithLocation:n})=>`${n} ${t}`))}) internal pure returns (bytes memory) {
341
+ return abi.encodePacked(${b(e.map(t=>E(t)))});
960
342
  }
961
- };
962
- }
963
-
964
- // ts/codegen/getTableOptions.ts
965
- import { getKeySchema, getValueSchema } from "@latticexyz/protocol-parser/internal";
966
- import { isDefined } from "@latticexyz/common/utils";
967
- function getTableOptions({
968
- tables,
969
- rootDir,
970
- codegenDir,
971
- userTypes,
972
- storeImportPath
973
- }) {
974
- const options = tables.map((table) => {
975
- const outputPath = path3.join(rootDir, codegenDir, table.codegen.outputDirectory, `${table.label}.sol`);
976
- const keySchema = getKeySchema(table);
977
- const valueSchema = getValueSchema(table);
978
- const withStruct = table.codegen.dataStruct;
979
- const withRecordMethods = withStruct || table.type === "offchainTable" || Object.keys(valueSchema).length > 1;
980
- const withSuffixlessFieldMethods = !withRecordMethods && Object.keys(valueSchema).length === 1;
981
- const imports = Object.values(table.schema).map((field) => userTypes.find((type) => type.name === field.internalType)).filter(isDefined).map((userType) => {
982
- return {
983
- // If it's a fully qualified name, remove trailing references
984
- // This enables support for user types inside libraries
985
- symbol: userType.name.replace(/\..*$/, ""),
986
- path: userType.importPath.startsWith(".") ? "./" + path3.relative(path3.dirname(outputPath), path3.join(rootDir, userType.importPath)) : userType.importPath
987
- };
988
- });
989
- const keyTuple = Object.entries(keySchema).map(([name, field]) => {
990
- const { renderType } = resolveAbiOrUserType(field.internalType, userTypes);
991
- return {
992
- ...renderType,
993
- name,
994
- isDynamic: false
995
- };
996
- });
997
- const fields = Object.entries(valueSchema).map(([name, field]) => {
998
- const { renderType, schemaType } = resolveAbiOrUserType(field.internalType, userTypes);
999
- const elementType = SchemaTypeArrayToElement[schemaType];
1000
- return {
1001
- ...renderType,
1002
- arrayElement: elementType !== void 0 ? getSchemaTypeInfo(elementType) : void 0,
1003
- name
1004
- };
1005
- });
1006
- const staticFields = fields.filter(({ isDynamic }) => !isDynamic);
1007
- const dynamicFields = fields.filter(({ isDynamic }) => isDynamic);
1008
- const staticResourceData = table.codegen.tableIdArgument ? void 0 : {
1009
- namespace: table.namespace,
1010
- name: table.name,
1011
- offchainOnly: table.type === "offchainTable"
1012
- };
1013
- return {
1014
- outputPath,
1015
- tableName: table.label,
1016
- renderOptions: {
1017
- imports,
1018
- libraryName: table.label,
1019
- structName: withStruct ? table.label + "Data" : void 0,
1020
- staticResourceData,
1021
- storeImportPath: storeImportPath.startsWith(".") ? "./" + path3.relative(path3.dirname(outputPath), path3.join(rootDir, storeImportPath)) : storeImportPath,
1022
- keyTuple,
1023
- fields,
1024
- staticFields,
1025
- dynamicFields,
1026
- withGetters: table.type === "table",
1027
- withRecordMethods,
1028
- withDynamicFieldMethods: table.type === "table",
1029
- withSuffixlessFieldMethods,
1030
- storeArgument: table.codegen.storeArgument
1031
- }
1032
- };
1033
- });
1034
- return options;
1035
- }
1036
-
1037
- // ts/codegen/tablegen.ts
1038
- import debug from "debug";
1039
- async function tablegen({ rootDir, config }) {
1040
- const userTypes = getUserTypes({ config });
1041
- if (Object.keys(config.enums).length > 0) {
1042
- const userTypesFilename = path4.join(rootDir, getUserTypesFilename({ config }));
1043
- const source = renderEnums2(config.enums);
1044
- await formatAndWriteSolidity(source, userTypesFilename, "Generated types file with enums");
1045
- }
1046
- await Promise.all(
1047
- Object.values(config.namespaces).map(async (namespace) => {
1048
- const sourceDir = config.multipleNamespaces ? path4.join(config.sourceDirectory, "namespaces", namespace.label) : config.sourceDirectory;
1049
- const codegenDir = path4.join(sourceDir, config.codegen.outputDirectory);
1050
- const tables = Object.values(namespace.tables);
1051
- if (tables.length === 0) return;
1052
- const tableOptions = getTableOptions({
1053
- tables,
1054
- rootDir,
1055
- codegenDir,
1056
- userTypes,
1057
- storeImportPath: config.codegen.storeImportPath
1058
- });
1059
- const tableDirs = uniqueBy(
1060
- tableOptions.map(({ outputPath }) => path4.dirname(outputPath)),
1061
- (dir) => dir
1062
- );
1063
- await Promise.all(tableDirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));
1064
- await Promise.all(
1065
- tableOptions.map(async ({ outputPath, renderOptions }) => {
1066
- const source = renderTable(renderOptions);
1067
- return await formatAndWriteSolidity(source, outputPath, "Generated table");
1068
- })
1069
- );
1070
- if (config.codegen.indexFilename !== false && tableOptions.length > 0) {
1071
- const codegenIndexPath = path4.join(rootDir, codegenDir, config.codegen.indexFilename);
1072
- const source = renderTableIndex(codegenIndexPath, tableOptions);
1073
- await formatAndWriteSolidity(source, codegenIndexPath, "Generated table index");
1074
- }
1075
- })
1076
- );
1077
- debug("Generated tables");
1078
- }
1079
-
1080
- // ts/codegen/tightcoder/renderDecodeSlice.ts
1081
- import { renderedSolidityHeader as renderedSolidityHeader3 } from "@latticexyz/common/codegen";
1082
- import { staticAbiTypeToByteLength, staticAbiTypes } from "@latticexyz/schema-type/internal";
343
+ `}import{renderEnums as Ee}from"@latticexyz/common/codegen";function St(e){return Ee(e.enums)}import je from"node:fs/promises";import k from"node:path";import{formatAndWriteSolidity as G,renderEnums as Ge}from"@latticexyz/common/codegen";import{renderImportPath as Fe,renderList as Re,renderedSolidityHeader as ke}from"@latticexyz/common/codegen";import ee from"node:path";function te(e,t){return`
344
+ ${ke}
1083
345
 
1084
- // ts/codegen/tightcoder/renderFunctions.ts
1085
- import { getLeftPaddingBits } from "@latticexyz/common/codegen";
1086
- function renderTightCoderDecode(element) {
1087
- return `
346
+ ${Re(t,({outputPath:n,tableName:r,renderOptions:{structName:s}})=>{let i=[r];return s&&i.push(s),`import { ${i.join(", ")} } from "${Fe("./"+ee.relative(ee.dirname(e),n))}";`})}
347
+ `}import{uniqueBy as He}from"@latticexyz/common/utils";import we from"node:path";function B({config:e}){return we.join(e.sourceDirectory,e.codegen.outputDirectory,e.codegen.userTypesFilename)}import{groupBy as Oe}from"@latticexyz/common/utils";function ne({config:e}){let t=Object.keys(e.enums).map(i=>({type:"enum",name:i,abiType:"uint8",importPath:"./"+B({config:e})})),n=Object.entries(e.userTypes).map(([i,a])=>({type:"userType",name:i,abiType:a.type,importPath:a.filePath})),r=[...t,...n],s=Array.from(Oe(r,i=>i.name).entries()).filter(([,i])=>i.length>1).map(([i])=>i);if(s.length>0)throw new Error(`Found enums and user types sharing the same name: ${s.join(", ")}`);return r}import I from"path";import{SchemaTypeArrayToElement as We}from"@latticexyz/schema-type/deprecated";import{AbiTypeToSchemaType as F,getStaticByteLength as C,SchemaType as R,SchemaTypeToAbiType as ve}from"@latticexyz/schema-type/deprecated";function Be(e){let t=e.match(/^(\w+)\[(\d+)\]$/);return t?{elementType:t[1],staticLength:Number.parseInt(t[2])}:null}function U(e,t){if(e in F){let s=F[e];return{schemaType:s,renderType:j(s)}}let n=Be(e);if(n){if(n.elementType in F)return Ne(e,n.elementType,n.staticLength);throw new Error("Static arrays of user types are not supported")}let r=t.find(s=>s.name===e);if(!r)throw new Error(`User type "${e}" not found`);return Me(r)}function j(e){let t=C(e),n=t===0,r=ve[e];return{typeId:r,typeWithLocation:n?r+" memory":r,enumName:R[e],staticByteLength:t,isDynamic:n,typeWrap:"",typeUnwrap:"",internalTypeId:r}}function Me(e){switch(e.type){case"enum":{let t=R.UINT8,n=C(t),r=n===0;return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:n,isDynamic:r,typeWrap:e.name,typeUnwrap:e.abiType,internalTypeId:e.abiType}}}case"userType":{let t=F[e.abiType];return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:C(t),isDynamic:!1,typeWrap:`${e.name}.wrap`,typeUnwrap:`${e.name}.unwrap`,internalTypeId:e.abiType}}}}}function Ne(e,t,n){let r=t+"[]",s=F[r];return{schemaType:s,renderType:{typeId:e,typeWithLocation:`${e} memory`,enumName:R[s],staticByteLength:0,isDynamic:!0,typeWrap:`toStaticArray_${t}_${n}`,typeUnwrap:`fromStaticArray_${t}_${n}`,typeWrappingData:{kind:"staticArray",elementType:t,staticLength:n},internalTypeId:r}}}import{getKeySchema as Pe,getValueSchema as Ce}from"@latticexyz/protocol-parser/internal";import{isDefined as Ue}from"@latticexyz/common/utils";function re({tables:e,rootDir:t,codegenDir:n,userTypes:r,storeImportPath:s}){return e.map(a=>{let d=I.join(t,n,a.codegen.outputDirectory,`${a.label}.sol`),y=Pe(a),o=Ce(a),c=a.codegen.dataStruct,l=c||a.type==="offchainTable"||Object.keys(o).length>1,u=!l&&Object.keys(o).length===1,h=Object.values(a.schema).map($=>r.find(A=>A.name===$.internalType)).filter(Ue).map($=>({symbol:$.name.replace(/\..*$/,""),path:$.importPath.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,$.importPath)):$.importPath})),f=Object.entries(y).map(([$,A])=>{let{renderType:M}=U(A.internalType,r);return{...M,name:$,isDynamic:!1}}),m=Object.entries(o).map(([$,A])=>{let{renderType:M,schemaType:de}=U(A.internalType,r),H=We[de];return{...M,arrayElement:H!==void 0?j(H):void 0,name:$}}),p=m.filter(({isDynamic:$})=>!$),L=m.filter(({isDynamic:$})=>$),x=a.codegen.tableIdArgument?void 0:{namespace:a.namespace,name:a.name,offchainOnly:a.type==="offchainTable"};return{outputPath:d,tableName:a.label,renderOptions:{imports:h,libraryName:a.label,structName:c?a.label+"Data":void 0,staticResourceData:x,storeImportPath:s.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,s)):s,keyTuple:f,fields:m,staticFields:p,dynamicFields:L,withGetters:a.type==="table",withRecordMethods:l,withDynamicFieldMethods:a.type==="table",withSuffixlessFieldMethods:u,storeArgument:a.codegen.storeArgument}}})}import Ke from"debug";async function zt({rootDir:e,config:t}){let n=ne({config:t});if(Object.keys(t.enums).length>0){let r=k.join(e,B({config:t})),s=Ge(t.enums);await G(s,r,"Generated types file with enums")}await Promise.all(Object.values(t.namespaces).map(async r=>{let s=t.multipleNamespaces?k.join(t.sourceDirectory,"namespaces",r.label):t.sourceDirectory,i=k.join(s,t.codegen.outputDirectory),a=Object.values(r.tables);if(a.length===0)return;let d=re({tables:a,rootDir:e,codegenDir:i,userTypes:n,storeImportPath:t.codegen.storeImportPath}),y=He(d.map(({outputPath:o})=>k.dirname(o)),o=>o);if(await Promise.all(y.map(o=>je.rm(o,{recursive:!0,force:!0}))),await Promise.all(d.map(async({outputPath:o,renderOptions:c})=>{let l=Q(c);return await G(l,o,"Generated table")})),t.codegen.indexFilename!==!1&&d.length>0){let o=k.join(e,i,t.codegen.indexFilename),c=te(o,d);await G(c,o,"Generated table index")}})),Ke("Generated tables")}import{renderedSolidityHeader as qe}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as Ye,staticAbiTypes as Xe}from"@latticexyz/schema-type/internal";import{getLeftPaddingBits as oe}from"@latticexyz/common/codegen";function ie(e){return`
1088
348
  /**
1089
- * @notice Decodes a slice into an array of ${element.internalTypeId}.
349
+ * @notice Decodes a slice into an array of ${e.internalTypeId}.
1090
350
  * @dev Uses TightCoder for initial decoding, and then assembly for memory conversion.
1091
351
  * @param _input The slice to decode.
1092
- * @return _output The decoded array of ${element.internalTypeId}.
352
+ * @return _output The decoded array of ${e.internalTypeId}.
1093
353
  */
1094
- function decodeArray_${element.internalTypeId}(
354
+ function decodeArray_${e.internalTypeId}(
1095
355
  Slice _input
1096
356
  ) internal pure returns (
1097
- ${element.internalTypeId}[] memory _output
357
+ ${e.internalTypeId}[] memory _output
1098
358
  ) {
1099
359
  bytes32[] memory _genericArray = TightCoder.decode(
1100
360
  _input,
1101
- ${element.staticByteLength},
1102
- ${getLeftPaddingBits(element)}
361
+ ${e.staticByteLength},
362
+ ${oe(e)}
1103
363
  );
1104
364
  assembly {
1105
365
  _output := _genericArray
1106
366
  }
1107
367
  }
1108
- `;
1109
- }
1110
- function renderTightCoderEncode(element) {
1111
- return `
368
+ `}function ae(e){return`
1112
369
 
1113
370
  /**
1114
- * @notice Encodes an array of ${element.internalTypeId} into a tightly packed bytes representation.
1115
- * @param _input The array of ${element.internalTypeId} values to be encoded.
371
+ * @notice Encodes an array of ${e.internalTypeId} into a tightly packed bytes representation.
372
+ * @param _input The array of ${e.internalTypeId} values to be encoded.
1116
373
  * @return The resulting tightly packed bytes representation of the input array.
1117
374
  */
1118
- function encode(${element.internalTypeId}[] memory _input) internal pure returns (bytes memory) {
375
+ function encode(${e.internalTypeId}[] memory _input) internal pure returns (bytes memory) {
1119
376
  bytes32[] memory _genericArray;
1120
377
  assembly {
1121
378
  _genericArray := _input
1122
379
  }
1123
380
  return TightCoder.encode(
1124
381
  _genericArray,
1125
- ${element.staticByteLength},
1126
- ${getLeftPaddingBits(element)}
382
+ ${e.staticByteLength},
383
+ ${oe(e)}
1127
384
  );
1128
385
  }
1129
- `;
1130
- }
1131
-
1132
- // ts/codegen/tightcoder/renderDecodeSlice.ts
1133
- function renderDecodeSlice() {
1134
- return `
1135
- ${renderedSolidityHeader3}
386
+ `}function an(){return`
387
+ ${qe}
1136
388
  import { TightCoder } from "./TightCoder.sol";
1137
389
  import { Slice } from "../Slice.sol";
1138
390
 
@@ -1143,22 +395,11 @@ function renderDecodeSlice() {
1143
395
  * @dev This library provides functions for decoding slices into arrays of basic uint types.
1144
396
  */
1145
397
  library DecodeSlice {
1146
- ${staticAbiTypes.map(
1147
- (staticAbiType) => renderTightCoderDecode({
1148
- internalTypeId: staticAbiType,
1149
- staticByteLength: staticAbiTypeToByteLength[staticAbiType]
1150
- })
1151
- ).join("\n")}
398
+ ${Xe.map(e=>ie({internalTypeId:e,staticByteLength:Ye[e]})).join(`
399
+ `)}
1152
400
  }
1153
- `;
1154
- }
1155
-
1156
- // ts/codegen/tightcoder/renderEncodeArray.ts
1157
- import { renderedSolidityHeader as renderedSolidityHeader4 } from "@latticexyz/common/codegen";
1158
- import { staticAbiTypeToByteLength as staticAbiTypeToByteLength2, staticAbiTypes as staticAbiTypes2 } from "@latticexyz/schema-type/internal";
1159
- function renderEncodeArray() {
1160
- return `
1161
- ${renderedSolidityHeader4}
401
+ `}import{renderedSolidityHeader as Ve}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as Ze,staticAbiTypes as ze}from"@latticexyz/schema-type/internal";function ln(){return`
402
+ ${Ve}
1162
403
  import { TightCoder } from "./TightCoder.sol";
1163
404
 
1164
405
  /**
@@ -1167,27 +408,16 @@ function renderEncodeArray() {
1167
408
  * @dev This library provides utilities for encoding arrays into tightly packed bytes representations.
1168
409
  */
1169
410
  library EncodeArray {
1170
- ${staticAbiTypes2.map(
1171
- (staticAbiType) => renderTightCoderEncode({
1172
- internalTypeId: staticAbiType,
1173
- staticByteLength: staticAbiTypeToByteLength2[staticAbiType]
1174
- })
1175
- ).join("\n")}
411
+ ${ze.map(e=>ae({internalTypeId:e,staticByteLength:Ze[e]})).join(`
412
+ `)}
1176
413
  }
1177
- `;
1178
- }
1179
-
1180
- // ts/codegen/tightcoder/renderTightCoderAutoTest.ts
1181
- import { renderedSolidityHeader as renderedSolidityHeader5 } from "@latticexyz/common/codegen";
1182
- import { staticAbiTypes as staticAbiTypes3 } from "@latticexyz/schema-type/internal";
1183
- function renderTightCoderAutoTestFunction({ typeId }) {
1184
- return `
1185
- function testEncodeDecodeArray_${typeId}(
1186
- ${typeId} val0,
1187
- ${typeId} val1,
1188
- ${typeId} val2
414
+ `}import{renderedSolidityHeader as Je}from"@latticexyz/common/codegen";import{staticAbiTypes as Qe}from"@latticexyz/schema-type/internal";function et({typeId:e}){return`
415
+ function testEncodeDecodeArray_${e}(
416
+ ${e} val0,
417
+ ${e} val1,
418
+ ${e} val2
1189
419
  ) public {
1190
- ${typeId}[] memory input = new ${typeId}[](3);
420
+ ${e}[] memory input = new ${e}[](3);
1191
421
  input[0] = val0;
1192
422
  input[1] = val1;
1193
423
  input[2] = val2;
@@ -1195,46 +425,21 @@ function renderTightCoderAutoTestFunction({ typeId }) {
1195
425
  bytes memory encoded = EncodeArray.encode(input);
1196
426
  assertEq(encoded, abi.encodePacked(val0, val1, val2));
1197
427
 
1198
- ${typeId}[] memory decoded = SliceLib.fromBytes(encoded).decodeArray_${typeId}();
428
+ ${e}[] memory decoded = SliceLib.fromBytes(encoded).decodeArray_${e}();
1199
429
  assertEq(decoded.length, 3);
1200
430
  assertEq(decoded[0], val0);
1201
431
  assertEq(decoded[1], val1);
1202
432
  assertEq(decoded[2], val2);
1203
433
  }
1204
- `;
1205
- }
1206
- function renderTightCoderAutoTest() {
1207
- return `
1208
- ${renderedSolidityHeader5}
434
+ `}function hn(){return`
435
+ ${Je}
1209
436
 
1210
437
  import { Test } from "forge-std/Test.sol";
1211
438
  import { EncodeArray } from "../../src/tightcoder/EncodeArray.sol";
1212
439
  import { SliceLib } from "../../src/Slice.sol";
1213
440
 
1214
441
  contract TightCoderAutoTest is Test {
1215
- ${staticAbiTypes3.map((staticAbiType) => renderTightCoderAutoTestFunction({ typeId: staticAbiType })).join("")}
442
+ ${Qe.map(e=>et({typeId:e})).join("")}
1216
443
  }
1217
- `;
1218
- }
1219
- export {
1220
- getSchemaTypeInfo,
1221
- getTableOptions,
1222
- getUserTypeInfo,
1223
- renderDecodeSlice,
1224
- renderDecodeValueType,
1225
- renderDeleteRecordMethods,
1226
- renderEncodeArray,
1227
- renderEncodeFieldSingle,
1228
- renderFieldMethods,
1229
- renderRecordData,
1230
- renderRecordMethods,
1231
- renderTable,
1232
- renderTightCoderAutoTest,
1233
- renderTightCoderAutoTestFunction,
1234
- renderTightCoderDecode,
1235
- renderTightCoderEncode,
1236
- renderTypesFromConfig,
1237
- resolveAbiOrUserType,
1238
- tablegen
1239
- };
444
+ `}export{j as getSchemaTypeInfo,re as getTableOptions,Me as getUserTypeInfo,an as renderDecodeSlice,q as renderDecodeValueType,z as renderDeleteRecordMethods,ln as renderEncodeArray,E as renderEncodeFieldSingle,K as renderFieldMethods,O as renderRecordData,Z as renderRecordMethods,Q as renderTable,hn as renderTightCoderAutoTest,et as renderTightCoderAutoTestFunction,ie as renderTightCoderDecode,ae as renderTightCoderEncode,St as renderTypesFromConfig,U as resolveAbiOrUserType,zt as tablegen};
1240
445
  //# sourceMappingURL=codegen.js.map