๐Ÿš€ Your Journey into Web3 Starts Now: A Beginner's Guide

Rahul RoyRahul Roy
6 min read

Welcome to the new internet! Web3 is all about decentralization, blockchain technology, and giving power back to the users. If you've been curious about this exciting space but didn't know where to start, you're in the right place. In this guide, we'll build and deploy a simple "Greeter" smart contract on a local blockchain.

Here's a little glimpse of what you'll be able to do by the end of this tutorial: interact with a deployed smart contract right from your terminal!

Let's get started! ๐Ÿ’ป


Prerequisites

Before we dive in, make sure you have these tools installed. They're essential for blockchain development.

  • Node.js: You'll need Node.js (version 18 or later). It comes with npm (Node Package Manager), which we'll use to manage our project's packages. You can download it from nodejs.org.

  • A Code Editor: Any text editor will work, but Visual Studio Code (VS Code) is highly recommended for its great features and extensions for developers.

  • MetaMask: A browser-based crypto wallet. We won't use it directly in this terminal-based tutorial, but it's fundamental to Web3, so go ahead and install the MetaMask extension for your browser.


Step 1: Setting Up Your Development Environment

We'll use Hardhat, an amazing development environment that makes building on Ethereum a breeze. It lets you compile, deploy, test, and debug your code.

First, create a new folder for your project, navigate into it, and initialize an npm project. Open your terminal and run these commands:

mkdir my-web3-project
cd my-web3-project
npm init -y

Next, let's install Hardhat:

npm install --save-dev hardhat

Now, run Hardhat to create a sample project:

npx hardhat

You'll be prompted with a few questions. Choose the following options:

  1. What do you want to do? โ†’ Create a JavaScript project

  2. Hardhat project root: โ†’ Press Enter to accept the default.

  3. Do you want to add a .gitignore? โ†’ yes

Hardhat will create a simple project structure for you. You're all set! ๐ŸŽ‰


Step 2: Writing Your First Smart Contract

A smart contract is a program that runs on the blockchain. It's like the backend logic for a decentralized application (dApp).

Hardhat has already created a sample contract for us. Let's look at it. Open the file contracts/Lock.sol in your code editor. It's a bit complex for a first timer, so let's replace its content with something simpler.

Delete everything in Lock.sol, rename the file to Greeter.sol, and paste the following code into it:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

/**
 * @title Greeter
 * @dev A simple smart contract that stores and retrieves a greeting.
 */
contract Greeter {
    string private greeting;

    // The constructor is called only once when the contract is deployed.
    // It sets the initial greeting message.
    constructor(string memory _initialGreeting) {
        greeting = _initialGreeting;
    }

    // A "view" function that reads data from the blockchain. It doesn't cost any gas.
    function greet() public view returns (string memory) {
        return greeting;
    }

    // A function that writes data to the blockchain. This will cost gas.
    function setGreeting(string memory _newGreeting) public {
        greeting = _newGreeting;
    }
}

This simple contract does two things:

  1. greet(): Returns a greeting message stored on the blockchain.

  2. setGreeting(): Allows us to change that greeting message.


Step 3: Compiling and Deploying the Contract

Before deploying, we need to compile our Solidity code into bytecode that the Ethereum Virtual Machine (EVM) can understand.

Run this command in your terminal:

npx hardhat compile

If everything is correct, you'll see a Compilation finished successfully message.

Now, let's write a script to deploy our Greeter contract. Hardhat created a sample deployment script at scripts/deploy.js. Let's modify it for our Greeter contract.

Replace the contents of scripts/deploy.js with this code:

// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
const hre = require("hardhat");

