This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathindex.js
407 lines (335 loc) · 13.6 KB
/
index.js
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
const OS = require("os");
const path = require("path");
const Profiler = require("./profiler");
const CompileError = require("./compileerror");
const CompilerSupplier = require("./compilerSupplier");
const expect = require("truffle-expect");
const find_contracts = require("truffle-contract-sources");
const Config = require("truffle-config");
const semver = require("semver");
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars
// Most basic of the compile commands. Takes a hash of sources, where
// the keys are file or module paths and the values are the bodies of
// the contracts. Does not evaulate dependencies that aren't already given.
//
// Default options:
// {
// strict: false,
// quiet: false,
// logger: console
// }
const compile = function(sources, options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
if (options.logger === undefined) options.logger = console;
const hasTargets =
options.compilationTargets && options.compilationTargets.length;
expect.options(options, ["contracts_directory", "compilers"]);
expect.options(options.compilers, ["solc"]);
options.compilers.solc.settings.evmVersion =
options.compilers.solc.settings.evmVersion ||
options.compilers.solc.evmVersion;
options.compilers.solc.settings.optimizer =
options.compilers.solc.settings.optimizer ||
options.compilers.solc.optimizer ||
{};
// Grandfather in old solc config
if (options.solc) {
options.compilers.solc.settings.evmVersion = options.solc.evmVersion;
options.compilers.solc.settings.optimizer = options.solc.optimizer;
}
// Ensure sources have operating system independent paths
// i.e., convert backslashes to forward slashes; things like C: are left intact.
const operatingSystemIndependentSources = {};
const operatingSystemIndependentTargets = {};
const originalPathMappings = {};
Object.keys(sources).forEach(function(source) {
// Turn all backslashes into forward slashes
var replacement = source.replace(/\\/g, "/");
// Turn G:/.../ into /G/.../ for Windows
if (replacement.length >= 2 && replacement[1] === ":") {
replacement = "/" + replacement;
replacement = replacement.replace(":", "");
}
// Save the result
operatingSystemIndependentSources[replacement] = sources[source];
// Just substitute replacement for original in target case. It's
// a disposable subset of `sources`
if (hasTargets && options.compilationTargets.includes(source)) {
operatingSystemIndependentTargets[replacement] = sources[source];
}
// Map the replacement back to the original source path.
originalPathMappings[replacement] = source;
});
const defaultSelectors = {
"": ["legacyAST", "ast"],
"*": [
"abi",
"metadata",
"evm.bytecode.object",
"evm.bytecode.sourceMap",
"evm.deployedBytecode.object",
"evm.deployedBytecode.sourceMap",
"userdoc",
"devdoc"
]
};
// Specify compilation targets
// Each target uses defaultSelectors, defaulting to single target `*` if targets are unspecified
const outputSelection = {};
const targets = operatingSystemIndependentTargets;
const targetPaths = Object.keys(targets);
targetPaths.length
? targetPaths.forEach(key => (outputSelection[key] = defaultSelectors))
: (outputSelection["*"] = defaultSelectors);
const solcStandardInput = {
language: "Solidity",
sources: {},
settings: {
evmVersion: options.compilers.solc.settings.evmVersion,
optimizer: options.compilers.solc.settings.optimizer,
outputSelection
}
};
// Nothing to compile? Bail.
if (Object.keys(sources).length === 0) {
return callback(null, [], []);
}
Object.keys(operatingSystemIndependentSources).forEach(file_path => {
solcStandardInput.sources[file_path] = {
content: operatingSystemIndependentSources[file_path]
};
});
// Load solc module only when compilation is actually required.
const supplier = new CompilerSupplier(options.compilers.solc);
supplier
.load()
.then(solc => {
const result = solc.compile(JSON.stringify(solcStandardInput));
const standardOutput = JSON.parse(result);
let errors = standardOutput.errors || [];
let warnings = [];
if (options.strict !== true) {
warnings = errors.filter(error => error.severity === "warning");
errors = errors.filter(error => error.severity !== "warning");
if (options.quiet !== true && warnings.length > 0) {
options.logger.log(
OS.EOL + " > compilation warnings encountered:" + OS.EOL
);
options.logger.log(
warnings.map(warning => warning.formattedMessage).join()
);
}
}
if (errors.length > 0) {
options.logger.log("");
errors = errors.map(error => error.formattedMessage).join();
if (errors.includes("requires different compiler version")) {
const contractSolcVer = errors.match(/pragma solidity[^;]*/gm)[0];
const configSolcVer =
options.compilers.solc.version || semver.valid(solc.version());
errors = errors.concat(
`\nError: Truffle is currently using solc ${configSolcVer}, but one or more of your contracts specify "${contractSolcVer}".\nPlease update your truffle config or pragma statement(s).\n(See https://truffleframework.com/docs/truffle/reference/configuration#compiler-configuration for information on\nconfiguring Truffle to use a specific solc compiler version.)`
);
}
return callback(new CompileError(errors));
}
var contracts = standardOutput.contracts;
var files = [];
Object.keys(standardOutput.sources).forEach(filename => {
var source = standardOutput.sources[filename];
files[source.id] = originalPathMappings[filename];
});
var returnVal = {};
// This block has comments in it as it's being prepared for solc > 0.4.10
Object.keys(contracts).forEach(source_path => {
var files_contracts = contracts[source_path];
Object.keys(files_contracts).forEach(contract_name => {
var contract = files_contracts[contract_name];
// All source will have a key, but only the compiled source will have
// the evm output.
if (!Object.keys(contract.evm).length) return;
var contract_definition = {
contract_name: contract_name,
sourcePath: originalPathMappings[source_path], // Save original source path, not modified ones
source: operatingSystemIndependentSources[source_path],
sourceMap: contract.evm.bytecode.sourceMap,
deployedSourceMap: contract.evm.deployedBytecode.sourceMap,
legacyAST: standardOutput.sources[source_path].legacyAST,
ast: standardOutput.sources[source_path].ast,
abi: contract.abi,
metadata: contract.metadata,
bytecode: "0x" + contract.evm.bytecode.object,
deployedBytecode: "0x" + contract.evm.deployedBytecode.object,
unlinked_binary: "0x" + contract.evm.bytecode.object, // deprecated
compiler: {
name: "solc",
version: solc.version()
},
devdoc: contract.devdoc,
userdoc: contract.userdoc
};
// Reorder ABI so functions are listed in the order they appear
// in the source file. Solidity tests need to execute in their expected sequence.
contract_definition.abi = orderABI(contract_definition);
// Go through the link references and replace them with older-style
// identifiers. We'll do this until we're ready to making a breaking
// change to this code.
Object.keys(contract.evm.bytecode.linkReferences).forEach(function(
file_name
) {
var fileLinks = contract.evm.bytecode.linkReferences[file_name];
Object.keys(fileLinks).forEach(function(library_name) {
var linkReferences = fileLinks[library_name] || [];
contract_definition.bytecode = replaceLinkReferences(
contract_definition.bytecode,
linkReferences,
library_name
);
contract_definition.unlinked_binary = replaceLinkReferences(
contract_definition.unlinked_binary,
linkReferences,
library_name
);
});
});
// Now for the deployed bytecode
Object.keys(contract.evm.deployedBytecode.linkReferences).forEach(
function(file_name) {
var fileLinks =
contract.evm.deployedBytecode.linkReferences[file_name];
Object.keys(fileLinks).forEach(function(library_name) {
var linkReferences = fileLinks[library_name] || [];
contract_definition.deployedBytecode = replaceLinkReferences(
contract_definition.deployedBytecode,
linkReferences,
library_name
);
});
}
);
returnVal[contract_name] = contract_definition;
});
});
const compilerInfo = { name: "solc", version: solc.version() };
callback(null, returnVal, files, compilerInfo);
})
.catch(callback);
};
function replaceLinkReferences(bytecode, linkReferences, libraryName) {
var linkId = "__" + libraryName;
while (linkId.length < 40) {
linkId += "_";
}
linkReferences.forEach(function(ref) {
// ref.start is a byte offset. Convert it to character offset.
var start = ref.start * 2 + 2;
bytecode =
bytecode.substring(0, start) + linkId + bytecode.substring(start + 40);
});
return bytecode;
}
function orderABI({ abi, contract_name: contractName, ast }) {
// AST can have multiple contract definitions, make sure we have the
// one that matches our contract
const contractDefinition = ast.nodes.find(
({ nodeType, name }) =>
nodeType === "ContractDefinition" && name === contractName
);
if (!contractDefinition || !contractDefinition.nodes) {
return abi;
}
// Find all function definitions
const orderedFunctionNames = contractDefinition.nodes
.filter(({ nodeType }) => nodeType === "FunctionDefinition")
.map(({ name: functionName }) => functionName);
// Put function names in a hash with their order, lowest first, for speed.
const functionIndexes = orderedFunctionNames
.map((functionName, index) => ({ [functionName]: index }))
.reduce((a, b) => Object.assign({}, a, b), {});
// Construct new ABI with functions at the end in source order
return [
...abi.filter(({ name }) => functionIndexes[name] === undefined),
// followed by the functions in the source order
...abi
.filter(({ name }) => functionIndexes[name] !== undefined)
.sort(
({ name: a }, { name: b }) => functionIndexes[a] - functionIndexes[b]
)
];
}
// contracts_directory: String. Directory where .sol files can be found.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.all = function(options, callback) {
find_contracts(options.contracts_directory, function(err, files) {
if (err) return callback(err);
options.paths = files;
compile.with_dependencies(options, callback);
});
};
// contracts_directory: String. Directory where .sol files can be found.
// build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false.
// all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files
// in the build directory to see what needs to be compiled.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.necessary = function(options, callback) {
options.logger = options.logger || console;
Profiler.updated(options, function(err, updated) {
if (err) return callback(err);
if (updated.length === 0 && options.quiet !== true) {
return callback(null, [], {});
}
options.paths = updated;
compile.with_dependencies(options, callback);
});
};
compile.with_dependencies = function(options, callback) {
var self = this;
options.logger = options.logger || console;
options.contracts_directory = options.contracts_directory || process.cwd();
expect.options(options, [
"paths",
"working_directory",
"contracts_directory",
"resolver"
]);
var config = Config.default().merge(options);
Profiler.required_sources(
config.with({
paths: options.paths,
base_path: options.contracts_directory,
resolver: options.resolver
}),
(err, allSources, required) => {
if (err) return callback(err);
var hasTargets = required.length;
hasTargets
? self.display(required, options)
: self.display(allSources, options);
options.compilationTargets = required;
compile(allSources, options, callback);
}
);
};
compile.display = function(paths, options) {
if (options.quiet !== true) {
if (!Array.isArray(paths)) {
paths = Object.keys(paths);
}
const blacklistRegex = /^truffle\//;
paths.sort().forEach(contract => {
if (path.isAbsolute(contract)) {
contract =
"." + path.sep + path.relative(options.working_directory, contract);
}
if (contract.match(blacklistRegex)) return;
options.logger.log("> Compiling " + contract);
});
}
};
compile.CompilerSupplier = CompilerSupplier;
module.exports = compile;