hardhat/types#BuildInfo TypeScript Examples

The following examples show how to use hardhat/types#BuildInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: get-build-info.ts    From openzeppelin-transpiler with MIT License 6 votes vote down vote up
export async function getBuildInfo(version: string): Promise<BuildInfo> {
  const buildInfoPath = path.join(hre.config.paths.artifacts, 'build-info');
  const filenames = await fs.readdir(buildInfoPath);
  const buildInfos: BuildInfo[] = await Promise.all(
    filenames.map(async f => JSON.parse(await fs.readFile(path.join(buildInfoPath, f), 'utf8'))),
  );

  const matching = buildInfos.filter(i => i.solcVersion.startsWith(version));

  if (matching.length > 1) {
    throw new Error('More than 1 matching compilation found');
  } else if (matching.length < 1) {
    throw new Error('Compilation not found');
  }

  return matching[0];
}
Example #2
Source File: task.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
artifact(contractName: string, fileName?: string): Artifact {
    const buildInfoDir = this._dirAt(this.dir(), 'build-info');
    const builds: {
      [sourceName: string]: { [contractName: string]: CompilerOutputContract };
    } = this._existsFile(path.join(buildInfoDir, `${fileName || contractName}.json`))
      ? this.buildInfo(contractName).output.contracts
      : this.buildInfos().reduce((result, info: BuildInfo) => ({ ...result, ...info.output.contracts }), {});

    const sourceName = Object.keys(builds).find((sourceName) =>
      Object.keys(builds[sourceName]).find((key) => key === contractName)
    );

    if (!sourceName) throw Error(`Could not find artifact for ${contractName}`);
    return builds[sourceName][contractName];
  }
Example #3
Source File: verifier.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
private findBuildInfoWithContract(buildInfos: BuildInfo[], contractName: string): BuildInfo {
    const found = buildInfos.find((buildInfo) =>
      getAllFullyQualifiedNames(buildInfo).some((name) => name.contractName === contractName)
    );

    if (found === undefined) {
      throw Error(`Could not find a build info for contract ${contractName}`);
    } else {
      return found;
    }
  }
Example #4
Source File: buildinfo.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
export function findContractSourceName(buildInfo: BuildInfo, contractName: string): string {
  const names = getAllFullyQualifiedNames(buildInfo);
  const contractMatches = names.filter((name) => name.contractName === contractName);
  if (contractMatches.length === 0)
    throw Error(`Could not find a source file for the requested contract ${contractName}`);
  if (contractMatches.length > 1) throw Error(`More than one source file was found to match ${contractName}`);
  return contractMatches[0].sourceName;
}
Example #5
Source File: buildinfo.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
export function getAllFullyQualifiedNames(buildInfo: BuildInfo): Array<{ sourceName: string; contractName: string }> {
  const contracts = buildInfo.output.contracts;
  return Object.keys(contracts).reduce((names: { sourceName: string; contractName: string }[], sourceName) => {
    const contractsNames = Object.keys(contracts[sourceName]);
    const qualifiedNames = contractsNames.map((contractName) => ({ sourceName, contractName }));
    return names.concat(qualifiedNames);
  }, []);
}
Example #6
Source File: task.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
buildInfo(fileName: string): BuildInfo {
    const buildInfoDir = this._dirAt(this.dir(), 'build-info');
    const artifactFile = this._fileAt(buildInfoDir, `${extname(fileName) ? fileName : `${fileName}.json`}`);
    return JSON.parse(fs.readFileSync(artifactFile).toString());
  }
Example #7
Source File: task.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
buildInfos(): Array<BuildInfo> {
    const buildInfoDir = this._dirAt(this.dir(), 'build-info');
    return fs.readdirSync(buildInfoDir).map((fileName) => this.buildInfo(fileName));
  }
