contract-defs.ts 1.68 KB
Newer Older
1
import { ethers } from 'ethers'
2

3 4 5 6 7 8 9
/**
 * Gets the hardhat artifact for the given contract name.
 * Will throw an error if the contract artifact is not found.
 *
 * @param name Contract name.
 * @returns The artifact for the given contract name.
 */
10
export const getContractDefinition = (name: string): any => {
11 12 13 14 15
  // We import this using `require` because hardhat tries to build this file when compiling
  // the contracts, but we need the contracts to be compiled before the contract-artifacts.ts
  // file can be generated.
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const { getContractArtifact } = require('./contract-artifacts')
16
  const artifact = getContractArtifact(name)
17
  if (artifact === undefined) {
18 19
    throw new Error(`Unable to find artifact for contract: ${name}`)
  }
20
  return artifact
21 22
}

23 24 25 26 27 28
/**
 * Gets an ethers Interface instance for the given contract name.
 *
 * @param name Contract name.
 * @returns The interface for the given contract name.
 */
29 30
export const getContractInterface = (name: string): ethers.utils.Interface => {
  const definition = getContractDefinition(name)
31 32 33
  return new ethers.utils.Interface(definition.abi)
}

34 35 36 37 38 39 40
/**
 * Gets an ethers ContractFactory instance for the given contract name.
 *
 * @param name Contract name.
 * @param signer The signer for the ContractFactory to use.
 * @returns The contract factory for the given contract name.
 */
41 42
export const getContractFactory = (
  name: string,
43 44 45 46 47 48 49 50 51
  signer?: ethers.Signer
): ethers.ContractFactory => {
  const definition = getContractDefinition(name)
  const contractInterface = getContractInterface(name)
  return new ethers.ContractFactory(
    contractInterface,
    definition.bytecode,
    signer
  )
52
}