forked from OpenZeppelin/contracts-wizard
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprint.ts
More file actions
281 lines (245 loc) · 8.05 KB
/
print.ts
File metadata and controls
281 lines (245 loc) · 8.05 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import 'array.prototype.flatmap/auto';
import type { Contract, Component, Argument, Value, Impl, ContractFunction, } from './contract';
import { formatLines, spaceBetween, Lines } from './utils/format-lines';
import { getSelfArg } from './common-options';
import { compatibleContractsSemver } from './utils/version';
export function printContract(contract: Contract): string {
return formatLines(
...spaceBetween(
[
`// SPDX-License-Identifier: ${contract.license}`,
`// Compatible with OpenZeppelin Contracts for Cairo ${compatibleContractsSemver}`,
],
printSuperVariables(contract),
[
`#[starknet::contract]`,
`mod ${contract.name} {`,
spaceBetween(
printImports(contract),
printComponentDeclarations(contract),
printImpls(contract),
printStorage(contract),
printEvents(contract),
printConstructor(contract),
printImplementedTraits(contract),
),
`}`,
],
),
);
}
function withSemicolons(lines: string[]): string[] {
return lines.map(line => line.endsWith(';') ? line : line + ';');
}
function printSuperVariables(contract: Contract) {
return withSemicolons(contract.superVariables.map(v => `const ${v.name}: ${v.type} = ${v.value}`));
}
function printImports(contract: Contract) {
const lines: string[] = [];
getCategorizedImports(contract)
.forEach(category => category.forEach(i => lines.push(`use ${i}`)));
return withSemicolons(lines);
}
function getCategorizedImports(contract: Contract) {
const componentImports = contract.components.flatMap(c => `${c.path}::${c.name}`);
const combined = componentImports.concat(contract.standaloneImports);
const ozTokenImports = [];
const ozImports = [];
const otherImports = [];
const superImports = [];
for (const importStatement of combined) {
if (importStatement.startsWith('openzeppelin::token')) {
ozTokenImports.push(importStatement);
} else if (importStatement.startsWith('openzeppelin')) {
ozImports.push(importStatement);
} else {
otherImports.push(importStatement);
}
}
if (contract.superVariables.length > 0) {
superImports.push(`super::{${contract.superVariables.map(v => v.name).join(', ')}}`);
}
return [ ozTokenImports, ozImports, otherImports, superImports ];
}
function printComponentDeclarations(contract: Contract) {
const lines = [];
for (const component of contract.components) {
lines.push(`component!(path: ${component.name}, storage: ${component.substorage.name}, event: ${component.event.name});`);
}
return lines;
}
function printImpls(contract: Contract) {
const externalImpls = contract.components.flatMap(c => c.impls);
const internalImpls = contract.components.flatMap(c => c.internalImpl ? [c.internalImpl] : []);
return spaceBetween(
externalImpls.flatMap(impl => printImpl(impl)),
internalImpls.flatMap(impl => printImpl(impl, true))
);
}
function printImpl(impl: Impl, internal = false) {
const lines = [];
if (!internal) {
lines.push('#[abi(embed_v0)]');
}
lines.push(`impl ${impl.name} = ${impl.value};`);
return lines;
}
function printStorage(contract: Contract) {
const lines = [];
// storage is required regardless of whether there are components
lines.push('#[storage]');
lines.push('struct Storage {');
const storageLines = [];
for (const component of contract.components) {
storageLines.push(`#[substorage(v0)]`);
storageLines.push(`${component.substorage.name}: ${component.substorage.type},`);
}
lines.push(storageLines);
lines.push('}');
return lines;
}
function printEvents(contract: Contract) {
const lines = [];
if (contract.components.length > 0) {
lines.push('#[event]');
lines.push('#[derive(Drop, starknet::Event)]');
lines.push('enum Event {')
const eventLines = [];
for (const component of contract.components) {
eventLines.push('#[flat]');
eventLines.push(`${component.event.name}: ${component.event.type},`);
}
lines.push(eventLines);
lines.push('}');
}
return lines;
}
function printImplementedTraits(contract: Contract) {
const impls = [];
for (const trait of contract.implementedTraits) {
const implLines = [];
implLines.push(...trait.tags.map(t => `#[${t}]`));
implLines.push(`impl ${trait.name} of ${trait.of} {`);
const fns = trait.functions.map(fn => printFunction(fn));
implLines.push(spaceBetween(...fns));
implLines.push('}');
impls.push(implLines);
}
return spaceBetween(...impls);
}
function printFunction(fn: ContractFunction) {
const head = `fn ${fn.name}`;
const args = fn.args.map(a => printArgument(a));
const codeLines = fn.codeBefore?.concat(fn.code) ?? fn.code;
for (let i = 0; i < codeLines.length; i++) {
const line = codeLines[i];
const shouldEndWithSemicolon = i < codeLines.length - 1 || fn.returns === undefined;
if (line !== undefined) {
if (shouldEndWithSemicolon && !line.endsWith(';')) {
codeLines[i] += ';';
} else if (!shouldEndWithSemicolon && line.endsWith(';')) {
codeLines[i] = line.slice(0, line.length - 1);
}
}
}
return printFunction2(head, args, fn.tag, fn.returns, undefined, codeLines);
}
function printConstructor(contract: Contract): Lines[] {
const hasParentParams = contract.components.some(p => p.initializer !== undefined && p.initializer.params.length > 0);
const hasConstructorCode = contract.constructorCode.length > 0;
if (hasParentParams || hasConstructorCode) {
const parents = contract.components
.filter(hasInitializer)
.flatMap(p => printParentConstructor(p));
const tag = 'constructor';
const head = 'fn constructor';
const args = [ getSelfArg(), ...contract.constructorArgs ];
const body = spaceBetween(
withSemicolons(parents),
withSemicolons(contract.constructorCode),
);
const constructor = printFunction2(
head,
args.map(a => printArgument(a)),
tag,
undefined,
undefined,
body,
);
return constructor;
} else {
return [];
}
}
function hasInitializer(parent: Component) {
return parent.initializer !== undefined && parent.substorage?.name !== undefined;
}
function printParentConstructor({ substorage, initializer }: Component): [] | [string] {
if (initializer === undefined || substorage?.name === undefined) {
return [];
}
const fn = `self.${substorage.name}.initializer`;
return [
fn + '(' + initializer.params.map(printValue).join(', ') + ')',
];
}
export function printValue(value: Value): string {
if (typeof value === 'object') {
if ('lit' in value) {
return value.lit;
} else if ('note' in value) {
return `${printValue(value.value)} /* ${value.note} */`;
} else {
throw Error('Unknown value type');
}
} else if (typeof value === 'number') {
if (Number.isSafeInteger(value)) {
return value.toFixed(0);
} else {
throw new Error(`Number not representable (${value})`);
}
} else {
return `'${value}'`;
}
}
// generic for functions and constructors
// kindedName = 'fn foo'
function printFunction2(kindedName: string, args: string[], tag: string | undefined, returns: string | undefined, returnLine: string | undefined, code: Lines[]): Lines[] {
const fn = [];
if (tag !== undefined) {
fn.push(`#[${tag}]`);
}
let accum = `${kindedName}(`;
if (args.length > 0) {
let formattedArgs = args.join(', ');
if (formattedArgs.length > 80) {
fn.push(accum);
accum = '';
// print each arg in a separate line
fn.push(args.map(arg => `${arg},`));
} else {
accum += `${formattedArgs}`;
}
}
accum += ')';
if (returns === undefined) {
accum += ' {';
} else {
accum += ` -> ${returns} {`;
}
fn.push(accum);
fn.push(code);
if (returnLine !== undefined) {
fn.push([returnLine]);
}
fn.push('}');
return fn;
}
function printArgument(arg: Argument): string {
if (arg.type !== undefined) {
const type = arg.type;
return `${arg.name}: ${type}`;
} else {
return `${arg.name}`;
}
}