Example #8
Source File: hardhat.config.ts    From hardhat-deploy with MIT License 5 votes vote down vote up
task(TASK_COMPILE).setAction(async (args, hre, runSuper) => {
  await runSuper(args);
  const extendedArtifactFolderpath = 'extendedArtifacts';
  fs.emptyDirSync(extendedArtifactFolderpath);
  const artifactPaths = await hre.artifacts.getArtifactPaths();
  for (const artifactPath of artifactPaths) {
    const artifact: Artifact = await fs.readJSON(artifactPath);
    const artifactName = path.basename(artifactPath, '.json');
    const artifactDBGPath = path.join(
      path.dirname(artifactPath),
      artifactName + '.dbg.json'
    );
    const artifactDBG = await fs.readJSON(artifactDBGPath);
    const buildinfoPath = path.join(
      path.dirname(artifactDBGPath),
      artifactDBG.buildInfo
    );
    const buildInfo: BuildInfo = await fs.readJSON(buildinfoPath);
    const output =
      buildInfo.output.contracts[artifact.sourceName][artifactName];

    // TODO decide on ExtendedArtifact vs Artifact vs Deployment type
    // save space by not duplicating bytecodes
    if (output.evm?.bytecode?.object) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (output.evm.bytecode.object as any) = undefined;
    }
    if (output.evm?.deployedBytecode?.object) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (output.evm.deployedBytecode.object as any) = undefined;
    }
    // -----------------------------------------

    const solcInput = JSON.stringify(buildInfo.input, null, '  ');
    const solcInputHash = Buffer.from(murmur128(solcInput)).toString('hex');
    const extendedArtifact = {
      ...artifact,
      ...output,
      solcInput,
      solcInputHash,
    };
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (extendedArtifact._format as any) = undefined;
    fs.writeFileSync(
      path.join(extendedArtifactFolderpath, artifactName + '.json'),
      JSON.stringify(extendedArtifact, null, '  ')
    );
  }
});
Example #9
Source File: index.ts    From hardhat-deploy with MIT License 4 votes vote down vote up
task('export-artifacts')
  .addPositionalParam(
    'dest',
    'destination folder where the extended artifacts files will be written to',
    undefined,
    types.string
  )
  .addFlag(
    'solcInput',
    'if set, artifacts will have an associated solcInput files (required for old version of solidity to ensure verifiability'
  )
  .addFlag(
    'includingEmptyBytecode',
    'if set, even contract without bytecode (like interfaces) will be exported'
  )
  .addFlag(
    'includingNoPublicFunctions',
    'if set, even contract without public interface (like imternal libraries) will be exported'
  )
  .addOptionalParam(
    'exclude',
    'list of contract names separated by commas to exclude',
    undefined,
    types.string
  )
  .addOptionalParam(
    'include',
    'list of contract names separated by commas to include. If specified, only these will be considered',
    undefined,
    types.string
  )
  .addFlag(
    'hideSources',
    'if set, the artifacts files will not contain source code (metadata or other data exposing it) unless specified via --sources-for'
  )
  .addOptionalParam(
    'sourcesFor',
    'list of contract names separated by commas to include source (metadata,etc...) for (see --hide-sources)',
    undefined,
    types.string
  )
  .setAction(async (args, hre) => {
    await hre.run('compile');
    const argsInclude: string[] = args.include ? args.include.split(',') : [];
    const checkInclude = argsInclude.length > 0;
    const include = argsInclude.reduce(
      (result: Record<string, boolean>, item: string) => {
        result[item] = true;
        return result;
      },
      {}
    );
    const argsExclude: string[] = args.exclude ? args.exclude.split(',') : [];
    const exclude = argsExclude.reduce(
      (result: Record<string, boolean>, item: string) => {
        result[item] = true;
        return result;
      },
      {}
    );
    const argsSourcesFor: string[] = args.sourcesFor
      ? args.sourcesFor.split(',')
      : [];
    const sourcesFor = argsSourcesFor.reduce(
      (result: Record<string, boolean>, item: string) => {
        result[item] = true;
        return result;
      },
      {}
    );
    const extendedArtifactFolderpath = args.dest;
    fs.emptyDirSync(extendedArtifactFolderpath);
    const artifactPaths = await hre.artifacts.getArtifactPaths();
    for (const artifactPath of artifactPaths) {
      const artifact: Artifact = await fs.readJSON(artifactPath);
      const artifactName = path.basename(artifactPath, '.json');
      if (exclude[artifactName]) {
        continue;
      }
      if (checkInclude && !include[artifactName]) {
        continue;
      }
      const artifactDBGPath = path.join(
        path.dirname(artifactPath),
        artifactName + '.dbg.json'
      );
      const artifactDBG = await fs.readJSON(artifactDBGPath);
      const buildinfoPath = path.join(
        path.dirname(artifactDBGPath),
        artifactDBG.buildInfo
      );
      const buildInfo: BuildInfo = await fs.readJSON(buildinfoPath);
      const output =
        buildInfo.output.contracts[artifact.sourceName][artifactName];

      if (!args.includingNoPublicFunctions) {
        if (
          !artifact.abi ||
          artifact.abi.filter((v) => v.type !== 'event').length === 0
        ) {
          continue;
        }
      }

      if (!args.includingEmptyBytecode) {
        if (!artifact.bytecode || artifact.bytecode === '0x') {
          continue;
        }
      }

      // TODO decide on ExtendedArtifact vs Artifact vs Deployment type
      // save space by not duplicating bytecodes
      if (output.evm?.bytecode?.object) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (output.evm.bytecode.object as any) = undefined;
      }
      if (output.evm?.deployedBytecode?.object) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (output.evm.deployedBytecode.object as any) = undefined;
      }
      // -----------------------------------------

      const extendedArtifact: ExtendedArtifact = {
        ...artifact,
        ...output,
      };
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (extendedArtifact as any)._format = undefined;

      if (args.solcInput) {
        const solcInput = JSON.stringify(buildInfo.input, null, '  ');
        const solcInputHash = Buffer.from(murmur128(solcInput)).toString('hex');
        extendedArtifact.solcInput = solcInput;
        extendedArtifact.solcInputHash = solcInputHash;
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      let dataToWrite: any = extendedArtifact;
      if (args.hideSources && !sourcesFor[artifactName]) {
        dataToWrite = {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          contractName: (extendedArtifact as any).contractName,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          sourceName: (extendedArtifact as any).sourceName,
          abi: extendedArtifact.abi,
          bytecode: extendedArtifact.bytecode,
          deployedBytecode: extendedArtifact.deployedBytecode,
          linkReferences: extendedArtifact.linkReferences,
          deployedLinkReferences: extendedArtifact.deployedLinkReferences,
          devdoc: extendedArtifact.devdoc,
          userdoc: extendedArtifact.userdoc,
          evm: extendedArtifact.evm
            ? {
                gasEstimates: extendedArtifact.evm.gasEstimates,
                methodIdentifiers: extendedArtifact.evm.methodIdentifiers,
              }
            : undefined,
        };
      }

      let filepath = path.join(
        extendedArtifactFolderpath,
        artifactName + '.json'
      );
      if (dataToWrite.sourceName) {
        if (dataToWrite.contractName) {
          filepath = path.join(
            extendedArtifactFolderpath,
            dataToWrite.sourceName,
            dataToWrite.contractName + '.json'
          );
        } else {
          filepath = path.join(
            extendedArtifactFolderpath,
            dataToWrite.sourceName,
            artifactName + '.json'
          );
        }
      }

      fs.ensureFileSync(filepath);
      fs.writeFileSync(filepath, JSON.stringify(dataToWrite, null, '  '));
    }
  });