hardhat/config#subtask TypeScript Examples

The following examples show how to use hardhat/config#subtask. 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: index.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
subtask(TASK_COMPILE_SOLIDITY, async (args: { force: boolean }, hre, runSuper) => {
  const { readValidations, ValidationsCacheOutdated, ValidationsCacheNotFound } = await import('./utils/validations');

  try {
    await readValidations(hre);
  } catch (e) {
    if (e instanceof ValidationsCacheOutdated || e instanceof ValidationsCacheNotFound) {
      args = { ...args, force: true };
    } else {
      throw e;
    }
  }

  return runSuper(args);
});
Example #2
Source File: index.ts    From hardhat-deploy with MIT License 6 votes vote down vote up
subtask(TASK_NODE_SERVER_READY).setAction(async (args, hre, runSuper) => {
  await runSuper(args);

  if (nodeTaskArgs.watch) {
    await hre.run(TASK_DEPLOY_MAIN, {
      ...nodeTaskArgs,
      watchOnly: true,
      reset: false,
    });
  }
});
Example #3
Source File: index.ts    From hardhat-deploy with MIT License 6 votes vote down vote up
subtask(TASK_NODE_GET_PROVIDER).setAction(
  async (args, hre, runSuper): Promise<EthereumProvider> => {
    const provider = await runSuper(args);

    if (!nodeTaskArgs.noReset) {
      await deploymentsManager.deletePreviousDeployments('localhost');
    }

    if (nodeTaskArgs.noDeploy) {
      // console.log('skip');
      return provider;
    }
    // console.log('enabling logging');
    await enableProviderLogging(provider, false);

    const networkName = getNetworkName(hre.network);
    if (networkName !== hre.network.name) {
      console.log(`copying ${networkName}'s deployment to localhost...`);
      // copy existing deployment from specified netwotk into localhost deployment folder
      fs.copy(
        path.join(hre.config.paths.deployments, networkName),
        path.join(hre.config.paths.deployments, 'localhost')
      );
    }

    nodeTaskArgs.log = !nodeTaskArgs.silent;
    delete nodeTaskArgs.silent;
    nodeTaskArgs.pendingtx = false;
    await hre.run(TASK_DEPLOY_MAIN, {
      ...nodeTaskArgs,
      watch: false,
      reset: false,
    });

    await enableProviderLogging(provider, true);

    return provider;
  }
);
Example #4
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Override https://github.com/wighawag/hardhat-deploy/blob/819df0fad56d75a5de5218c3307bec2093f8794c/src/index.ts#L396
 * in hardhat-deploy plugin, as it does not support EIP-1559
 */
subtask(TASK_DEPLOY_RUN_DEPLOY, 'Override the deploy task, with an explicit gas price.').setAction(
  async (taskArgs, { network, ethers }, runSuper) => {
    // const protocolConfigNetworkNames = Object.keys<ResolvedEnvironment['network']>(PROTOCOL_CONFIG.networks);
    // const protocolConfigNetworks = Object.values<ResolvedEnvironment['network']>(PROTOCOL_CONFIG.networks);
    const protocolConfigNetwork = PROTOCOL_CONFIG.networks[network.name] ?? undefined
    if (!protocolConfigNetwork) {
      throw Error(
        'Cannot deploy with hardhat-deploy due to missing hardhat_deploy_gas_price field in protocol-config.json file'
      )
    }

    const hardhatDeployGasPrice = (protocolConfigNetwork as ResolvedEnvironment['network']).hardhat_deploy_gas_price
    const parsedGasPrice = hardhatDeployGasPrice.split(' ')

    // as in https://github.com/wighawag/hardhat-deploy/blob/819df0fad56d75a5de5218c3307bec2093f8794c/src/DeploymentsManager.ts#L974
    let gasPrice: string
    if (parsedGasPrice.length > 1) {
      gasPrice = ethers.utils.parseUnits(parsedGasPrice[0], parsedGasPrice[1]).toString()
    } else {
      gasPrice = parsedGasPrice[0]
    }

    console.log(`Deployment arguments are ${JSON.stringify({ ...taskArgs, gasprice: gasPrice }, null, 2)}`)

    try {
      await runSuper({ ...taskArgs, gasprice: gasPrice })
    } catch (error) {
      console.log(error)
      throw Error('Cannot override hardhat task TASK_DEPLOY_RUN_DEPLOY')
    }
  }
)
Example #5
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
subtask('flat:get-dependency-graph')
  .addOptionalParam('files', undefined, undefined, types.any)
  .setAction(async ({ files }, { run }) => {
    const sourcePaths =
      files === undefined ? await run('compile:solidity:get-source-paths') : files.map((f: string) => realpathSync(f))

    const sourceNames = await run('compile:solidity:get-source-names', {
      sourcePaths
    })

    const dependencyGraph = await run('compile:solidity:get-dependency-graph', { sourceNames })

    return dependencyGraph
  })
