validate-output.ts 10.8 KB
Newer Older
1 2 3 4
'use strict'

import { task, extendConfig } from 'hardhat/config'

5
import { TASK_COMPILE } from 'hardhat/builtin-tasks/task-names'
6 7 8 9 10 11 12
import chalk from 'chalk'
import 'hardhat/types/config'
import {
  HardhatConfig,
  HardhatUserConfig,
  CompilerOutputContract,
} from 'hardhat/types'
13 14 15 16 17 18 19 20 21
import { BuildInfo } from 'hardhat/src/types/artifacts'

export interface Checks {
  title?: boolean // default: true,
  details?: boolean // default: true,
  compilationWarnings?: boolean // default: true,
  missingUserDoc?: boolean // default: true,
  missingDevDoc?: boolean // default: true,
}
22 23 24 25 26 27 28 29

declare module 'hardhat/types/config' {
  export interface HardhatUserConfig {
    outputChecks?: {
      include?: string[]
      exclude?: string[]
      runOnCompile?: boolean
      errorMode?: boolean
30
      checks?: Checks
31 32 33 34 35 36 37 38 39
    }
  }

  export interface HardhatConfig {
    outputChecks: {
      include: string[]
      exclude: string[]
      runOnCompile: boolean
      errorMode: boolean
40
      checks: Checks
41 42 43 44 45 46 47 48
    }
  }
}

extendConfig(
  (config: HardhatConfig, userConfig: Readonly<HardhatUserConfig>) => {
    config.outputChecks = {
      errorMode: userConfig.outputChecks?.errorMode || false,
49 50 51 52 53 54 55 56
      checks: {
        title: true,
        details: true,
        compilationWarnings: true,
        missingUserDoc: true,
        missingDevDoc: true,
        ...(userConfig.outputChecks?.checks || {}),
      },
57 58 59 60 61 62
      include: userConfig.outputChecks?.include || [],
      exclude: userConfig.outputChecks?.exclude || [],
      runOnCompile: userConfig.outputChecks?.runOnCompile || false,
    }
  }
)
63 64

interface ErrorInfo {
65
  type: ErrorType
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  text: string
  at: string
  filePath: string
  fileName: string
}

enum ErrorType {
  MissingTitle,
  MissingDetails,
  CompilationWarning,
  // User Docs
  MissingUserDoc,
  // Dev Docs
  MissingDevDoc,
}

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
declare interface ErrorUserdocArrayItem {
  notice?: string
}

export interface ErrorDevdocArrayItem {
  details?: string
  params?: {
    [key: string]: string
  }
}

export interface CompilerOutputContractWithDocumentation
  extends CompilerOutputContract {
  devdoc?: {
    author?: string
    details?: string
    title?: string
    errors?: {
      [key: string]: ErrorDevdocArrayItem[]
    }
    events?: {
      [key: string]: {
        details: string
        params: {
          [key: string]: string
        }
      }
    }
    methods?: {
      [key: string]: {
        details?: string
        params: {
          [key: string]: string
        }
        returns: {
          [key: string]: string
        }
      }
    }
    returns?: {
      [key: string]: {
        details?: string
        params: {
          [key: string]: string
        }
      }
    }
    stateVariables?: {
      [key: string]: {
        details?: string
        params: {
          [key: string]: string
        }
        returns: {
          [key: string]: string
        }
      }
    }
  }
  userdoc?: {
    errors?: {
      [key: string]: ErrorUserdocArrayItem[]
    }
    events?: {
      [key: string]: {
        notice: string
      }
    }
    methods?: {
      [key: string]: {
        notice: string
      }
    }
    notice?: string
  }
}

export interface CompilerOutputWithDocsAndPath
  extends CompilerOutputContractWithDocumentation {
  filePath: string
  fileName: string
}

