Back to homepage

Hardhat first steps: create project and configuration

Published

Step-by-step guide to create a basic smart contract project with Hardhat and review which options we can change in the configuration file so it can be used on a Web3 app.


Hardhat is an Ethereum development environment. That means that we can create smart contract projects including tests and scripts to deploy them. In addition Hardhat allows us to run Ethereum locally so we can deploy and test the smart contracts we create in our own development machine.

How to create a project with Hardhat

To create a project with Hardhat we just need to run npx hardhat and choose the option "Create sample project". It will generate some files and folders so let's review them:

  • hardhat.config.js: by default it contains basic configuration like the Solidity version but we can override defaults if we want to change the source folder of our smart contracts, the networks etc.
  • /contracts: inside this folder we'll find a Greeter.sol smart contract. We can add more smart contracts here.
  • /scripts: this folder contains a sample-script.js that we can run to initialize variables of our smat contract and deploy it.
  • /test: this folder contains a sample-test.js with, obviously, basic tests.

Initialize project with Hardhat

Configure Hardhat project paths

In most of my projects I like to have both a web application and smart contracts in the same folder and repository but instead of keeping the smart contracts in the default folders (the ones mentioned above), I prefer to have the smart contracts source files in /solidity/contracts and the compiled files in /src/artifacts. For that, you need to change the hardhat.config.js file as follows:

// .... some tasks above this

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: '0.8.4',

  paths: {
    sources: './solidity/contracts',
    artifacts: './src/artifacts',
  },
};

You can also change the add a tests property if you want to separate your smart contract tests from the application ones.

Configure networks in Hardhat

By default, Hardhat will target its own network that we can run locally but if we decide to use another local network like Ganache, we can configure it by adding it in the networks section of the configuration file:

// .... some tasks above this

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: '0.8.4',

  paths: {
    sources: './solidity/contracts',
    artifacts: './src/artifacts',
  },
  networks: {
    hardhat: {
      chainId: 1337,
    },
    ganache: {
      chainId: 5777,
      url: 'http://127.0.0.1:7545',
    },
  },
};

TAGS


If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee