Deploying smart contracts is a foundational skill in the Ethereum ecosystem. However, it can be daunting for beginners. This comprehensive guide will teach you how to deploy a simple smart contract to the Sepolia Ethereum test network with detailed steps, best practices, and troubleshooting tips.

Prerequisites

Before we begin, make sure you have:

  • Node.js (version 18.0.0 or higher)
  • npm (Node Package Manager): Included with Node.js for running JavaScript/TypeScript tools and packages.
  • A code editor (VS Code recommended)
  • Metamask: An Ethereum wallet with some Sepolia ETH. Get test ETH from Sepolia faucets like this one. Paste your Metamask wallet address and start mining to receive test Ethereum (sepETH) for gas fees.
  • An Infura account for API access.
  • An Etherscan account for exploring and verifying contracts.

Initial Setup

First, let's set up our development environment:

1) Install Node.js and npm:

Download from Node.js official site.

2) Verify the installation:

   node --version
   npm --version

3) Create a new project directory:

   mkdir my-smart-contract
   cd my-smart-contract

Installing Hardhat

1) Initialize a new npm project:

   npm init -y

2) Install Hardhat and related dependencies:

   npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox dotenv

Project Initialization

Run the following command to initialize Hardhat:

npx hardhat init

Select "Create a JavaScript project" when prompted.

Your project structure will look like this:

my-smart-contract/
├── contracts/
│   └── Lock.sol
├── scripts/
│   └── deploy.js
├── test/
│   └── Lock.js
├── hardhat.config.js
├── package.json
└── .gitignore

Next Steps

1) Create a .env file in your project root:

   SEPOLIA_RPC_URL=your_sepolia_url
   PRIVATE_KEY=your_wallet_private_key
   ETHERSCAN_API_KEY=your_etherscan_api_key

2) Update hardhat.config.js:

   require("@nomicfoundation/hardhat-toolbox");
   require('dotenv').config();

   console.log('Environment variables loaded:');
   console.log('INFURA_API_KEY:', process.env.INFURA_API_KEY ? 'Present' : 'Missing');
   console.log('PRIVATE_KEY:', process.env.PRIVATE_KEY ? 'Present' : 'Missing');
   console.log('ETHERSCAN_API_KEY:', process.env.ETHERSCAN_API_KEY ? 'Present' : 'Missing');

   module.exports = {
     solidity: "0.8.28",
     networks: {
       hardhat: {},
       sepolia: {
         url: `https://sepolia.infura.io/v3/${process.env.INFURA_API_KEY}`,
         accounts: [`0x${process.env.PRIVATE_KEY}`]
       }
     },
     etherscan: {
       apiKey: process.env.ETHERSCAN_API_KEY
     }
   };

3) Write your first smart contract:

Create contracts/Storage.sol:

   // SPDX-License-Identifier: MIT
   pragma solidity ^0.8.28;

   contract Storage {
       uint256 private number;
       event NumberChanged(uint256 newNumber);

       function store(uint256 _number) public {
           number = _number;
           emit NumberChanged(_number);
       }

       function retrieve() public view returns (uint256) {
           return number;
       }
   }

4) Create test/Storage.test.js:

   const { expect } = require("chai");

   describe("Storage", function() {
     let storage;
     let owner;

     beforeEach(async function() {
       const Storage = await ethers.getContractFactory("Storage");
       storage = await Storage.deploy();
       [owner] = await ethers.getSigners();
     });

     it("Should store and retrieve a number", async function() {
       await storage.store(42);
       expect(await storage.retrieve()).to.equal(42);
     });

     it("Should emit event when storing number", async function() {
       await expect(storage.store(42))
         .to.emit(storage, "NumberChanged")
         .withArgs(42);
     });
   });

5) Run the test:

   npx hardhat test

6) Create scripts/deploy.js:

   async function main() {
       console.log("Deploying Storage Contract...");
       const Contract = await ethers.getContractFactory("Storage");
       const contract = await Contract.deploy();
       await contract.waitForDeployment();
       const address = await contract.getAddress();
       console.log("Contract deployed to:", address);
   }

   main()
       .then(() => process.exit(0))
       .catch((error) => {
           console.error(error);
           process.exit(1);
       });

7) Deploy and verify your contract:

   npx hardhat run scripts/deploy.js --network sepolia
   npx hardhat verify --network sepolia <CONTRACT_ADDRESS>

Verifying the Deployment

1) Visit Sepolia Etherscan.

2) Enter your contract address in the search bar.

3) Verify the source code in the Contract tab.

4) Use the Read Contract and Write Contract sections to interact with your contract.

Conclusion

Congratulations! You have successfully deployed your first smart contract on the Sepolia Ethereum test network. This setup equips you with the tools needed to explore Ethereum development further.

Happy coding! 🚀

Please share your thoughts in the comments if you found this guide helpful. Check my GitHub repo for this tutorial here.

Author Of article : Showkot Hossain Read full article