0% found this document useful (0 votes)
28 views22 pages

Till Hardhat Task and Hardhat Task Questions

Hardhat is an Ethereum development framework that facilitates compiling, deploying, testing, and debugging smart contracts with features like local network simulation and a robust testing framework. It allows users to automate tasks through its task runner and extend functionality via plugins. The document provides a comprehensive guide on installing Hardhat, writing smart contracts, deploying them, and interacting with Ethereum networks, including configuration details and example scripts.

Uploaded by

email.yashdaga81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views22 pages

Till Hardhat Task and Hardhat Task Questions

Hardhat is an Ethereum development framework that facilitates compiling, deploying, testing, and debugging smart contracts with features like local network simulation and a robust testing framework. It allows users to automate tasks through its task runner and extend functionality via plugins. The document provides a comprehensive guide on installing Hardhat, writing smart contracts, deploying them, and interacting with Ethereum networks, including configuration details and example scripts.

Uploaded by

email.yashdaga81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is HardHat

Hardhat is a powerful Ethereum development framework that simplifies tasks like compiling, deploying,
testing, and debugging smart contracts.

Why Use Hardhat?

● Local Ethereum network simulation.

● Robust Testing Framework

● Debugging tools for error resolution.

● Plugin ecosystem to enhance capabilities (hardhat-ethers).

Feature Hardhat Truffle Foundry

Local Yes Yes Yes


Network

Plugin Excellent Limited Basic


Support

Debuggin Robust Moderate Minimal


g

Core Functionality of Hardhat

Hardhat Runner

The main interface for interacting with Hardhat. It acts as a task runner, allowing users to automate
repetitive tasks in the development workflow.

Task and Plugins


Tasks: Each command executed in Hardhat is considered a task. Tasks can be built-in or user-defined,
enabling complex workflows.

Plugins: These extend Hardhat's functionality. Users can add plugins to customize their development
environment according to their needs.

Installing and Setting Hardhat

Install [Link]

Create a new directory for your project

```

mkdir my-hardhat-project

cd my-hardhat-project

```

Run npm init -y

Install Hardhat : “ npm install –save-dev hardhat ”

Create a project: npx hardhat

Select options like "empty project" or "sample project."

Verify folder creation and dependencies.

● Folder Structure:

○ contracts/: Store Solidity contracts.

○ scripts/: Deployment scripts.

○ test/: Unit testing scripts.

○ [Link]: Custom configuration.

● Example Configuration:

Acts as the project’s backbone, defining Solidity versions, network connections, and paths.
Writing a Smart Contract
Install [Link]

Open visual studio- create a folder in drive-In vs code open a folder-open new terminal in vs code

npm init //package manager , initializes new json files, like artifacts.. general
package configuration file for any [Link] project, including Hardhat projects

npm install --save-dev hardhat@^2.8.0 // used to install development dependencies in a [Link]

//project, --save-dev: This flag tells npm to add the installed


//package to the devDependencies section of your [Link] file

In [Link] projects, development dependencies (often referred


to as devDependencies) are packages essential for the development and
testing phases but not required in the production environment.

npx hardhat init // is used to quickly initialize a new Hardhat project in your current

//directory, setting up the basic file structure and configuration for


a //Hardhat-based project.

What do you want to do? · Create an empty [Link]


Config file created

add this command in hardhat [Link] file

require("@nomiclabs/hardhat-ethers")

npm install --save-dev @nomiclabs/hardhat-ethers ethers // provides the integration of [Link] with

Hardhat

//The @nomiclabs/hardhat-ethers plugin integrates the


[Link] library into the Hardhat development
environment, enabling seamless interaction with the
Ethereum blockchain. This integration simplifies tasks
such as contract deployment, testing, and interaction
within Hardhat projects.

npx hardhat node // is used to start a local Ethereum network, often referred
to //as a Hardhat Network, which is designed for development and
testing purposes. It allows you to deploy, test, and interact with smart
contracts in a local environment without needing access to the main
Ethereum network or a testnet like Rinkeby.