Example #6
Source File: utils.ts    From eth with GNU General Public License v3.0 6 votes vote down vote up
subtask('utils:assertChainId', 'Assert proper network is selectaed').setAction(assertChainId);
Example #7
Source File: copy-uniswap-v3-artifacts.ts    From hypervisor with The Unlicense 6 votes vote down vote up
subtask(TASK_CREATE_UNISWAPV3_ARTIFACT, async (_, { artifacts }) => {
    fse.copySync(
        path.join(__dirname, '../node_modules/@uniswap/v3-core/artifacts/contracts'),
        path.join((artifacts as any)['_artifactsPath'], '@uniswap/v3-core/contracts'),
        { overwrite: false }
    )
    fse.copySync(
        path.join(__dirname, '../node_modules/@uniswap/v3-periphery/artifacts/contracts'),
        path.join((artifacts as any)['_artifactsPath'], '@uniswap/v3-periphery/contracts'),
        { overwrite: false }
    )
});
Example #8
Source File: index.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
subtask(TASK_COMPILE_SOLIDITY_COMPILE, async (args: RunCompilerArgs, hre, runSuper) => {
  const { validate, solcInputOutputDecoder } = await import('@openzeppelin/upgrades-core');
  const { writeValidations } = await import('./utils/validations');

  // TODO: patch input
  const { output, solcBuild } = await runSuper();

  const { isFullSolcOutput } = await import('./utils/is-full-solc-output');
  if (isFullSolcOutput(output)) {
    const decodeSrc = solcInputOutputDecoder(args.input, output);
    const validations = validate(output, decodeSrc);
    await writeValidations(hre, validations);
  }

  return { output, solcBuild };
});
Example #9
Source File: subtasks.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
// Injects network block limit (minus 1 million) in the abi so
// ethers uses it instead of running gas estimation.
subtask(TASK_COMPILE_SOLIDITY_GET_ARTIFACT_FROM_COMPILATION_OUTPUT)
  .setAction(async (_, { network }, runSuper) => {
    const artifact = await runSuper();

    // These changes should be skipped when publishing to npm.
    // They override ethers' gas estimation
    if (!process.env.SKIP_ABI_GAS_MODS) {
      artifact.abi = addGasToAbiMethods(network.config, artifact.abi);
    }

    return artifact;
  }
);
Example #10
Source File: subgraph.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
subtask(
  TASK_SUBGRAPH_DOCKER,
  'hook when docker containers are fully deployed, but graph hasnt been deployed yet'
).setAction(subgraphDocker);
Example #11
Source File: circom.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
subtask(TASK_CIRCOM_TEMPLATE, 'replace hardhat-circom templating with custom').setAction(
  circomTemplate
);
Example #12
Source File: whitelist.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
subtask('whitelist:existsAddress', 'determine if an address is whitelisted')
  .addParam('address', 'network address', undefined, types.string)
  .setAction(whitelistExistsAddress);
Example #13
Source File: whitelist.ts    From eth with GNU General Public License v3.0 5 votes vote down vote up
subtask('whitelist:existsKeyHash', 'determine if a whitelist key is valid')
  .addParam('key', 'whitelist key', undefined, types.string)
  .setAction(whitelistExistsKeyHash);
