How to Deploy Smart Contracts Using Hardhat: A Step-by-Step Guide
This guide will walk you through deploying a smart contract using Hardhat.
Last updated
This guide will walk you through deploying a smart contract using Hardhat.
Last updated
Before we begin, make sure you have the following:
Node.js installed (version 12.0.0 or later).
NPM or Yarn.
.
Basic knowledge of Solidity and smart contracts.
Download Node.js from the official site and follow the instructions for installation. This will also install NPM (Node Package Manager), which is needed to install Hardhat and other dependencies.
Open a terminal and create a new directory for your project, then navigate:
Initialize an empty project and install Hardhat:
Once the installation is complete, run Hardhat to initialize your project:
Hardhat will present a menu of options. Select Create an empty hardhat.config.js
for simplicity.
You’ll need to install a few additional libraries that will help with writing and deploying contracts:
ethers.js
helps interact with the Ethereum blockchain.
dotenv
allows you to store environment variables securely (e.g., private keys).
Create a folder named contracts
in the root of your project:
Inside the contracts
folder, create a new Solidity file, MyContract.sol
. Below is a simple example of an ERC20 token contract:
This contract creates an ERC20 token named "MyToken" with the symbol "MTK" and an initial supply of 1000 tokens.
In the root of your project, locate or create the hardhat.config.js
file. Configure it to deploy to a specific network. Add the following configuration:
PRIVATE_KEY
is your wallet private key. Do not expose it publicly
.
To securely store your API keys, create a .env file
in the root of your project:
Create a folder named scripts
and inside it, create a deploy.js
script:
In scripts/deploy.js
, add the following code:
Before deploying, compile your Solidity contract:
If everything is set up correctly, this should compile without errors.
Run the deployment script:
This command will deploy your contract to the Graphite network using the configuration provided in hardhat.config.js
.
After deployment, you can interact with your contract using ethers.js
. Here's an example of how to call a function on your contract:
Create a new script called interact.js
in the scripts
folder.
Run the script to interact with the contract:
Once the deployment is successful, Hardhat will print the contract address in the terminal. You can verify the contract on a by searching for the deployed contract address.