(it will not stop, click on split terminal)

Create two folders and files

In contracts- [Link]

In scripts- [Link]

Hardhat [Link]

/** @type import('hardhat/config').HardhatUserConfig */

require("@nomiclabs/hardhat-ethers")

[Link] = {
solidity: "0.8.28",

network:{

localhost:{

url:"[Link]

};

[Link]

pragma solidity ^0.8.0;

contract SimpleStorage {

uint public storedData;

function set(uint x) public {

storedData = x;}

function get() public view returns (uint) {

return storedData;

} }

[Link]

// Import Hardhat runtime environment

const hre = require("hardhat");

async function main() {

// 1. Get the ContractFactory for the contract

const SimpleStorage = await [Link]("SimpleStorage");

// 2. Deploy the contract (you can pass constructor arguments here if needed)

const simpleStorage = await [Link]();


// 3. Wait for the deployment to be mined

await [Link]();

[Link]("SimpleStorage deployed to:", [Link]);}

// Execute the main function

main().catch((error) => {

[Link](error);

[Link] = 1;});

npx hardhat compile

npx hardhat run scripts/[Link] //run like this if you have not mentioned localhost in

//[Link]

Add localhost
/** @type import('hardhat/config').HardhatUserConfig */
require("@nomiclabs/hardhat-ethers")
[Link] = {
solidity: "0.8.28",
network:{
localhost:{
url:"[Link]
}
}
};

Or run like this

npx hardhat run scripts/[Link] --network localhost

copy the deployed address in the code

//create [Link] in scripts folder

const hre = require("hardhat");

async function main() {

// Replace with your deployed contract's address

const deployedAddress = "0x5fbdb2315678afecb367f032d93f642f64180aa3";


// Get the contract factory and attach it to the deployed address

const simpleStorage = await [Link]("SimpleStorage",deployedAddress);

[Link]("Interacting with deployed SimpleStorage contract at:", deployedAddress);

await [Link](42);

// await [Link](); // Wait for the transaction to be mined

[Link]("Stored number set to 42.");

// Retrieve the stored number

const storedNumber = await [Link]();

[Link]("Retrieved stored number:", [Link]());

main()

.catch((error) => {

[Link](error);

[Link](1);

});

add [Link] in scripts file (for storing and retrieving data)

npx hardhat run scripts/[Link] --network localhost

Exercise:

1. Set the string and return it on console. ( do you need toString())

Explanation of [Link] (Solidity Smart Contract)

This is a basic Solidity smart contract named SimpleStorage that allows users to store and retrieve an
integer value on the Ethereum blockchain.
1. Solidity Version Declaration

pragma solidity ^0.8.0;

● Specifies that the contract is written for Solidity version 0.8.0 or later.

● Helps ensure compatibility with the correct compiler version.

2. Contract Definition

contract SimpleStorage {

● Declares the contract named SimpleStorage.

● A contract in Solidity is similar to a class in object-oriented programming.

3. State Variable

uint public storedData;

● Declares a state variable storedData of type uint (unsigned integer).

● public keyword:

o Generates an automatic getter function.

o Allows other contracts and users to access the variable.

4. set() Function (Store a Value)

function set(uint x) public {

storedData = x;

● A public function that allows users to store a number in storedData.

● Takes an unsigned integer (x) as an argument.

● Modifies the contract’s state by updating storedData with the new value.

🔹 Note: Since this function modifies the blockchain state, it costs gas to execute.
5. get() Function (Retrieve the Stored Value)

function get() public view returns (uint) {

return storedData;

● A public function that returns the stored value.

● The view keyword:

o Indicates that the function only reads blockchain data.

o Does not modify the state, so calling it is gas-free.

Explanation

[Link]

Explanation of [Link] (Hardhat Deployment Script)

This JavaScript script is used to deploy the SimpleStorage smart contract using Hardhat and [Link].

Step-by-Step Breakdown

1. Import Hardhat Runtime Environment

const hre = require("hardhat");

Imports the Hardhat Runtime Environment (hre).

Provides access to [Link] and other Hardhat functionalities.

2. Define the main() Function

async function main() {

Declares an async function to handle the contract deployment.

3. Get the Contract Factory

const SimpleStorage = await [Link]("SimpleStorage");

Retrieves the contract factory for SimpleStorage.

A contract factory is an abstraction used to deploy new contract instances.


The name ("SimpleStorage") must match the Solidity contract name.

4. Deploy the Contract

const simpleStorage = await [Link]();

Calls .deploy() to deploy the contract on the blockchain.

If the contract has constructor parameters, they would be passed inside .deploy(args).

Example with constructor:

const simpleStorage = await [Link](100);

5. Wait for Deployment Confirmation

await [Link]();

Waits until the deployment transaction is mined and confirmed on the blockchain.

6. Log the Deployed Contract Address

[Link]("SimpleStorage deployed to:", [Link]);

Prints the contract's address on the blockchain.

This address is needed for interacting with the contract.

7. Handle Errors

main().catch((error) => {

[Link](error);

[Link] = 1;

});

If an error occurs:

Logs the error message.

Sets [Link] = 1 (indicating failure).

What Happens When You Call getContractFactory()?

● Loads Compiled Artifacts:

○ The getContractFactory method loads the compiled contract artifacts from Hardhat's
artifacts/ directory.
● Creates a Factory Object:

○ Based on the compiled artifacts, getContractFactory creates a Contract Factory object.

○ The Contract Factory is a helper object that allows you to:

■ Deploy a new instance of the contract to the blockchain.

■ Specify constructor arguments if the contract requires them.

eg: const simpleStorage = await [Link](arg1, arg2);

Hardhat Networks
Hardhat provides multiple network options to deploy and interact with Ethereum smart
contracts.

1. Hardhat Network (Default)

● Why Use It?

o Fast Testing: Transactions are mined instantly, making it ideal for quick unit tests
and debugging.

o Advanced Debugging: Provides detailed stack traces and supports Solidity


[Link], making it easier to debug contracts.

o Ephemeral State: Resets the blockchain state each time you restart, ensuring
clean test environments.

● When to Use It?

○ Writing and running automated unit tests.

○ Debugging smart contracts.

○ Initial development before deploying to persistent networks.

2. Localhost Network :

● local blockchain network for development and testing.

● Typically used to connect external tools (like Metamask, frontend apps,


or scripts) to your local development environment.

● Persists the blockchain state until the process is terminated.


[Link] = {

networks: {

localhost: {

url: "[Link]

},

},

};

3. Ethereum Mainnet
● The live Ethereum blockchain used for deploying production smart contracts.

● Requires real ETH for transactions.

[Link] = {

networks: {

mainnet: {

url: "[Link]

accounts: [`0x${PRIVATE_KEY}`], // Replace with your private key

},

},

};

command

npx hardhat run scripts/[Link] --network mainnet

4. Testnets (Goerli, Sepolia, etc.)


● Public Ethereum test networks for testing smart contracts before deploying
to Mainnet.

● Transactions require test ETH, which can be obtained from faucets.

o When to Use Them?

● Testing smart contracts in an environment that closely resembles Mainnet.

● Sharing contracts with other developers or testers for feedback.

● Ensuring contracts function as intended under live network conditions.

[Link] = {

networks: {

goerli: {

url: "[Link]

accounts: [`0x${PRIVATE_KEY}`], // Replace with your private key

},

},

};

Interacting with external network


Step:1 Alchemy

Using Alchemy with Hardhat

Alchemy is a blockchain infrastructure provider that offers fast, reliable, and scalable access to
Ethereum and other blockchains. You can use Alchemy with Hardhat for faster RPC calls,
archival data access, transaction simulations, and real-time event listening.

Follow these steps:

Apps-netwok-ethereum-next-create app—sepolia- copy url


Step:2 Metamask

Follow these steps:

Install-add extension- ping-create wallet-secure my wallet-show test network-sepolia

MetaMask is a crypto wallet and gateway to blockchain apps. It allows users to store, send, and
receive cryptocurrencies, interact with decentralized applications (dApps), and connect to
Ethereum and other blockchains directly from their browser or mobile device.

🔹 Available as:
Browser extension (Chrome, Firefox, Brave, Edge)
Mobile app (iOS, Android)

Step : 3 Sepolia faucet

Sepolia is an Ethereum testnet used for testing smart contracts before deploying them on
Ethereum Mainnet. Where we can get the dummy ethers.

Follow these steps:

Copy public address from metamask-receive ethers

Step 4: Metamask -copy private key

Seploia ether scan-for verifying ethere are transferred

It allows you to:

Check transactions (TxID, gas fees, confirmations)


View wallet balances and token holdings
Track smart contracts (deployment, verification, execution)

Monitor block production and network status

Add .env file

RPC_URL = [Link]

PRIVATE_KEY=1c37d1d09d926bdb184b07d18325f0bc01dbfa3d0aad6285c0e6decfa00367b8
In [Link]

/** @type import('hardhat/config').HardhatUserConfig */

require("@nomiclabs/hardhat-ethers")

require("dotenv").config();

[Link] = {

solidity: "0.8.28",

networks:{

localhost:{

url:"[Link]

},

sepolia:{

url:[Link].RPC_URL,

accounts:[`0x${[Link].PRIVATE_KEY}`] //ensures private kay does not have 0x already

};

If your .env private key already starts with 0x, then just use:

accounts: [[Link].PRIVATE_KEY]

to avoid double 0x prefixes.

In VS code terminal run>>

npm i dotenv

npx hardhat run scripts/[Link] --network sepolia


Hardhat Tasks

Commands
npm init

npm install --save-dev hardhat

npx hardhat init

What do you want to do? · Create an empty [Link]

Config file created

add this command in hardhat [Link] file


require("@nomiclabs/hardhat-ethers")

npm install --save-dev @nomiclabs/hardhat-ethers ethers

npx hardhat node

(it will not stop, click on split terminal)

npx hardhat accounts --network localhost

Explanation

. task("accounts", "Prints the list of accounts", async (_, hre) => { ... })

task(): This is a Hardhat function used to define custom tasks that you can run from the
command line using npx hardhat <task-name>. You can create any number of tasks for different
purposes in your Hardhat project.

"accounts": The name of the custom task. This is the name you'll use to invoke this task from
the command line, e.g., npx hardhat accounts.

"Prints the list of accounts": This is a description of the task. When you run npx hardhat --help,
it will show the name and description of this task, so users can understand what the task does.

async (_, hre): The function that will be executed when you run the task.

async: The function is asynchronous because we need to interact with the blockchain and
retrieve data (accounts) that requires async operations.

_: This parameter represents any arguments passed to the task (none in this case), so we use _
to indicate that we're not using it.

hre: Stands for Hardhat Runtime Environment. It is an object that provides access to various
Hardhat tools, such as [Link], [Link], and more. In this case, we're using [Link] to
interact with the Ethereum network.

2. const accounts = await [Link]();


[Link]: This is part of the Hardhat Runtime Environment. The ethers object provides utility
functions to interact with Ethereum, including signing transactions, getting signers, etc.

getSigners(): This is a function that returns an array of signers (accounts). These are the
accounts available in the Hardhat local network or the configured network. A signer in
Ethereum represents an account that can sign transactions (i.e., a wallet address).

await: Since getSigners() is an asynchronous function, we use await to wait for the function to
resolve and return the list of signers. This ensures that the list of accounts is available before we
proceed.

The result is assigned to the accounts variable, which now contains an array of account objects.

3. for (const account of accounts) { [Link]([Link]); }

for (const account of accounts): This is a for...of loop, which is used to iterate over each
account in the accounts array. Each account is an instance of an Ethereum account with
properties like address, balance, etc.

[Link]: The address property of an account represents the Ethereum address


associated with that account (e.g., 0xAbc123...).

[Link]([Link]);: This line logs the address of each account to the console.

The loop will print all the account addresses that were retrieved by [Link]().

Exercise

[Link] Hardhat Task to Print Account Addresses and balances// cmds same as
previous program

require("@nomiclabs/hardhat-ethers")

// Task to print accounts with balances

task("accounts", "Prints the list of accounts and their balances", async (_, hre) => {

const accounts = await [Link]();


for (const account of accounts) {

const balance = await [Link]([Link]);

[Link](`Address: ${[Link]} | Balance: $


{[Link](balance)} ETH`);

});

[Link] = {

solidity: "0.8.28",

network:{

localhost:{

url:"[Link] } }};

Explanation

for (const account of accounts):

● This is a for...of loop that iterates over each account in the accounts array.
This array was likely populated earlier using [Link](), which
returns an array of Ethereum account signers.

● Each account object in this loop contains details about a specific Ethereum
address.

2. const balance = await [Link]([Link]);:


● [Link]: This refers to the ethers object in the Hardhat Runtime
Environment (hre). The ethers library is an essential utility that Hardhat
uses to interact with Ethereum networks.

● provider: The provider is an object responsible for interacting with the


Ethereum network. It handles reading data from the network (e.g.,
balances, smart contract states) and is also used to send transactions. In
this case, the provider is the connection to the Ethereum network (whether
local or a live network).

● getBalance([Link]): This function is used to retrieve the balance


(in wei) of the given account address.

o The getBalance() function returns a BigNumber object that


represents the account’s balance in wei (smallest unit of Ether).

● await: This is used to wait for the asynchronous function getBalance() to


return the balance before continuing with the next command.

o Note: getBalance() is an async function because it requires fetching


data from the blockchain, which takes time.

3. if ([Link](0)):

● [Link](0): This checks if the balance (which is a BigNumber object) is


greater than 0.

o The gt() function is a method available on BigNumber objects that


checks if the value is greater than the specified number (0 in this
case).

o If the balance is greater than 0, the code inside the if statement will
execute.
4. [Link](Address: ${[Link]} | Balance: $
{[Link](balance)} ETH);:

● [Link](): This is used to print information to the console.

● ${[Link]}: This template literal embeds the [Link] into


the string, displaying the account's Ethereum address.

● [Link](balance):

o This utility function converts the balance from wei (the smallest unit
of Ether) to ether (the standard Ether unit).

o formatEther() takes the balance (which is a BigNumber in wei) and


converts it to a human-readable format (in Ether).

● ETH: This is the unit of Ether and is appended to the output to indicate that
the balance is in Ether.

The line prints out the address and balance of the account only if the balance is
greater than 0.

1 ETH = 1,000,000,000,000,000,000 wei (1 quintillion wei).

3. Custom Hardhat Task to Print the connected network name // commands same
as previous program

4. print accounts with a balance greater than 0.

require("@nomiclabs/hardhat-ethers")

const { task } = require("hardhat/config");

// Task to print accounts with balances > 0


task("accounts", "Prints the list of accounts with balances greater than 0", async
(_, hre) => {

const accounts = await [Link]();

// Loop through the accounts and filter out accounts with 0 balance

for (const account of accounts) {

const balance = await [Link]([Link]);

// Check if balance is greater than 0

if ([Link](0)) {

[Link](`Address: ${[Link]} | Balance: $


{[Link](balance)} ETH`);

});

[Link] a custom task to to print connected network name, chain id and block number

Artifacts Troubleshooting in Hardhat

In Hardhat, artifacts are the compiled output files of smart contracts. These files contain ABI
(Application Binary Interface), bytecode, and metadata that are required for contract deployment and
interaction.

You might also like