This repository has been archived by the owner on May 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
TsMorhProject.ts
337 lines (314 loc) · 11.1 KB
/
TsMorhProject.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import { readdirSync, removeSync } from "fs-extra";
import { HardhatRuntimeEnvironment } from "hardhat/types";
import path from "path";
import {
Project,
ScriptTarget,
ModuleKind,
ModuleResolutionKind,
} from "ts-morph";
import { ReactContext } from "./ReactContext";
import { debug } from "debug";
import { JsxEmit } from "typescript";
const log = debug("hardhat:plugin:react");
const TS_CONFIG = {
target: ScriptTarget.ES2018,
lib: ["dom", "dom.iterable", "esnext"],
allowJs: true,
skipLibCheck: true,
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: true,
forceConsistentCasingInFileNames: true,
module: ModuleKind.CommonJS,
moduleResolution: ModuleResolutionKind.NodeJs,
resolveJsonModule: true,
isolatedModules: true,
noEmit: true,
jsx: JsxEmit.React,
};
export interface ContractContext {
name: string;
typechainInstanceName: string;
typechainFactoryName: string;
deploymentFile?: string;
artifactFile: string;
typechainInstance: string;
typechainFactory: string;
instance: boolean;
contractAddress?: string;
}
export const contractInterfaceName = (contract: ContractContext) => {
return `Symfoni${contract.typechainInstanceName}`;
};
export class TsMorphProject {
private readonly project: Project;
private HARDHAT_CONTEXT_FILE_NAME: string;
private readonly hre: HardhatRuntimeEnvironment;
private readonly args: any;
constructor(args: any, hre: HardhatRuntimeEnvironment) {
this.hre = hre;
this.args = args;
this.HARDHAT_CONTEXT_FILE_NAME = "SymfoniContext.tsx";
this.project = new Project({
compilerOptions: TS_CONFIG, // REVIEW : tsconfig can depend on frontend project
});
this.ensure_hardhat_context_file();
}
async generate() {
const hardhat_context_file = this.project.getSourceFile(
this.HARDHAT_CONTEXT_FILE_NAME
);
if (!hardhat_context_file) {
throw Error(
"After it assured hardhat context file in contruction, it could not resolve hardhat context file in generate."
);
}
const contractContexts = await this.getContractContexts();
const reactContext = new ReactContext(
hardhat_context_file,
this.args,
this.hre,
contractContexts
);
return reactContext.generate();
}
async save() {
// if (true) {
// log("Verbode mode, get ready for Diagnostics");
// const sourceFile = this.project.getSourceFile(
// this.HARDHAT_CONTEXT_FILE_NAME
// );
// if (!sourceFile) throw Error("No Hardhat react context file");
// const emitOutput = sourceFile.getPreEmitDiagnostics();
// log(emitOutput);
// }
this.project.saveSync();
return true;
}
private async getContractContexts() {
let currentNetwork = this.hre.network.name;
// currentNetwork =
// currentNetwork === "hardhat" ? "localhost" : currentNetwork;
log("Mapping deployments from " + currentNetwork + " to React context");
const typechainFactoriesPath = path.resolve(
this.hre.config.typechain.outDir,
"factories"
);
const relativeDeploymentsPath = path.relative(
this.hre.config.paths.react,
path.resolve(this.hre.config.paths.deployments, currentNetwork)
);
const relativeTypechainsInstancePath = path.relative(
this.hre.config.paths.react,
this.hre.config.typechain.outDir
);
const relativeTypechainsFactoriesPath = path.relative(
this.hre.config.paths.react,
typechainFactoriesPath
);
const relativeArtifactsPath = path.relative(
this.hre.config.paths.react,
this.hre.config.paths.artifacts
);
let deploymentFiles: string[] = [];
try {
log(
"Checking deploymentfiles in " +
path.resolve(this.hre.config.paths.deployments, currentNetwork)
);
deploymentFiles = readdirSync(
path.resolve(this.hre.config.paths.deployments, currentNetwork)
);
log("deploymentFiles => ");
log(deploymentFiles);
} catch (error) {
log("No deployment folder or files found.");
}
// TODO : Hardhat maybe rewrite later
// const deploymentFiles = await this.hre.deployments.all();
const artifactFiles = await this.hre.artifacts.getAllFullyQualifiedNames();
log("artifactFiles => ");
log(artifactFiles);
const typechainInstanceFiles = readdirSync(
this.hre.config.typechain.outDir
);
// TODO : Create PR to typechain for optional index file or implciit / explicit generation.
removeSync(path.resolve(this.hre.config.typechain.outDir, "index.ts"));
const typechainFactoriesFiles = readdirSync(typechainFactoriesPath);
log("typechainInstanceFiles => ");
log(typechainInstanceFiles);
log("typechainFactoriesFiles => ");
log(typechainFactoriesFiles);
let contracts: ContractContext[] = [];
await Promise.all(
[...artifactFiles].map(async (fileName) => {
const artifactJson = await this.hre.artifacts.readArtifact(fileName);
// Skip list
if (this.hre.config.react.skip) {
if (
this.hre.config.react.skip.indexOf(artifactJson.contractName) !== -1
) {
log("Skipping " + fileName + " because its in skip list.");
return;
}
}
// Skip list
if (this.hre.config.react.handle) {
if (
this.hre.config.react.handle.indexOf(artifactJson.contractName) ===
-1
) {
log("Skipping " + fileName + " because its NOT in handle list.");
return;
}
}
if (artifactJson.bytecode.length < 3) {
// TODO handle interface contracts
log("Skipping " + fileName + " because we think its a interface.");
return;
}
const deploymentFile = deploymentFiles.find((deploymentFile) => {
return (
path.basename(deploymentFile, ".json") === artifactJson.contractName
);
});
// TODO : Hardhat maybe rewrite later
// const hasDeploymentFile = Object.prototype.hasOwnProperty.call(deploymentFiles, artifactName)
// const deploymentFile = hasDeploymentFile ? deploymentFiles[artifactName] : undefined
const typechainInstanceFile = typechainInstanceFiles.find(
(typechainFile) => {
const hasInstanceFile =
path.basename(typechainFile, ".d.ts") ===
artifactJson.contractName;
return hasInstanceFile;
}
);
const typechainFactoryFile = typechainFactoriesFiles.find(
(typechainFile) => {
const hasFactoryFile =
path.basename(typechainFile, ".ts") ===
artifactJson.contractName + "__factory";
return hasFactoryFile;
}
);
if (!typechainInstanceFile) {
// if we dont a typechain file, we cant create anything. So lets just return
log("No typechain instance for " + artifactJson.contractName);
return;
}
if (!typechainFactoryFile) {
// if we dont a typechain file, we cant create anything. So lets just return
log("No typechain factory for " + artifactJson.contractName);
return;
}
log("Creating context for " + artifactJson.contractName);
contracts.push({
name: artifactJson.contractName,
typechainInstanceName: `${path.basename(
typechainInstanceFile,
".d.ts"
)}`,
typechainFactoryName: `${path.basename(typechainFactoryFile, ".ts")}`,
deploymentFile: deploymentFile
? `${relativeDeploymentsPath}/${deploymentFile}`
: undefined,
artifactFile: `${relativeArtifactsPath}/${artifactJson.sourceName}`,
typechainInstance: `${relativeTypechainsInstancePath}/${typechainInstanceFile}`,
typechainFactory: `${relativeTypechainsFactoriesPath}/${typechainFactoryFile}`,
instance: false,
});
})
);
// Filter out possible duplicates
contracts = contracts.filter((contract, i, arr) => {
const duplicate =
arr.slice(0, i).findIndex((otherContract) => {
return (
contract.typechainInstance === otherContract.typechainInstance ||
contract.typechainFactory === otherContract.typechainFactory
);
}) !== -1;
if (duplicate) {
log(
`Contract ${contract.name} is duplicated. Removing the last instance of it from React context generation`
);
}
return !duplicate;
});
let contractInstances: ContractContext[] = [];
// Handle possible deployment instances
deploymentFiles
.filter(
(deploymentFile) => ![".chainId", "solcInputs"].includes(deploymentFile)
)
.forEach((deploymentFile) => {
const exist = contracts.find((contract) => {
if (!contract.deploymentFile) {
return false;
}
return path.basename(contract.deploymentFile) === deploymentFile;
});
if (!exist) {
log("Deployment " + deploymentFile + " had no contract.");
// try to find the contract which has been used to instantiate the deploymentInstance
const possibleContract = contracts.find((contract) => {
const deploymentFileNormalized = path
.basename(deploymentFile, ".json")
.toLowerCase();
const artifactFileNormalized = path
.basename(contract.artifactFile, ".sol")
.toLowerCase();
return deploymentFileNormalized.includes(artifactFileNormalized);
});
if (possibleContract) {
log(
"Found possible contract " +
possibleContract.name +
" for deploymentFile " +
deploymentFile
);
contractInstances.push({
...possibleContract,
deploymentFile: `${relativeDeploymentsPath}/${deploymentFile}`,
name: path.basename(deploymentFile, ".json"),
instance: true,
});
}
}
});
contracts = [...contractInstances, ...contracts];
contracts = await Promise.all(
contracts.map(async (contract) => {
if (contract.deploymentFile) {
const deploymentFile = await this.hre.deployments.get(contract.name);
console.log(deploymentFile.receipt?.contractAddress);
if (deploymentFile.receipt) {
contract.contractAddress = deploymentFile.receipt.contractAddress;
}
}
return contract;
})
);
log(
contracts.length + " contracts has been set for react context generation"
);
log(contracts.map((c) => c.name).join(","));
return contracts;
}
private ensure_hardhat_context_file() {
const exist = this.project
.getSourceFiles()
.find((file) => file.getBaseName() === this.HARDHAT_CONTEXT_FILE_NAME);
if (!exist) {
const newFile = this.project.createSourceFile(
path.resolve(
this.hre.config.paths.react,
this.HARDHAT_CONTEXT_FILE_NAME
),
undefined,
{ overwrite: true }
);
}
}
}