Example #14
Source File: index.ts    From plugins with MIT License 5 votes vote down vote up
subtask(
  TASK_COMPILE_SOLIDITY_RUN_SOLC,
  async (args: { input: any; solcPath: string }, hre, runSuper) => {
    const ignoreRxList = hre.network.config.ignoreRxList || [];
    const ignore = (filename: string) => ignoreRxList.reduce((ignored: boolean, rx: string | RegExp) => ignored || new RegExp(rx).test(filename), false);
    if (hre.network.ovm !== true) {
        // Separate the EVM and OVM inputs.
        for (const file of Object.keys(args.input.sources)) {
          // Ignore any contract that has this tag or in ignore list
          if (args.input.sources[file].content.includes('// @unsupported: evm') || ignore(file)) {
              delete args.input.sources[file];
          }
          else {
              //console.log(file + ' included');
          }
        }
        return runSuper(args)
    }

    // Just some silly sanity checks, make sure we have a solc version to download. Our format is
    // `X.Y.Z` (for now).
    let ovmSolcVersion = DEFAULT_OVM_SOLC_VERSION
    if (hre.config?.ovm?.solcVersion) {
      ovmSolcVersion = hre.config.ovm.solcVersion
    }

    // Get a path to a soljson file.
    const ovmSolcPath = await getOvmSolcPath(ovmSolcVersion)

    // These objects get fed into the compiler. We're creating two of these because we need to
    // throw one into the OVM compiler and another into the EVM compiler. Users are able to prevent
    // certain files from being compiled by the OVM compiler by adding "// @unsupported: ovm"
    // somewhere near the top of their file.
    const ovmInput = {
      language: 'Solidity',
      sources: {},
      settings: args.input.settings,
    }

    // Separate the EVM and OVM inputs.
    for (const file of Object.keys(args.input.sources)) {
      // Ignore any contract that has this tag or in ignore list
      if (!args.input.sources[file].content.includes('// @unsupported: ovm') && !ignore(file)) {
        ovmInput.sources[file] = args.input.sources[file]
      }
    }

    // Build both inputs separately.
    const ovmOutput = await hre.run(TASK_COMPILE_SOLIDITY_RUN_SOLCJS, {
      input: ovmInput,
      solcJsPath: ovmSolcPath,
    })

    // Just doing this to add some extra useful information to any errors in the OVM compiler output.
    ovmOutput.errors = (ovmOutput.errors || []).map((error: any) => {
      if (error.severity === 'error') {
        error.formattedMessage = `OVM Compiler Error (insert "// @unsupported: ovm" if you don't want this file to be compiled for the OVM):\n ${error.formattedMessage}`
      }

      return error
    })

    return ovmOutput
  }
)
Example #15
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
subtask('flat:get-flattened-sources', 'Returns all contracts and their dependencies flattened')
  .addOptionalParam('files', undefined, undefined, types.any)
  .addOptionalParam('output', undefined, undefined, types.string)
  .setAction(async ({ files, output }, { run }) => {
    const dependencyGraph = await run('flat:get-dependency-graph', { files })
    console.log(dependencyGraph)

    let flattened = ''

    if (dependencyGraph.getResolvedFiles().length === 0) {
      return flattened
    }

    const sortedFiles = getSortedFiles(dependencyGraph)

    let isFirst = true
    for (const file of sortedFiles) {
      if (!isFirst) {
        flattened += '\n'
      }
      flattened += `// File ${file.getVersionedName()}\n`
      flattened += `${getFileWithoutImports(file)}\n`

      isFirst = false
    }

    // Remove every line started with "// SPDX-License-Identifier:"
    flattened = flattened.replace(/SPDX-License-Identifier:/gm, 'License-Identifier:')

    flattened = `// SPDX-License-Identifier: MIXED\n\n${flattened}`

    // Remove every line started with "pragma experimental ABIEncoderV2;" except the first one
    flattened = flattened.replace(
      /pragma experimental ABIEncoderV2;\n/gm,
      (
        (i) => (m: string) =>
          !i++ ? m : ''
      )(0)
    )

    flattened = flattened.trim()
    if (output) {
      console.log('Writing to', output)
      writeFileSync(output, flattened)
      return ''
    }
    return flattened
  })
Example #16
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
subtask(TASK_TEST_SETUP_TEST_ENVIRONMENT, 'Setup test environment').setAction(async (_, { network }) => {
  if (network.name === HARDHAT_NETWORK_NAME) {
    await network.provider.send('hardhat_reset')
  }
})
Example #17
Source File: hardhat.config.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
subtask<ParallelTestCLIOpts>(
  'test:in-group:with-same-instance',
  'Put test files into groups that shares the same ganache instances',
  parallelTest
)
Example #18
Source File: copy-uniswap-v3-artifacts.ts    From hypervisor with The Unlicense 5 votes vote down vote up
subtask(
    TASK_COMPILE_GET_COMPILATION_TASKS,
    async (_, __, runSuper) => {
        const otherTasks = await runSuper()
        return [...otherTasks, TASK_CREATE_UNISWAPV3_ARTIFACT]
    }
);
Example #19
Source File: index.ts    From hardhat-circom with GNU General Public License v3.0 5 votes vote down vote up
subtask(TASK_CIRCOM_TEMPLATE, "template Verifier with zkeys")
  .addParam("zkeys", "array of zkey fastfiles (can be passed directly to SnarkJS)", undefined, types.any)
  .setAction(circomTemplate);
