Deploying a smart contract using Hardhat involves writing a deployment script, configuring the network, and running the script to deploy the contract.
1. Set Up Your Hardhat Project
If you haven’t already set up a Hardhat project, follow these steps:
a. Create a new project directory:
mkdir my-hardhat-project
cd my-hardhat-project
b. Initialize a new npm project:
npm init -y
c. Install Hardhat:
npm install --save-dev hardhat
d. Create a new Hardhat project:
npx hardhat
Follow the prompts to create a basic project.
2. Write Your Smart Contract
In the contracts/
directory, create a Solidity contract. For example, create MyContract.sol
:
contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
uint256 public value;
constructor(uint256 _value) {
value = _value;
}
function setValue(uint256 _value) public {
value = _value;
}
function getValue() public view returns (uint256) {
return value;
}
}
This contract is simple: it stores an unsigned integer and allows updating and retrieving that value.
3. Configure the Hardhat Network and Other Networks
Now, you need to configure Hardhat to deploy the contract to an Ethereum network (local Hardhat network, testnet, or mainnet). In hardhat.config.js
, add network configuration.
Install necessary plugins:
npm install --save-dev @nomiclabs/hardhat-ethers ethers
Configure hardhat.config.js
:
require("@nomiclabs/hardhat-ethers");
module.exports = {
solidity: "0.8.0", // Your Solidity compiler version
networks: {
hardhat: {}, // Local Hardhat network (default)
ropsten: {
url: `https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID`, // Use Infura or Alchemy for connecting to a testnet
accounts: [`0xYOUR_PRIVATE_KEY`]
},
mainnet: {
url: `https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID`, // Use for mainnet deployment
accounts: [`0xYOUR_PRIVATE_KEY`]
},
},
};
Replace YOUR_INFURA_PROJECT_ID
with your Infura (or Alchemy) project ID and YOUR_PRIVATE_KEY
with your Ethereum private key. For security, use .env
files to manage sensitive information like private keys.
You can also use dotenv
to load environment variables from a .env
file:
npm install dotenv --save
Then, in your hardhat.config.js
:
require("dotenv").config();
module.exports = {
solidity: "0.8.0",
networks: {
ropsten: {
url: `https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`,
accounts: [`0x${process.env.PRIVATE_KEY}`]
},
},
};
Create a .env
file to store sensitive data:
INFURA_API_KEY=your_infura_project_id
PRIVATE_KEY=your_ethereum_private_key
4. Write the Deployment Script
In the scripts/
folder, create a deployment script. For example, deploy.js
.
scripts/deploy.js
async function main() {
// Get the deployer's account
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
// Compile the contract
const MyContract = await ethers.getContractFactory("MyContract");
// Deploy the contract
const myContract = await MyContract.deploy(42); // Pass an initial value (e.g., 42)
console.log("Contract deployed to address:", myContract.address);
// Wait for deployment to be mined
await myContract.deployed();
console.log("Contract deployed successfully!");
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
This script does the following:
- Gets the deployer's Ethereum account using
ethers.getSigners()
.
- Compiles the contract using
ethers.getContractFactory()
.
- Deploys the contract with an initial value (in this case,
42
).
- Waits for the contract to be mined.
5. Deploy the Contract
To deploy the contract, run the following command:
a. To deploy to the Hardhat local network (default)
npx hardhat run scripts/deploy.js --network hardhat
b. To deploy to a testnet (e.g., Ropsten)
npx hardhat run scripts/deploy.js --network ropsten
c. To deploy to the Ethereum mainnet
npx hardhat run scripts/deploy.js --network mainnet
6. Verify the Deployment
Once the contract is deployed, you will see the contract address in the terminal. You can interact with the contract through Hardhat's console, or use web3.js/ethers.js in a frontend application.
Example: Interacting with the deployed contract using Hardhat console
npx hardhat console --network ropsten
Then in the console, you can interact with the contract:
const contractAddress = "your_contract_address";
const myContract = await ethers.getContractAt("MyContract", contractAddress);
// Get the current value
let value = await myContract.getValue();
console.log(value.toString()); // Should log 42
// Set a new value
await myContract.setValue(100);
value = await myContract.getValue();
console.log(value.toString()); // Should log 100