-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathhardhat.py
executable file
·316 lines (252 loc) · 11.4 KB
/
hardhat.py
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
"""
Hardhat platform
"""
import json
import logging
import os
import shutil
import subprocess
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from crytic_compile.compiler.compiler import CompilerVersion
from crytic_compile.platform.exceptions import InvalidCompilation
from crytic_compile.platform.types import Type
from crytic_compile.utils.naming import convert_filename, extract_name
from crytic_compile.utils.natspec import Natspec
from crytic_compile.utils.subprocess import run
from crytic_compile.platform.abstract_platform import AbstractPlatform
# Handle cycle
from crytic_compile.platform.solc import relative_to_short
from crytic_compile.compilation_unit import CompilationUnit
if TYPE_CHECKING:
from crytic_compile import CryticCompile
LOGGER = logging.getLogger("CryticCompile")
class Hardhat(AbstractPlatform):
"""
Hardhat platform
"""
NAME = "Hardhat"
PROJECT_URL = "https://github.com/nomiclabs/hardhat"
TYPE = Type.HARDHAT
# pylint: disable=too-many-locals,too-many-statements
def compile(self, crytic_compile: "CryticCompile", **kwargs: str) -> None:
"""Run the compilation
Args:
crytic_compile (CryticCompile): Associated CryticCompile object
**kwargs: optional arguments. Used: "hardhat_ignore", "hardhat_ignore_compile", "ignore_compile",
"hardhat_artifacts_directory","hardhat_working_dir","npx_disable"
Raises:
InvalidCompilation: If hardhat failed to run
"""
hardhat_ignore_compile, base_cmd = self._settings(kwargs)
detected_paths = self._get_hardhat_paths(base_cmd, kwargs)
build_directory = Path(
self._target,
detected_paths["artifacts"],
"build-info",
)
hardhat_working_dir = Path(self._target, detected_paths["root"])
if not hardhat_ignore_compile:
cmd = base_cmd + ["compile", "--force"]
LOGGER.info(
"'%s' running",
" ".join(cmd),
)
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self._target,
executable=shutil.which(cmd[0]),
) as process:
stdout_bytes, stderr_bytes = process.communicate()
stdout, stderr = (
stdout_bytes.decode(errors="backslashreplace"),
stderr_bytes.decode(errors="backslashreplace"),
) # convert bytestrings to unicode strings
LOGGER.info(stdout)
if stderr:
LOGGER.error(stderr)
files = sorted(
os.listdir(build_directory), key=lambda x: os.path.getmtime(Path(build_directory, x))
)
files = [f for f in files if f.endswith(".json")]
if not files:
txt = f"`hardhat compile` failed. Can you run it?\n{build_directory} is empty"
raise InvalidCompilation(txt)
for file in files:
build_info = Path(build_directory, file)
# The file here should always ends .json, but just in case use ife
uniq_id = file if ".json" not in file else file[0:-5]
compilation_unit = CompilationUnit(crytic_compile, uniq_id)
with open(build_info, encoding="utf8") as file_desc:
loaded_json = json.load(file_desc)
targets_json = loaded_json["output"]
version_from_config = loaded_json["solcVersion"] # TODO supper vyper
input_json = loaded_json["input"]
compiler = "solc" if input_json["language"] == "Solidity" else "vyper"
optimized = input_json["settings"]["optimizer"]["enabled"]
compilation_unit.compiler_version = CompilerVersion(
compiler=compiler, version=version_from_config, optimized=optimized
)
skip_filename = compilation_unit.compiler_version.version in [
f"0.4.{x}" for x in range(0, 10)
]
if "contracts" in targets_json:
for original_filename, contracts_info in targets_json["contracts"].items():
filename = convert_filename(
original_filename,
relative_to_short,
crytic_compile,
working_dir=hardhat_working_dir,
)
source_unit = compilation_unit.create_source_unit(filename)
for original_contract_name, info in contracts_info.items():
contract_name = extract_name(original_contract_name)
source_unit.contracts_names.add(contract_name)
compilation_unit.filename_to_contracts[filename].add(contract_name)
source_unit.abis[contract_name] = info["abi"]
source_unit.bytecodes_init[contract_name] = info["evm"]["bytecode"][
"object"
]
source_unit.bytecodes_runtime[contract_name] = info["evm"][
"deployedBytecode"
]["object"]
source_unit.srcmaps_init[contract_name] = info["evm"]["bytecode"][
"sourceMap"
].split(";")
source_unit.srcmaps_runtime[contract_name] = info["evm"][
"deployedBytecode"
]["sourceMap"].split(";")
userdoc = info.get("userdoc", {})
devdoc = info.get("devdoc", {})
natspec = Natspec(userdoc, devdoc)
source_unit.natspec[contract_name] = natspec
if "sources" in targets_json:
for path, info in targets_json["sources"].items():
if skip_filename:
path = convert_filename(
self._target,
relative_to_short,
crytic_compile,
working_dir=hardhat_working_dir,
)
else:
path = convert_filename(
path,
relative_to_short,
crytic_compile,
working_dir=hardhat_working_dir,
)
source_unit = compilation_unit.create_source_unit(path)
source_unit.ast = info["ast"]
def clean(self, **kwargs: str) -> None:
"""Clean compilation artifacts
Args:
**kwargs: optional arguments.
"""
hardhat_ignore_compile, base_cmd = self._settings(kwargs)
if hardhat_ignore_compile:
return
for clean_cmd in [["clean"], ["clean", "--global"]]:
run(base_cmd + clean_cmd, cwd=self._target)
@staticmethod
def is_supported(target: str, **kwargs: str) -> bool:
"""Check if the target is an hardhat project
Args:
target (str): path to the target
**kwargs: optional arguments. Used: "hardhat_ignore"
Returns:
bool: True if the target is an hardhat project
"""
hardhat_ignore = kwargs.get("hardhat_ignore", False)
if hardhat_ignore:
return False
return os.path.isfile(os.path.join(target, "hardhat.config.js")) | os.path.isfile(
os.path.join(target, "hardhat.config.ts")
)
def is_dependency(self, path: str) -> bool:
"""Check if the path is a dependency
Args:
path (str): path to the target
Returns:
bool: True if the target is a dependency
"""
if path in self._cached_dependencies:
return self._cached_dependencies[path]
ret = "node_modules" in Path(path).parts
self._cached_dependencies[path] = ret
return ret
def _guessed_tests(self) -> List[str]:
"""Guess the potential unit tests commands
Returns:
List[str]: The guessed unit tests commands
"""
return ["hardhat test"]
@staticmethod
def _settings(args: Dict[str, Any]) -> Tuple[bool, List[str]]:
hardhat_ignore_compile = args.get("hardhat_ignore_compile", False) or args.get(
"ignore_compile", False
)
base_cmd = ["hardhat"]
return hardhat_ignore_compile, base_cmd
def _get_hardhat_paths(
self, base_cmd: List[str], args: Dict[str, str]
) -> Dict[str, Union[Path, str]]:
"""Obtain hardhat configuration paths, defaulting to the
standard config if needed.
Args:
base_cmd ([str]): hardhat command
args (Dict[str, str]): crytic-compile options that may affect paths
Returns:
Dict[str, str]: hardhat paths configuration
"""
target_path = Path(self._target)
default_paths = {
"root": target_path,
"configFile": target_path.joinpath("hardhat.config.js"),
"sources": target_path.joinpath("contracts"),
"cache": target_path.joinpath("cache"),
"artifacts": target_path.joinpath("artifacts"),
"tests": target_path.joinpath("test"),
}
override_paths = {}
if args.get("hardhat_cache_directory", None):
override_paths["cache"] = Path(target_path, args["hardhat_cache_directory"])
if args.get("hardhat_artifacts_directory", None):
override_paths["artifacts"] = Path(target_path, args["hardhat_artifacts_directory"])
if args.get("hardhat_working_dir", None):
override_paths["root"] = Path(target_path, args["hardhat_working_dir"])
print_paths = "console.log(JSON.stringify(config.paths))"
config_str = self._run_hardhat_console(base_cmd, print_paths)
try:
paths = json.loads(config_str or "{}")
return {**default_paths, **paths, **override_paths}
except ValueError as e:
LOGGER.info("Problem deserializing hardhat configuration: %s", e)
return {**default_paths, **override_paths}
def _run_hardhat_console(self, base_cmd: List[str], command: str) -> Optional[str]:
"""Run a JS command in the hardhat console
Args:
base_cmd ([str]): hardhat command
command (str): console command to run
Returns:
Optional[str]: command output if execution succeeds
"""
with subprocess.Popen(
base_cmd + ["console", "--no-compile"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self._target,
executable=shutil.which(base_cmd[0]),
) as process:
stdout_bytes, stderr_bytes = process.communicate(command.encode("utf-8"))
stdout, stderr = (
stdout_bytes.decode(),
stderr_bytes.decode(errors="backslashreplace"),
)
if stderr:
LOGGER.info("Problem executing hardhat: %s", stderr)
return None
return stdout