-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodegen.mjs
More file actions
220 lines (187 loc) · 6.08 KB
/
codegen.mjs
File metadata and controls
220 lines (187 loc) · 6.08 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
import { readdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import shell from 'shelljs';
import {
arbitrum,
arbitrumSepolia,
base,
baseSepolia,
cannon,
mainnet,
optimism,
optimismSepolia,
sepolia,
} from 'viem/chains';
const supportedMainnets = [arbitrum.id, base.id, mainnet.id, optimism.id];
const supportedTestnets = [
arbitrumSepolia.id,
baseSepolia.id,
cannon.id,
optimismSepolia.id,
sepolia.id,
];
const packageRef = 'cartesi-rollups:2.1.0';
const abiFolder = join(process.cwd(), 'abi');
const outFolder = join(process.cwd(), 'src', 'deployments');
const codegenMetaFileName = '__meta.json';
const v2OutDir = join(
process.cwd(),
'node_modules',
'@cartesi',
'rollups-v2',
'out',
);
const buildContractsOfInterest = (chainId) => [
{
name: 'CartesiApplication',
targetFile: join(v2OutDir, 'Application.sol', 'Application.json'),
},
{
name: 'CartesiApplicationFactory',
targetFile: join(outFolder, chainId, 'ApplicationFactory.json'),
},
{
name: 'InputBoxV2',
targetFile: join(outFolder, chainId, 'InputBox.json'),
},
];
const shouldSkipInspect = async ({ packageRef, targetFolder }) => {
const meta = await readFile(join(targetFolder, codegenMetaFileName), {
encoding: 'utf-8',
})
.then((fileContent) => {
try {
return JSON.parse(fileContent);
} catch (error) {
console.error(error);
}
return null;
})
.catch((_) => {
return null;
});
const isPackageRefMatching = meta?.packageRef === packageRef;
if (isPackageRefMatching)
console.log(`Skipping Cannon inspect for package ${packageRef}`);
return isPackageRefMatching;
};
const generateContractsJSON = async (sourceFolder, targetFolder) => {
const files = await readdir(sourceFolder);
const contracts = {};
for (const file of files) {
if (file === codegenMetaFileName) continue;
const filePath = join(sourceFolder, file);
const [name] = file.split('.');
const content = await readFile(filePath);
contracts[name] = JSON.parse(content);
}
await writeFile(
join(targetFolder, 'contracts.json'),
JSON.stringify({ contracts }, null, ' '),
{ encoding: 'utf-8' },
);
};
const execCannonInspect = async ({ packageRef, chainId, outFolder }) => {
const targetFolder = join(outFolder, chainId);
const shouldSkip = await shouldSkipInspect({ packageRef, targetFolder });
if (shouldSkip) return { ok: true };
const child = shell.exec(
`npm run cannon -- inspect ${packageRef} --chain-id ${chainId} --write-deployments ${targetFolder} --quiet`,
{ async: true },
);
const outputPromise = new Promise((resolve) => {
child.on('exit', (code) => {
resolve({ code });
});
});
const output = await outputPromise;
const isSuccess = output.code === 0;
if (isSuccess) {
await Promise.all([
generateContractsJSON(targetFolder, targetFolder),
writeFile(
join(targetFolder, codegenMetaFileName),
JSON.stringify({
packageRef,
timestamp: Math.floor(Date.now() / 1000),
desc: 'Autogenerated. Do not change it manually.',
}),
{ encoding: 'utf-8' },
),
]);
}
return { ok: isSuccess };
};
const readABIFor = async (list) => {
const contracts = await Promise.all(
list.map((target) => {
return readFile(target.targetFile, {
encoding: 'utf-8',
}).then((content) => {
try {
const config = JSON.parse(content);
return { name: target.name, abi: config.abi };
} catch (error) {
console.error(error.message);
return { name: target.name, abi: [] };
}
});
}),
);
return contracts;
};
async function codegen(chainId) {
const { ok } = await execCannonInspect({
packageRef,
chainId,
outFolder,
});
if (!ok)
return Promise.reject(
`Failed during inspection of ${packageRef} for chain-id: ${chainId}`,
);
return { ok: true, chainId };
}
async function generateABIFiles(chainId) {
const contracts = await readABIFor(
buildContractsOfInterest(chainId.toString()),
);
const result = await Promise.allSettled(
contracts.map((contract) => {
const content = JSON.stringify(contract.abi, null, ' ');
const fileName = join(abiFolder, `${contract.name}.json`);
return writeFile(fileName, content, { encoding: 'utf-8' });
}),
);
result.forEach((data, i) => {
if (data.status === 'fulfilled')
console.info(`${contracts[i].name} created at ${abiFolder}\n`);
else
console.error(
`${contracts[i].name} failed to be created. Reason: ${data.reason}`,
);
});
}
async function run() {
const networks = [...supportedMainnets, ...supportedTestnets];
const codegenPromises = networks.map((chainId) => {
console.log(`Codegen for chain-id: ${chainId.toString()}`);
return codegen(chainId.toString());
});
const codegenResult = await Promise.allSettled(codegenPromises);
const index = codegenResult.findIndex(
(data) => data.status === 'fulfilled',
);
if (index >= 0) await generateABIFiles(networks[index]);
codegenResult.forEach((data, i) => {
if (data.status === 'fulfilled')
console.info(
`Rollups contracts for chain-id ${networks[i].toString()} generated at ${outFolder}`,
);
else
console.error(
`Rollups contracts for chain-id ${networks[i].toString()} failed to be created. Reason: ${data.reason}`,
);
});
}
run();