Example #20
Source File: index.ts    From hardhat-deploy with MIT License 5 votes vote down vote up
subtask(TASK_DEPLOY_RUN_DEPLOY, 'deploy run only')
  .addOptionalParam('export', 'export current network deployments')
  .addOptionalParam('exportAll', 'export all deployments into one file')
  .addOptionalParam(
    'tags',
    'specify which deploy script to execute via tags, separated by commas',
    undefined,
    types.string
  )
  .addOptionalParam(
    'write',
    'whether to write deployments to file',
    true,
    types.boolean
  )
  .addOptionalParam(
    'pendingtx',
    'whether to save pending tx',
    false,
    types.boolean
  )
  .addOptionalParam(
    'gasprice',
    'gas price to use for transactions',
    undefined,
    types.string
  )
  .addOptionalParam('maxfee', 'max fee per gas', undefined, types.string)
  .addOptionalParam(
    'priorityfee',
    'max priority fee per gas',
    undefined,
    types.string
  )
  .addFlag('reset', 'whether to delete deployments files first')
  .addFlag('log', 'whether to output log')
  .addFlag('reportGas', 'report gas use')
  .setAction(async (args, hre) => {
    let tags = args.tags;
    if (typeof tags === 'string') {
      tags = tags.split(',');
    }
    await deploymentsManager.runDeploy(tags, {
      log: args.log,
      resetMemory: false,
      deletePreviousDeployments: args.reset,
      writeDeploymentsToFiles: args.write,
      export: args.export,
      exportAll: args.exportAll,
      savePendingTx: args.pendingtx,
      gasPrice: args.gasprice,
      maxFeePerGas: args.maxfee,
      maxPriorityFeePerGas: args.priorityfee,
    });
    if (args.reportGas) {
      console.log(`total gas used: ${hre.deployments.getGasUsed()}`);
    }
  });
Example #21
Source File: index.ts    From hardhat-deploy with MIT License 4 votes vote down vote up
subtask(TASK_DEPLOY_MAIN, 'deploy')
  .addOptionalParam('export', 'export current network deployments')
  .addOptionalParam('exportAll', 'export all deployments into one file')
  .addOptionalParam(
    'tags',
    'specify which deploy script to execute via tags, separated by commas',
    undefined,
    types.string
  )
  .addOptionalParam(
    'write',
    'whether to write deployments to file',
    true,
    types.boolean
  )
  .addOptionalParam(
    'pendingtx',
    'whether to save pending tx',
    false,
    types.boolean
  )
  .addOptionalParam(
    'gasprice',
    'gas price to use for transactions',
    undefined,
    types.string
  )
  .addOptionalParam('maxfee', 'max fee per gas', undefined, types.string)
  .addOptionalParam(
    'priorityfee',
    'max priority fee per gas',
    undefined,
    types.string
  )
  .addFlag('noCompile', 'disable pre compilation')
  .addFlag('reset', 'whether to delete deployments files first')
  .addFlag('log', 'whether to output log')
  .addFlag('watch', 'redeploy on every change of contract or deploy script')
  .addFlag(
    'watchOnly',
    'do not actually deploy, just watch and deploy if changes occurs'
  )
  .addFlag('reportGas', 'report gas use')
  .setAction(async (args, hre) => {
    if (args.reset) {
      await deploymentsManager.deletePreviousDeployments(
        args.runAsNode ? 'localhost' : undefined
      );
    }

    async function compileAndDeploy() {
      if (!args.noCompile) {
        await hre.run('compile');
      }
      return hre.run(TASK_DEPLOY_RUN_DEPLOY, {...args, reset: false});
    }

    let currentPromise: Promise<{
      [name: string]: Deployment;
    }> | null = args.watchOnly ? null : compileAndDeploy();
    if (args.watch || args.watchOnly) {
      const deployPaths = getDeployPaths(hre.network);
      const watcher = chokidar.watch(
        [hre.config.paths.sources, ...deployPaths],
        {
          ignored: /(^|[/\\])\../, // ignore dotfiles
          persistent: true,
        }
      );

      watcher.on('ready', () =>
        console.log('Initial scan complete. Ready for changes')
      );

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      let rejectPending: any = null;
      // eslint-disable-next-line no-inner-declarations,@typescript-eslint/no-explicit-any
      function pending(): Promise<void> {
        return new Promise((resolve, reject) => {
          rejectPending = reject;
          if (currentPromise) {
            currentPromise
              .then(() => {
                rejectPending = null;
                resolve();
              })
              .catch((error) => {
                rejectPending = null;
                currentPromise = null;
                console.error(error);
              });
          } else {
            rejectPending = null;
            resolve();
          }
        });
      }
      watcher.on('change', async () => {
        console.log('change detected');
        if (currentPromise) {
          console.log('deployment in progress, please wait ...');
          if (rejectPending) {
            // console.log("disabling previously pending redeployments...");
            rejectPending();
          }
          try {
            // console.log("waiting for current redeployment...");
            await pending();
            // console.log("pending finished");
          } catch (e) {
            return;
          }
        }
        currentPromise = compileAndDeploy();
        try {
          await currentPromise;
        } catch (e) {
          console.error(e);
        }
        currentPromise = null;
      });
      try {
        await currentPromise;
      } catch (e) {
        console.error(e);
      }
      currentPromise = null;
      await new Promise((resolve) => setTimeout(resolve, 2000000000)); // TODO better way ?
    } else {
      const firstDeployments = await currentPromise;
      return firstDeployments;
    }
  });