165 166 167 168 169 170 171 172 173 174
const setupErrors =
  (fileSource: string, fileName: string) =>
  (errorType: ErrorType, extraData?: any) => {
    const typeToMessage = () => {
      switch (errorType) {
        case ErrorType.MissingTitle:
          return 'Contract is missing title'
        case ErrorType.MissingDetails:
          return 'Contract is missing details'
        case ErrorType.CompilationWarning:
175
          return `Compilation warnings: \n ${extraData} `
176 177 178 179 180 181 182 183 184 185 186 187 188 189

        // User DOCS
        case ErrorType.MissingUserDoc:
          return `${extraData} is missing @notice`

        // DEV DOCS
        case ErrorType.MissingDevDoc:
          return `${extraData} is missing @notice`

        default:
          return undefined
      }
    }

190 191 192
    return `${
      errorType !== ErrorType.CompilationWarning ? 'Comments Error' : ''
    }: ${typeToMessage()}\n   @ ${fileName} \n   --> ${fileSource}\n`
193 194 195
  }

task(TASK_COMPILE, async (args, hre, runSuper) => {
196
  const config = hre.config.outputChecks
197 198 199 200 201 202 203 204 205 206

  // Updates the compiler settings
  for (const compiler of hre.config.solidity.compilers) {
    compiler.settings.outputSelection['*']['*'].push('devdoc')
    compiler.settings.outputSelection['*']['*'].push('userdoc')
  }

  // Calls the actual COMPILE task
  await runSuper()

207 208 209
  if (!config.runOnCompile) {
    return
  }
210 211 212

  const getBuildInfo = async (
    qualifiedName: string
213 214 215 216 217 218 219
  ): Promise<BuildInfo | undefined> => {
    return hre.artifacts.getBuildInfo(qualifiedName)
  }

  // Loops through all the qualified names to get all the compiled contracts
  const getContractBuildInfo = async (
    qualifiedName: string
220 221
  ): Promise<CompilerOutputWithDocsAndPath | undefined> => {
    const [source, name] = qualifiedName.split(':')
222

223
    const build = await getBuildInfo(qualifiedName)
224
    const info: CompilerOutputContractWithDocumentation =
225
      build?.output.contracts[source][name]
226 227 228 229 230 231

    return {
      ...info,
      filePath: source,
      fileName: name,
    } as CompilerOutputWithDocsAndPath
232

233 234 235 236 237
    return undefined
  }

  const checkForErrors = (info: CompilerOutputWithDocsAndPath): ErrorInfo[] => {
    const foundErrors = []
238
    const getErrorText = setupErrors(info.filePath, info.fileName)
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

    const addError = (errorType: ErrorType, extraData?: any) => {
      const text = getErrorText(errorType, extraData)
      foundErrors.push({
        text,
        type: errorType,
        at: '',
        filePath: info.filePath,
        fileName: info.fileName,
      })
    }

    const findByName = (searchInObj: object, entityName: string) => {
      if (!searchInObj || !entityName) {
        return
      }

      const key = Object.keys(searchInObj).find((methodSigniture) => {
        const name = methodSigniture.split('(')[0]
        return name === entityName
      })

      if (!key) {
        return
      }
      return searchInObj[key]
    }

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const checkConstructor = (entity) => {
      // TODO:
      return
    }

    const checkEvent = (entity) => {
274 275
      if (config.checks.missingUserDoc) {
        const userDocEntry = findByName(info.userdoc.events, entity.name)
276

277 278 279
        if (!userDocEntry || !userDocEntry.notice) {
          addError(ErrorType.MissingUserDoc, `Event: (${entity.name})`)
        }
280
      }
281 282
      if (config.checks.missingDevDoc) {
        const devDocEntry = findByName(info.devdoc.events, entity.name)
283

284 285 286 287
        // TODO: Extend with checks for params, returns
        if (!devDocEntry) {
          addError(ErrorType.MissingUserDoc, `Event: (${entity.name})`)
        }
288 289 290 291
      }
    }

    const checkFunction = (entity) => {
292 293
      if (config.checks.missingUserDoc) {
        const userDocEntry = findByName(info.userdoc.methods, entity.name)
294

295 296 297
        if (!userDocEntry || !userDocEntry.notice) {
          addError(ErrorType.MissingUserDoc, `Function: (${entity.name})`)
        }
298
      }
299 300 301 302 303 304 305 306 307 308 309
      if (config.checks.missingDevDoc) {
        const devDocEntryFunc = findByName(info.devdoc.methods, entity.name)
        const devDocEntryVar = findByName(
          info.devdoc.stateVariables,
          entity.name
        )

        // TODO: Extend with checks for params, returns
        if (!devDocEntryFunc && !devDocEntryVar) {
          addError(ErrorType.MissingUserDoc, `Function: (${entity.name})`)
        }
310 311 312
      }
    }

313
    if (config.checks.title && !info.devdoc.title) {
314 315
      addError(ErrorType.MissingTitle)
    }
316
    if (config.checks.details && !info.devdoc.details) {
317 318 319 320
      addError(ErrorType.MissingDetails)
    }

    if (Array.isArray(info.abi)) {
321
      // Loops through the abi and for each function/event/var check in the user/dev doc.
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
      info.abi.forEach((entity) => {
        if (entity.type === 'constructor') {
          checkConstructor(entity)
        } else if (entity.type === 'event') {
          checkEvent(entity)
        } else if (entity.type === 'function') {
          checkFunction(entity)
        }
      })
    }

    // TODO: check for userDoc.errors

    return foundErrors
  }

338 339 340 341
  console.log('<<< Starting Output Checks >>> ')

  const allContracts = await hre.artifacts.getAllFullyQualifiedNames()
  // console.log("allContracts", allContracts);
342 343 344 345 346 347 348 349 350
  const qualifiedNames = allContracts
    .filter((str) => str.startsWith('contracts'))
    .filter((path) => {
      // Checks if this contact is included
      const includesPath = config.include.some((str) => path.includes(str))
      const excludesPath = config.exclude.some((str) => path.includes(str))

      return (config.include.length === 0 || includesPath) && !excludesPath
    })
351 352
  console.log('qualifiedNames', qualifiedNames)

353
  // 1. Setup
354
  const buildInfo: BuildInfo[] = (
355 356 357
    await Promise.all(qualifiedNames.map(getBuildInfo))
  ).filter((inf) => inf !== undefined)

358 359 360 361
  const contractBuildInfo: CompilerOutputWithDocsAndPath[] = (
    await Promise.all(qualifiedNames.map(getContractBuildInfo))
  ).filter((inf) => inf !== undefined)

362
  // 2. Check
363
  const errors = contractBuildInfo.reduce((foundErrors, info) => {
364 365 366 367 368 369 370 371 372
    const docErrors = checkForErrors(info)

    if (docErrors && docErrors.length > 0) {
      foundErrors[info.filePath] = docErrors
    }

    return foundErrors
  }, {} as { [file: string]: ErrorInfo[] })

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
  // Check for CompilationWarning
  if (config.checks.compilationWarnings) {
    for (const bi of buildInfo) {
      const outputErrors = (bi.output as any).errors
      if (outputErrors && outputErrors.length > 0) {
        outputErrors.forEach((err) => {
          if (!errors[err.sourceLocation.file]) {
            errors[err.sourceLocation.file] = []
          }
          const filePath = err.sourceLocation.file
          const fileComponents = filePath.split('/')
          const fileName = fileComponents[fileComponents.length - 1]

          errors[err.sourceLocation.file].push({
            text: setupErrors(filePath, fileName)(
              ErrorType.CompilationWarning,
              err.formattedMessage
            ),
            type: ErrorType.CompilationWarning,
            at: '',
            filePath,
            fileName,
          })
        })
        break
      }
    }
  }

402 403 404 405 406 407
  // 3. Act
  const printErrors = (level: 'error' | 'warn' = 'warn') => {
    Object.keys(errors).forEach((file) => {
      const errorsInfo = errors[file]

      if (errorsInfo && errorsInfo.length > 0) {
408
        errorsInfo.forEach((erIn) => {
409
          if (level === 'error') {
410
            console.error(chalk.red(erIn.text))
411
          } else {
412
            console.warn(chalk.yellow(erIn.text))
413 414 415 416 417 418
          }
        })
      }
    })
  }

419
  if (config.errorMode) {
420 421 422 423 424 425
    printErrors('error')
    throw new Error('Missing Natspec Comments')
  }

  printErrors()

426
  console.log('✅ All Contracts have been checked for missing Natspec comments')
427
})