compilation.ts 1.04 KB
Newer Older
Kelvin Fichter's avatar
Kelvin Fichter committed
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
import * as path from 'path'
import bre from '@nomiclabs/buidler'
import { Compiler } from '@nomiclabs/buidler/internal/solidity/compiler'

export interface SolidityCompiler {
  version: () => string
  compile: any
}

export interface ContractSource {
  path: string
  content: string
}

export const getDefaultCompiler = async (): Promise<SolidityCompiler> => {
  const compiler = new Compiler(
    bre.config.solc.version,
    path.join(bre.config.paths.cache, 'compilers')
  )

  return compiler.getSolc()
}

export const compile = async (
  sources: ContractSource[],
  compiler?: SolidityCompiler
): Promise<any> => {
  compiler = compiler || (await getDefaultCompiler())

  const compilerInput = {
    language: 'Solidity',
    sources: sources.reduce((parsed, source) => {
      parsed[source.path] = {
        content: source.content,
      }

      return parsed
    }, {}),
    settings: {
      outputSelection: {
        '*': {
          '*': ['*'],
        },
      },
    },
  }

  return JSON.parse(compiler.compile(JSON.stringify(compilerInput)))
}