async function main() {
  const initialGreeting = "Hello, Web3 World!";

  // Get the contract factory for our Greeter contract
  const greeterFactory = await hre.ethers.getContractFactory("Greeter");

  // Deploy the contract with an initial greeting
  const greeter = await greeterFactory.deploy(initialGreeting);

  // Wait for the deployment to be confirmed
  await greeter.waitForDeployment();

  console.log(
    `Greeter with initial greeting "${initialGreeting}" deployed to ${greeter.target}`
  );
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

This script uses ethers.js (a library included with Hardhat) to deploy our Greeter contract.

Now, let's spin up a local Hardhat blockchain and deploy our contract to it. Run this command:

npx hardhat run scripts/deploy.js --network localhost

You should see a success message with the contract's address, something like this:

Greeter with initial greeting "Hello, Web3 World!" deployed to 0x5FbDB2315678afecb367f032d93F642f64180aa3

Congratulations! You've just deployed your first smart contract to a local blockchain! ๐Ÿฅณ


Step 4: Interacting with Your Contract

What good is a deployed contract if you can't interact with it? Let's write a simple script to call its functions.

Create a new file named interact.js inside your scripts folder and add the following code. Remember to replace'YOUR_CONTRACT_ADDRESS' with the address you got in the previous step.

const hre = require("hardhat");

// Replace with your deployed contract address
const CONTRACT_ADDRESS = "0x5FbDB2315678afecb367f032d93F642f64180aa3";

async function main() {
    // Get the Greeter contract instance
    const greeter = await hre.ethers.getContractAt("Greeter", CONTRACT_ADDRESS);

    // 1. Read the initial greeting
    console.log("Reading initial greeting...");
    const initialGreeting = await greeter.greet();
    console.log(`Current Greeting: "${initialGreeting}"`);

    console.log("\n-----------------------------------\n");

    // 2. Update the greeting
    const newGreeting = "GM, Web3 Devs!";
    console.log(`Updating greeting to "${newGreeting}"...`);
    const tx = await greeter.setGreeting(newGreeting);

    // Wait for the transaction to be mined
    await tx.wait();
    console.log("Greeting updated successfully!");

    console.log("\n-----------------------------------\n");

    // 3. Read the new greeting to confirm
    console.log("Reading new greeting...");
    const updatedGreeting = await greeter.greet();
    console.log(`New Greeting: "${updatedGreeting}"`);
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

Now, run the script to interact with your contract on the local network:

npx hardhat run scripts/interact.js --network localhost

The output will show you the step-by-step interaction: reading the initial greeting, updating it, and then reading the new one.

Reading initial greeting...
Current Greeting: "Hello, Web3 World!"

-----------------------------------

Updating greeting to "GM, Web3 Devs!"...
Greeting updated successfully!

-----------------------------------

Reading new greeting...
New Greeting: "GM, Web3 Devs!"

What's Next?

You did it! You've successfully set up a development environment, written, compiled, deployed, and interacted with a smart contract. This is the fundamental workflow for all blockchain development.

From here, you can explore:

  • Building a Frontend: Connect a web interface (using React, Vue, etc.) to your smart contract using ethers.js or web3.js.

  • More Complex Contracts: Learn about tokens (ERC-20), NFTs (ERC-721), and more complex application logic.

  • Testing: Hardhat has a powerful testing framework. Explore writing automated tests for your contracts.

  • Deploying to a Testnet: Deploy your contract to a public test network like Sepolia to share it with the world.

Welcome to the future of the Web3. Keep building! ๐Ÿ› ๏ธ

0
Subscribe to my newsletter

Read articles from Rahul Roy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul Roy
Rahul Roy

As a full-stack developer, I have a wide range of skills and a passion for making innovative web applications. I know front-end technologies like HTML, CSS, JavaScript, and React, which helps me create engaging user interfaces that provide a great user experience. On the back end, I work with languages such as Java and Python to build strong server-side logic and APIs. My experience in Web3, decentralized technologies, and data science gives me a modern, forward-looking view on my projects. I have a problem-solving approach and a strong desire to learn, so I keep up with the latest trends in the industry and aim to deliver the best solutions. I also take part in tech communities by joining hackathons, workshops, and collaborative projects. My ability to smoothly blend front-end and back-end elements enables me to create consistent and high-performing applications that make a lasting impression.