UNPKG

truffle

Version:

Truffle - Simple development framework for Ethereum

1,214 lines (1,150 loc) 141 kB
#!/usr/bin/env node exports.id = 4273; exports.ids = [4273]; exports.modules = { /***/ 18957: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emptyWorkflowCompileResult = exports.promoteCompileResult = void 0; function promoteCompileResult(result) { const { compilations } = result; const contracts = compilations.flatMap(compilation => compilation.contracts); return { compilations, contracts }; } exports.promoteCompileResult = promoteCompileResult; function emptyWorkflowCompileResult() { return { compilations: [], contracts: [] }; } exports.emptyWorkflowCompileResult = emptyWorkflowCompileResult; //# sourceMappingURL=compilations.js.map /***/ }), /***/ 62575: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompileError = void 0; const colors_1 = __importDefault(__webpack_require__(83196)); const error_1 = __importDefault(__webpack_require__(73321)); class CompileError extends error_1.default { constructor(message) { // Note we trim() because solc likes to add extra whitespace. var fancy_message = message.trim() + "\n\n" + colors_1.default.red("Compilation failed. See above."); var normal_message = message.trim(); super(normal_message); this.message = fancy_message; //?? I don't understand this, I just found it here } } exports.CompileError = CompileError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 29833: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Compilations = exports.Errors = exports.Sources = exports.Shims = void 0; exports.Shims = __importStar(__webpack_require__(53304)); exports.Sources = __importStar(__webpack_require__(2543)); exports.Errors = __importStar(__webpack_require__(62575)); exports.Compilations = __importStar(__webpack_require__(18957)); __exportStar(__webpack_require__(40963), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 99164: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.forBytecode = exports.forContract = exports.forContracts = void 0; function forContracts(contracts) { // convert to list return Object.values(contracts).map(forContract); } exports.forContracts = forContracts; function forContract(contract) { const { contractName, contract_name, sourcePath, source, sourceMap, deployedSourceMap, legacyAST, ast, abi, metadata, bytecode, deployedBytecode, compiler, devdoc, userdoc, immutableReferences, generatedSources, deployedGeneratedSources, db } = contract; return { contractName: contract_name || contractName, sourcePath, source, sourceMap, deployedSourceMap, legacyAST, ast, abi, metadata, bytecode: bytecode ? forBytecode(bytecode) : undefined, deployedBytecode: deployedBytecode ? forBytecode(deployedBytecode) : undefined, compiler, devdoc, userdoc, immutableReferences, generatedSources, deployedGeneratedSources, db }; } exports.forContract = forContract; function forBytecode(bytecode) { if (typeof bytecode === "object") { return bytecode; } const linkReferences = []; const bytes = bytecode .slice(2) // remove 0x prefix .replace(/__[^_]+_*/g, (linkReference, characterOffset) => { const match = linkReference.match(/__([^_]+)_*/); if (match === null) { //this can't actually happen, but strictNullChecks requires it throw new Error("Could not extract link reference name"); } const name = match[1]; const characterLength = linkReference.length; const offset = characterOffset / 2; const length = characterLength / 2; linkReferences.push({ offsets: [offset], name, length }); return "0".repeat(characterLength); }); return { bytes, linkReferences }; } exports.forBytecode = forBytecode; //# sourceMappingURL=LegacyToNew.js.map /***/ }), /***/ 26624: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.forBytecode = exports.forContract = void 0; function forContract(contract) { const { contractName, sourcePath, source, sourceMap, deployedSourceMap, legacyAST, ast, abi, metadata, bytecode, deployedBytecode, compiler, devdoc, userdoc, immutableReferences, generatedSources, deployedGeneratedSources, db } = contract; return { contract_name: contractName, sourcePath, source, sourceMap, deployedSourceMap, legacyAST, ast, abi, metadata, bytecode: forBytecode(bytecode), deployedBytecode: forBytecode(deployedBytecode), unlinked_binary: forBytecode(bytecode), compiler, devdoc, userdoc, immutableReferences, generatedSources, deployedGeneratedSources, db }; } exports.forContract = forContract; function forBytecode(bytecode) { if (!bytecode) { return bytecode; } if (typeof bytecode === "string") { return bytecode; } let { bytes, linkReferences } = bytecode; linkReferences = linkReferences || []; // inline link references - start by flattening the offsets const flattenedLinkReferences = linkReferences // map each link ref to array of link refs with only one offset .map(({ offsets, length, name }) => offsets.map(offset => ({ offset, length, name }))) // flatten .reduce((a, b) => [...a, ...b], []); // then overwite bytes with link reference bytes = flattenedLinkReferences.reduce((bytes, { offset, name, length }) => { // length is a byte offset const characterLength = length * 2; let linkId = `__${name.slice(0, characterLength - 2)}`; while (linkId.length < characterLength) { linkId += "_"; } const start = offset * 2; return `${bytes.substring(0, start)}${linkId}${bytes.substring(start + characterLength)}`; }, bytes); return `0x${bytes}`; } exports.forBytecode = forBytecode; //# sourceMappingURL=NewToLegacy.js.map /***/ }), /***/ 53304: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NewToLegacy = exports.LegacyToNew = void 0; exports.LegacyToNew = __importStar(__webpack_require__(99164)); exports.NewToLegacy = __importStar(__webpack_require__(26624)); //# sourceMappingURL=index.js.map /***/ }), /***/ 2543: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.collectSources = void 0; const path = __importStar(__webpack_require__(71017)); /** * Collects sources, targets into collections with OS-independent paths, * along with a reverse mapping to the original path (for post-processing) * * @param originalSources - { [originalSourcePath]: contents } * @param originalTargets - originalSourcePath[] * @param baseDirectory - a directory to remove as a prefix * @param replacement - what to replace it with * @return { sources, targets, originalSourcePaths } */ function collectSources(originalSources, originalTargets = [], baseDirectory = "", replacement = "/") { const mappedResults = Object.entries(originalSources) .filter(([originalSourcePath, _]) => !path.isAbsolute(originalSourcePath) || originalSourcePath.startsWith(baseDirectory)) .map(([originalSourcePath, contents]) => ({ originalSourcePath, contents, sourcePath: getPortableSourcePath(replaceRootDirectory(originalSourcePath, baseDirectory, replacement)) })) .map(({ originalSourcePath, sourcePath, contents }) => ({ sources: { [sourcePath]: contents }, // include transformed form as target if original is a target targets: originalTargets.includes(originalSourcePath) ? [sourcePath] : [], originalSourcePaths: { [sourcePath]: originalSourcePath } })); const defaultAccumulator = { sources: {}, targets: [], originalSourcePaths: {} }; return mappedResults.reduce((accumulator, result) => ({ sources: Object.assign({}, accumulator.sources, result.sources), targets: [...accumulator.targets, ...result.targets], originalSourcePaths: Object.assign({}, accumulator.originalSourcePaths, result.originalSourcePaths) }), defaultAccumulator); } exports.collectSources = collectSources; /** * @param sourcePath - string * @return string - operating system independent path * @private */ function getPortableSourcePath(sourcePath) { let replacement = sourcePath; //on Windows, replace backslashes with forward slashes if (path.sep === "\\") { replacement = sourcePath.replace(/\\/g, "/"); } // Turn G:/.../ into /G/.../ for Windows if (replacement.length >= 2 && replacement[1] === ":") { replacement = "/" + replacement; replacement = replacement.replace(":", ""); } return replacement; } function replaceRootDirectory(sourcePath, rootDirectory, replacement) { //make sure root directory ends in a separator if (!rootDirectory.endsWith(path.sep)) { rootDirectory = rootDirectory + path.sep; } return sourcePath.startsWith(rootDirectory) ? replacement + sourcePath.slice(rootDirectory.length) //remove prefix : sourcePath; } //# sourceMappingURL=sources.js.map /***/ }), /***/ 40963: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=types.js.map /***/ }), /***/ 63505: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compileWithPragmaAnalysis = void 0; const compilerSupplier_1 = __webpack_require__(47922); const config_1 = __importDefault(__webpack_require__(20553)); const semver_1 = __importDefault(__webpack_require__(81249)); const profiler_1 = __webpack_require__(22860); const run_1 = __webpack_require__(71193); const reportSources_1 = __webpack_require__(77897); const os_1 = __importDefault(__webpack_require__(22037)); const cloneDeep_1 = __importDefault(__webpack_require__(50361)); const getSemverExpression = source => { const result = source.match(/pragma solidity(.*);/); return result && result[1] ? result[1].trim() : undefined; }; const getSemverExpressions = sources => { return sources .map(source => getSemverExpression(source)) .filter(expression => expression); }; const validateSemverExpressions = semverExpressions => { for (const expression of semverExpressions) { if (semver_1.default.validRange(expression) === null) { const message = `Invalid semver expression (${expression}) found in ` + `one of your contract's imports.`; throw new Error(message); } } }; // takes an array of versions and an array of semver expressions // returns a version of the compiler or undefined if none can be found const findNewestSatisfyingVersion = ({ solcReleases, semverExpressions }) => { // releases are ordered from newest to oldest return solcReleases.find(version => { return semverExpressions.every(expression => semver_1.default.satisfies(version, expression)); }); }; const throwCompilerVersionNotFound = ({ path, semverExpressions }) => { const message = `Could not find a single version of the Solidity compiler that ` + `satisfies the following semver expressions obtained from your source ` + `files' pragma statements: ${semverExpressions.join(" - ")}. ` + `${os_1.default.EOL}Please check the pragma statements for ${path} and its imports.`; throw new Error(message); }; const compileWithPragmaAnalysis = ({ paths, options }) => __awaiter(void 0, void 0, void 0, function* () { //don't compile if there's yul const yulPath = paths.find(path => path.endsWith(".yul")); if (yulPath !== undefined) { throw new Error(`Paths to compile includes Yul source ${yulPath}. ` + `Pragma analysis is not supported when compiling Yul.`); } const filteredPaths = paths.filter(path => path.endsWith(".sol") || path.endsWith(".json")); if (filteredPaths.length === 0) { return { compilations: [] }; } // construct supplier options for fetching list of solc versions; // enforce no Docker because listing Docker versions is slow (Docker Hub API // paginates responses, with >500 pages at time of writing) const supplierOptions = { events: options.events, solcConfig: Object.assign(Object.assign({}, options.compilers.solc), { docker: false }) }; const compilerSupplier = new compilerSupplier_1.CompilerSupplier(supplierOptions); const { releases } = yield compilerSupplier.list(); // collect sources by the version of the Solidity compiler that they require const versionsAndSources = {}; for (const path of filteredPaths) { const source = (yield options.resolver.resolve(path)).body; const parserVersion = findNewestSatisfyingVersion({ solcReleases: releases, semverExpressions: [getSemverExpression(source)] }); if (!parserVersion) { const m = `Could not find a valid pragma expression in ${path}. To use the ` + `"pragma" compiler setting your contracts must contain a pragma ` + `expression.`; throw new Error(m); } // allSources is of the format { [filename]: string } const { allSources } = yield profiler_1.Profiler.requiredSourcesForSingleFile(options.with({ path, base_path: options.contracts_directory, resolver: options.resolver, compiler: { name: "solc", version: parserVersion }, compilers: { solc: { version: parserVersion } } })); // get an array of all the semver expressions in the sources const semverExpressions = yield getSemverExpressions(Object.values(allSources)); // this really just validates the expressions from the contracts' imports // as it has already determined the parser version for each contract validateSemverExpressions(semverExpressions); const newestSatisfyingVersion = findNewestSatisfyingVersion({ solcReleases: releases, semverExpressions }); if (!newestSatisfyingVersion) { throwCompilerVersionNotFound({ path, semverExpressions }); } versionsAndSources[newestSatisfyingVersion] = Object.assign(Object.assign({}, versionsAndSources[newestSatisfyingVersion]), allSources); } (0, reportSources_1.reportSources)({ paths: filteredPaths, options }); const compilations = []; for (const compilerVersion in versionsAndSources) { const compilationOptions = { compilers: (0, cloneDeep_1.default)(options.compilers) }; compilationOptions.compilers.solc.version = compilerVersion; const config = config_1.default.default().with(compilationOptions); const compilation = yield (0, run_1.run)(versionsAndSources[compilerVersion], config); if (compilation && Object.keys(compilation.contracts).length > 0) { compilations.push(compilation); } } return { compilations }; }); exports.compileWithPragmaAnalysis = compileWithPragmaAnalysis; //# sourceMappingURL=compileWithPragmaAnalysis.js.map /***/ }), /***/ 46405: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cache = void 0; const config_1 = __importDefault(__webpack_require__(20553)); const path_1 = __importDefault(__webpack_require__(71017)); const fs_1 = __importDefault(__webpack_require__(57147)); // @ts-ignore const fsPromises = __importStar(__webpack_require__(73292)); const fileNotFoundMessage = "no such file or directory"; class Cache { constructor() { const compilersDir = path_1.default.resolve(config_1.default.getTruffleDataDirectory(), "compilers"); const compilerCachePath = path_1.default.resolve(compilersDir, "node_modules"); // because babel binds to require & does weird things if (!fs_1.default.existsSync(compilersDir)) fs_1.default.mkdirSync(compilersDir); if (!fs_1.default.existsSync(compilerCachePath)) fs_1.default.mkdirSync(compilerCachePath); // for 5.0.8 users this.compilerCachePath = compilerCachePath; this.memoizedCompilers = new Map(); } list() { return __awaiter(this, void 0, void 0, function* () { return yield fsPromises.readdir(this.compilerCachePath); }); } add(code, fileName) { return __awaiter(this, void 0, void 0, function* () { const filePath = this.resolve(fileName); yield fsPromises.writeFile(filePath, code); this.memoizedCompilers.set(filePath, code); }); } has(fileName) { return __awaiter(this, void 0, void 0, function* () { const filePath = this.resolve(fileName); try { yield fsPromises.stat(filePath); return true; } catch (error) { // only throw if the error is due to something other than it not existing if (!error.message.includes(fileNotFoundMessage)) { throw error; } return false; } }); } loadFile(fileName) { return __awaiter(this, void 0, void 0, function* () { const filePath = this.resolve(fileName); if (this.memoizedCompilers.has(filePath)) { return this.memoizedCompilers.get(filePath); } try { const compiler = (yield fsPromises.readFile(filePath)).toString(); this.memoizedCompilers.set(filePath, compiler); return compiler; } catch (error) { if (!error.message.includes(fileNotFoundMessage)) { throw error; } else { throw new Error("The specified file could not be found."); } } }); } resolve(fileName) { return path_1.default.resolve(this.compilerCachePath, fileName); } } exports.Cache = Cache; //# sourceMappingURL=Cache.js.map /***/ }), /***/ 40329: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FailedRequestError = exports.CompilerFetchingError = exports.NoVersionError = void 0; class NoVersionError extends Error { constructor(input) { const message = `Could not find a compiler version matching ${input}. ` + `Please ensure you are specifying a valid version, constraint or ` + `build in the truffle config. Run \`truffle compile --list\` to ` + `see available versions.`; super(message); } } exports.NoVersionError = NoVersionError; class CompilerFetchingError extends Error { constructor(compilerRoots) { const message = `Failed to fetch the Solidity compiler from the following locations: ` + `${compilerRoots}. Are you connected to the internet?\n\n`; super(message); } } exports.CompilerFetchingError = CompilerFetchingError; class FailedRequestError extends Error { constructor(input, error) { const message = `Failed to complete request to: ${input}. Are you connected to ` + `the internet?\n\n` + error; super(message); } } exports.FailedRequestError = FailedRequestError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 47922: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StrategyCannotListVersionsError = exports.BadInputError = exports.CompilerSupplier = void 0; const path_1 = __importDefault(__webpack_require__(71017)); const fs_1 = __importDefault(__webpack_require__(57147)); const semver_1 = __importDefault(__webpack_require__(81249)); const loadingStrategies_1 = __webpack_require__(41514); const defaultSolcVersion = "0.5.16"; class CompilerSupplier { constructor({ events, solcConfig }) { const { version, docker, compilerRoots, dockerTagsUrl, spawn } = solcConfig; this.version = version ? version : defaultSolcVersion; this.docker = docker; this.strategyOptions = {}; if (version) this.strategyOptions.version = this.version; if (dockerTagsUrl) this.strategyOptions.dockerTagsUrl = dockerTagsUrl; if (compilerRoots) this.strategyOptions.compilerRoots = compilerRoots; if (events) this.strategyOptions.events = events; if (spawn) this.strategyOptions.spawn = spawn; } load() { return __awaiter(this, void 0, void 0, function* () { const userSpecification = this.version; let strategy; const useDocker = this.docker; const useNative = userSpecification === "native"; const useSpecifiedLocal = userSpecification && (fs_1.default.existsSync(userSpecification) || path_1.default.isAbsolute(userSpecification)); const isValidVersionRange = semver_1.default.validRange(userSpecification); if (useDocker) { strategy = new loadingStrategies_1.Docker(this.strategyOptions); } else if (useNative) { strategy = new loadingStrategies_1.Native(); } else if (useSpecifiedLocal) { strategy = new loadingStrategies_1.Local(); } else if (isValidVersionRange) { strategy = new loadingStrategies_1.VersionRange(this.strategyOptions); } if (strategy) { const solc = yield strategy.load(userSpecification); return { solc }; } else { throw new BadInputError(userSpecification); } }); } /** * This function lists known solc versions, possibly asynchronously to * account for APIs with paginated data (namely, Docker Hub) * * @return Promise<{ * prereleases: AsyncIterable<string>; * releases: AsyncIterable<string>; * latestRelease: string; * }> */ list() { return __awaiter(this, void 0, void 0, function* () { const userSpecification = this.version; let strategy; const useDocker = this.docker; const useNative = userSpecification === "native"; const useSpecifiedLocal = userSpecification && (fs_1.default.existsSync(userSpecification) || path_1.default.isAbsolute(userSpecification)); const isValidVersionRange = semver_1.default.validRange(userSpecification) || userSpecification === "pragma"; if (useDocker) { strategy = new loadingStrategies_1.Docker(this.strategyOptions); } else if (useNative) { strategy = new loadingStrategies_1.Native(); } else if (useSpecifiedLocal) { strategy = new loadingStrategies_1.Local(); } else if (isValidVersionRange) { strategy = new loadingStrategies_1.VersionRange(this.strategyOptions); } if (!strategy) { throw new BadInputError(userSpecification); } if ("list" in strategy) { return yield strategy.list(); } throw new StrategyCannotListVersionsError(strategy.constructor.name); }); } static getDefaultVersion() { return defaultSolcVersion; } } exports.CompilerSupplier = CompilerSupplier; class BadInputError extends Error { constructor(input) { const message = `Could not find a compiler version matching ${input}. ` + `compilers.solc.version option must be a string specifying:\n` + ` - a path to a locally installed solcjs\n` + ` - a solc version or range (ex: '0.4.22' or '^0.5.0')\n` + ` - a docker image name (ex: 'stable')\n` + ` - 'native' to use natively installed solc\n`; super(message); } } exports.BadInputError = BadInputError; class StrategyCannotListVersionsError extends Error { constructor(strategyName) { super(`Cannot list versions for strategy ${strategyName}`); } } exports.StrategyCannotListVersionsError = StrategyCannotListVersionsError; //# sourceMappingURL=index.js.map /***/ }), /***/ 48352: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoStringError = exports.NoDockerError = exports.Docker = void 0; // must polyfill AbortController to use axios >=0.20.0, <=0.27.2 on node <= v14.x __webpack_require__(19492); const axios_1 = __importDefault(__webpack_require__(43306)); const axios_retry_1 = __importDefault(__webpack_require__(42817)); // @ts-ignore const fs_1 = __importDefault(__webpack_require__(57147)); const child_process_1 = __webpack_require__(32081); const semver_1 = __importDefault(__webpack_require__(81249)); const Cache_1 = __webpack_require__(46405); const normalizeSolcVersion_1 = __webpack_require__(69738); const errors_1 = __webpack_require__(40329); const iter_tools_1 = __webpack_require__(84248); class Docker { constructor(options) { const defaultConfig = { dockerTagsUrl: "https://registry.hub.docker.com/v2/repositories/ethereum/solc/tags/" }; this.config = Object.assign({}, defaultConfig, options); this.cache = new Cache_1.Cache(); } load() { return __awaiter(this, void 0, void 0, function* () { // Set a sensible limit for maxBuffer // See https://github.com/nodejs/node/pull/23027 let maxBuffer = 1024 * 1024 * 100; if (this.config.spawn && this.config.spawn.maxBuffer) { maxBuffer = this.config.spawn.maxBuffer; } const versionString = yield this.validateAndGetSolcVersion(); const command = "docker run --platform=linux/amd64 --rm -i ethereum/solc:" + this.config.version + " --standard-json"; try { return { compile: options => String((0, child_process_1.execSync)(command, { input: options, maxBuffer })), version: () => versionString }; } catch (error) { if (error.message === "No matching version found") { throw new errors_1.NoVersionError(versionString); } throw error; } }); } /** * Fetch list of solc versions available as Docker images. * * This returns a promise for an object with three fields: * { latestRelease, releases, prereleases } * NOTE that `releases` and `prereleases` in this object are both * AsyncIterableIterators (thus, use only `for await (const ...)` to consume) */ list() { var _a; return __awaiter(this, void 0, void 0, function* () { const allTags = this.streamAllDockerTags(); // split stream of all tags into separate releases and prereleases streams const isRelease = name => !!semver_1.default.valid(name); const isPrerelease = name => name.match(/nightly/); const [allTagsA, allTagsB] = (0, iter_tools_1.asyncFork)(allTags); // construct prereleases stream const prereleases = (0, iter_tools_1.asyncFilter)(isPrerelease, allTagsB); // construct releases stream and immediately fork so as to allow consuming // the first value in the stream safely const [releases, forkedReleases] = (0, iter_tools_1.asyncFork)((0, iter_tools_1.asyncFilter)(isRelease, allTagsA)); // grab the latest release from the forked releases stream; // coerce semver to remove possible `-alpine` suffix used by this repo const latestRelease = (_a = semver_1.default.coerce(yield (0, iter_tools_1.asyncFirst)(forkedReleases))) === null || _a === void 0 ? void 0 : _a.version; return { prereleases, releases, latestRelease }; }); } /* * Private methods */ downloadDockerImage(image) { if (!semver_1.default.valid(image)) { const message = `The image version you have provided is not valid.\n` + `Please ensure that ${image} is a valid docker image name.`; throw new Error(message); } this.config.events.emit("compile:downloadDockerImage:start"); try { (0, child_process_1.execSync)(`docker pull ethereum/solc:${image}`); this.config.events.emit("compile:downloadDockerImage:succeed"); } catch (error) { this.config.events.emit("compile:downloadDockerImage:fail", { error }); } } validateAndGetSolcVersion() { return __awaiter(this, void 0, void 0, function* () { const image = this.config.version; const fileName = image + ".version"; // Skip validation if they've validated for this image before. if (yield this.cache.has(fileName)) { const cachePath = this.cache.resolve(fileName); return fs_1.default.readFileSync(cachePath, "utf-8"); } // Image specified if (!image) throw new NoStringError(image); // Docker exists locally try { (0, child_process_1.execSync)("docker -v"); } catch (error) { throw new NoDockerError(); } // Image exists locally try { (0, child_process_1.execSync)("docker inspect --type=image ethereum/solc:" + image); } catch (error) { console.log(`${image} does not exist locally.\n`); this.downloadDockerImage(image); } // Get version & cache. const version = (0, child_process_1.execSync)("docker run --platform=linux/amd64 ethereum/solc:" + image + " --version"); const normalized = (0, normalizeSolcVersion_1.normalizeSolcVersion)(version); yield this.cache.add(normalized, fileName); return normalized; }); } streamAllDockerTags() { // build http client to account for rate limit problems // use axiosRetry to instate exponential backoff when requests come back // with expected 429 const client = axios_1.default.create(); (0, axios_retry_1.default)(client, { retries: 5, retryDelay: axios_retry_1.default.exponentialDelay, shouldResetTimeout: true, retryCondition: error => { const tooManyRequests = !!(error && error.response && error.response.status === 429); return (axios_retry_1.default.isNetworkOrIdempotentRequestError(error) || tooManyRequests); } }); const { dockerTagsUrl } = this.config; let nextUrl = dockerTagsUrl; return (function () { return __asyncGenerator(this, arguments, function* () { do { try { const { data: { // page of results results, // next page url next } } = yield __await(client.get(nextUrl, { maxRedirects: 50 })); for (const { name } of results) { yield yield __await(name); } nextUrl = next; } catch (error) { throw new errors_1.FailedRequestError(dockerTagsUrl, error); } } while (nextUrl); }); })(); } } exports.Docker = Docker; class NoDockerError extends Error { constructor() { super("You are trying to run dockerized solc, but docker is not installed."); } } exports.NoDockerError = NoDockerError; class NoStringError extends Error { constructor(input) { const message = "`compilers.solc.version` option must be a string specifying:\n" + " - a path to a locally installed solcjs\n" + " - a solc version or range (ex: '0.4.22' or '^0.5.0')\n" + " - a docker image name (ex: 'stable')\n" + " - 'native' to use natively installed solc\n" + "Received: " + input + " instead."; super(message); } } exports.NoStringError = NoStringError; //# sourceMappingURL=Docker.js.map /***/ }), /***/ 8831: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoPathError = exports.Local = void 0; const path_1 = __importDefault(__webpack_require__(71017)); const original_require_1 = __importDefault(__webpack_require__(44516)); const wrapper_1 = __importDefault(__webpack_require__(11433)); const observeListeners_1 = __webpack_require__(60207); class Local { load(localPath) { const listeners = (0, observeListeners_1.observeListeners)(); try { const compilerPath = path_1.default.isAbsolute(localPath) ? localPath : path_1.default.resolve(process.cwd(), localPath); let soljson; try { soljson = (0, original_require_1.default)(compilerPath); } catch (error) { throw new NoPathError(localPath, error); } //HACK: if it has a compile function, assume it's already wrapped return soljson.compile ? soljson : (0, wrapper_1.default)(soljson); } finally { listeners.cleanup(); } } } exports.Local = Local; class NoPathError extends Error { constructor(input, error) { const message = `Could not find compiler at: ${input}\n\n` + error; super(message); } } exports.NoPathError = NoPathError; //# sourceMappingURL=Local.js.map /***/ }), /***/ 39517: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoNativeError = exports.Native = void 0; const { execSync } = __webpack_require__(32081); const { normalizeSolcVersion } = __webpack_require__(69738); const { NoVersionError } = __webpack_require__(40329); class Native { load() { const versionString = this.validateAndGetSolcVersion(); const command = "solc --standard-json"; const maxBuffer = 1024 * 1024 * 50; try { return { compile: options => String(execSync(command, { input: options, maxBuffer })), version: () => versionString }; } catch (error) { if (error.message === "No matching version found") { throw new NoVersionError(versionString); } throw error; } } validateAndGetSolcVersion() { let version; try { version = execSync("solc --version"); } catch (error) { throw new NoNativeError(error); } return normalizeSolcVersion(version); } } exports.Native = Native; class NoNativeError extends Error { constructor(error) { super("Could not execute local solc binary: " + error); } } exports.NoNativeError = NoNativeError; //# sourceMappingURL=Native.js.map /***/ }), /***/ 780: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoUrlError = exports.VersionRange = void 0; const debug_1 = __importDefault(__webpack_require__(15158)); const debug = (0, debug_1.default)("compile:compilerSupplier"); const require_from_string_1 = __importDefault(__webpack_require__(46029)); // must polyfill AbortController to use axios >=0.20.0, <=0.27.2 on node <= v14.x __webpack_require__(19492); const axios_1 = __importDefault(__webpack_require__(43306)); const semver_1 = __importDefault(__webpack_require__(81249)); const wrapper_1 = __importDefault(__webpack_require__(11433)); const Cache_1 = __webpack_require__(46405); const observeListeners_1 = __webpack_require__(60207); const errors_1 = __webpack_require__(40329); class VersionRange { constructor(options) { const defaultConfig = { compilerRoots: [ // this order of url root preference was recommended by Cameel from the // Solidity team here -- https://github.com/trufflesuite/truffle/pull/5008 "https://binaries.soliditylang.org/emscripten-wasm32/", "https://binaries.soliditylang.org/emscripten-asmjs/", "https://solc-bin.ethereum.org/bin/", "https://ethereum.github.io/solc-bin/bin/", "https://relay.trufflesuite.com/solc/emscripten-wasm32/", "https://relay.trufflesuite.com/solc/emscripten-asmjs/" ] }; this.config = Object.assign({}, defaultConfig, options); this.cache = new Cache_1.Cache(); } load(versionRange) { return __awaiter(this, void 0, void 0, function* () { const rangeIsSingleVersion = semver_1.default.valid(versionRange); if (rangeIsSingleVersion && (yield this.versionIsCached(versionRange))) { return yield this.getCachedSolcByVersionRange(versionRange); } try { return yield this.getSolcFromCacheOrUrl(versionRange); } catch (error) { if (error.message.includes("Failed to complete request")) { return yield this.getSatisfyingVersionFromCache(versionRange); } throw error; } }); } list(index = 0) { return __awaiter(this, void 0, void 0, function* () { if (index >= this.config.compilerRoots.length) { throw new Error(`Failed to fetch the list of Solidity compilers from the following ` + `sources: ${this.config.compilerRoots}. Make sure you are connected ` + `to the internet.`); } let data; try { const att