This will generate a package.json file for managing dependencies and scripts.
2. Install Solidity and Hardhat Dependencies
Hardhat is a powerful development environment for compiling, deploying, and testing Ethereum smart contracts. Install Hardhat along with ethers.js for interacting with Ethereum, and the necessary plugins:
Hardhat: For development, testing, and deployment.
ethers.js: A library for interacting with Ethereum.
@nomiclabs/hardhat-ethers: A plugin that integrates Hardhat with ethers.js.
3. Create the Hardhat Configuration
Run Hardhat’s initialization command to generate the basic configuration and project files:
You will be prompted to select a task. Choose Create a basic sample project or Create an advanced project, depending on your needs. This will generate:
hardhat.config.js: Your Hardhat configuration file.
Sample contract, test, and script files.
4. Set Up the Folder Structure
5. Creating a Sample Solidity Contract
Inside the contracts/ folder, create a simple Solidity contract, e.g., MyContract.sol:
6. Creating a Deployment Script
In the scripts/ folder, create a deployment script (deploy.js):
7. Running the Deployment
To compile and deploy your contract locally:
Start a local Ethereum node using Hardhat:
Deploy your contract:
This will deploy your contract to a local test network.
8. Setting Up a Test File
In the test/ folder, create a test script (test.js) using Hardhat's testing framework and ethers.js:
9. Running the Tests
To run your tests:
10. Hardhat Network Configuration (Optional for Testnets)
To deploy on a real test network , configure your hardhat.config.js:
MySolidityProject/
├── contracts/ # Contains all the Solidity contracts
│ └── MyContract.sol # Example contract
├── scripts/ # Scripts for deployment and contract interaction
│ └── deploy.js # Script for contract deployment
├── test/ # Contains unit tests for smart contracts
│ └── test.js # Example test file
├── artifacts/ # Generated files (compiled contracts, ABIs, etc.)
├── cache/ # Cached files for faster compilation
├── node_modules/ # Installed npm packages
├── hardhat.config.js # Hardhat configuration file
└── package.json # Project dependencies and scripts
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
uint256 public value;
function setValue(uint256 _value) public {
value = _value;
}
function getValue() public view returns (uint256) {
return value;
}
}
npx hardhat run scripts/deploy.js --network localhost
const { expect } = require("chai");
describe("MyContract", function () {
it("Should set and get the correct value", async function () {
const MyContract = await ethers.getContractFactory("MyContract");
const myContract = await MyContract.deploy();
await myContract.deployed();
// Set a value
await myContract.setValue(42);
// Test the value
expect(await myContract.getValue()).to.equal(42);
});
});