/
common.ts
232 lines (207 loc) · 7.11 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import path from "path";
import {
AbsoluteImportDatum,
RelativeImportDatum,
ImportDatum,
StaticResourceData,
RenderKeyTuple,
RenderType,
} from "./types";
import { posixPath } from "../utils";
export const renderedSolidityHeader = `// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21;
/* Autogenerated file. Do not edit manually. */`;
/**
* Renders a list of lines
*/
export function renderList<T>(list: T[], renderItem: (item: T, index: number) => string): string {
return internalRenderList("", list, renderItem);
}
/**
* Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones
*/
export function renderArguments(args: (string | undefined)[]): string {
const filteredArgs = args.filter((arg) => arg !== undefined && arg !== "") as string[];
return internalRenderList(",", filteredArgs, (arg) => arg);
}
export function renderCommonData({
staticResourceData,
keyTuple,
}: {
staticResourceData?: StaticResourceData;
keyTuple: RenderKeyTuple[];
}): {
_tableId: string;
_typedTableId: string;
_keyArgs: string;
_typedKeyArgs: string;
_keyTupleDefinition: string;
} {
// static resource means static tableId as well, and no tableId arguments
const _tableId = staticResourceData ? "" : "_tableId";
const _typedTableId = staticResourceData ? "" : "ResourceId _tableId";
const _keyArgs = renderArguments(keyTuple.map(({ name }) => name));
const _typedKeyArgs = renderArguments(keyTuple.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));
const _keyTupleDefinition = `
bytes32[] memory _keyTuple = new bytes32[](${keyTuple.length});
${renderList(keyTuple, (key, index) => `_keyTuple[${index}] = ${renderValueTypeToBytes32(key.name, key)};`)}
`;
return {
_tableId,
_typedTableId,
_keyArgs,
_typedKeyArgs,
_keyTupleDefinition,
};
}
/** For 2 paths which are relative to a common root, create a relative import path from one to another */
export function solidityRelativeImportPath(fromPath: string, usedInPath: string): string {
// 1st "./" must be added because path strips it,
// but solidity expects it unless there's "../" ("./../" is fine).
// 2nd and 3rd "./" forcefully avoid absolute paths (everything is relative to `src`).
return posixPath("./" + path.relative("./" + usedInPath, "./" + fromPath));
}
/**
* Aggregates, deduplicates and renders imports for symbols per path.
* Identical symbols from different paths are NOT handled, they should be checked before rendering.
*/
export function renderImports(imports: ImportDatum[]): string {
return renderAbsoluteImports(
imports.map((importDatum) => {
if ("path" in importDatum) {
return importDatum;
} else {
return {
symbol: importDatum.symbol,
path: solidityRelativeImportPath(importDatum.fromPath, importDatum.usedInPath),
};
}
})
);
}
/**
* Aggregates, deduplicates and renders imports for symbols per path.
* Identical symbols from different paths are NOT handled, they should be checked before rendering.
*/
export function renderRelativeImports(imports: RelativeImportDatum[]): string {
return renderAbsoluteImports(
imports.map(({ symbol, fromPath, usedInPath }) => ({
symbol,
path: solidityRelativeImportPath(fromPath, usedInPath),
}))
);
}
/**
* Aggregates, deduplicates and renders imports for symbols per path.
* Identical symbols from different paths are NOT handled, they should be checked before rendering.
*/
export function renderAbsoluteImports(imports: AbsoluteImportDatum[]): string {
// Aggregate symbols by import path, also deduplicating them
const aggregatedImports = new Map<string, Set<string>>();
for (const { symbol, path } of imports) {
if (!aggregatedImports.has(path)) {
aggregatedImports.set(path, new Set());
}
aggregatedImports.get(path)?.add(symbol);
}
// Render imports
const renderedImports = [];
for (const [path, symbols] of aggregatedImports) {
const renderedSymbols = [...symbols].join(", ");
renderedImports.push(`import { ${renderedSymbols} } from "${posixPath(path)}";`);
}
return renderedImports.join("\n");
}
export function renderWithStore(
storeArgument: boolean,
callback: (
_typedStore: string | undefined,
_store: string,
_commentSuffix: string,
_untypedStore: string | undefined,
_methodPrefix: string,
_internal?: boolean
) => string
): string {
let result = "";
result += callback(undefined, "StoreSwitch", "", undefined, "");
result += callback(undefined, "StoreCore", "", undefined, "_", true);
if (storeArgument) {
result += "\n" + callback("IStore _store", "_store", " (using the specified store)", "_store", "");
}
return result;
}
export function renderWithFieldSuffix(
withSuffixlessFieldMethods: boolean,
fieldName: string,
callback: (_methodNameSuffix: string) => string
): string {
const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`;
let result = "";
result += callback(methodNameSuffix);
if (withSuffixlessFieldMethods) {
result += "\n" + callback("");
}
return result;
}
export function renderTableId({ namespace, name, offchainOnly, tableIdName }: StaticResourceData): {
hardcodedTableId: string;
tableIdDefinition: string;
} {
const hardcodedTableId = `
ResourceId.wrap(
bytes32(
abi.encodePacked(
${offchainOnly ? "RESOURCE_OFFCHAIN_TABLE" : "RESOURCE_TABLE"},
bytes14("${namespace}"),
bytes16("${name}")
)
)
)
`;
const tableIdDefinition = `
ResourceId constant _tableId = ${hardcodedTableId};
ResourceId constant ${tableIdName} = _tableId;
`;
return {
hardcodedTableId,
tableIdDefinition,
};
}
export function renderValueTypeToBytes32(name: string, { typeUnwrap, internalTypeId }: RenderType): string {
const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name;
if (internalTypeId === "bytes32") {
return innerText;
} else if (internalTypeId.match(/^bytes\d{1,2}$/)) {
return `bytes32(${innerText})`;
} else if (internalTypeId.match(/^uint\d{1,3}$/)) {
return `bytes32(uint256(${innerText}))`;
} else if (internalTypeId.match(/^int\d{1,3}$/)) {
return `bytes32(uint256(int256(${innerText})))`;
} else if (internalTypeId === "address") {
return `bytes32(uint256(uint160(${innerText})))`;
} else if (internalTypeId === "bool") {
return `_boolToBytes32(${innerText})`;
} else {
throw new Error(`Unknown value type id ${internalTypeId}`);
}
}
export function isLeftAligned(field: Pick<RenderType, "internalTypeId">): boolean {
return field.internalTypeId.match(/^bytes\d{1,2}$/) !== null;
}
export function getLeftPaddingBits(field: Pick<RenderType, "internalTypeId" | "staticByteLength">): number {
if (isLeftAligned(field)) {
return 0;
} else {
return 256 - field.staticByteLength * 8;
}
}
function internalRenderList<T>(
lineTerminator: string,
list: T[],
renderItem: (item: T, index: number) => string
): string {
return list
.map((item, index) => renderItem(item, index) + (index === list.length - 1 ? "" : lineTerminator))
.join("\n");
}