Start Here
Hardhat

Creating Your First DApp Using Apechain and Hardhat

The goal of this project is to deploy a contract and create a basic front-end interface for interacting with it. From there, you have the freedom to expand and enhance the project with your own ideas and creativity!

What is Hardhat?

Hardhat is a development environment for Ethereum that helps developers manage and automate the common tasks involved in building smart contracts and decentralized applications. It can directly interact with Caldera's Ethereum API, allowing for the deployment of smart contracts into the Caldera network.

Additionally, Hardhat is a comprehensive set of tools for creating Ethereum-based software, which includes various components that aid in editing, compiling, debugging, and deploying smart contracts and decentralized applications. All of these components work together to create a complete development environment.

In this guide we will see how you can build a token wallet dApp using Hardhat and Apechain.

Prerequisites

Basic Knowledge:


Development Environment:

  • Node.js and npm/yarn: Installed from Node.js (opens in a new tab).

  • Hardhat: Development environment for Ethereum.

    • Install with:
    npm install --save-dev hardhat
  • Metamask (opens in a new tab) A crypto wallet browser extension also available on mobile.

  • Ethers.js (opens in a new tab) Library to interact with Ethereum.

    npm install ethers
  • OpenZeppelin Contracts: Secure smart contract library.

    • Install with:
    npm install @openzeppelin/contracts

Step-by-Step Guide

Step 1: Set Up Hardhat Project

  1. Initialize a new Hardhat project:
mkdir helloApe
cd helloApe
npx hardhat

also run

npm i dotenv

We will use an .env file to hold our private key and pass it into our hardhat.config.js file.

Once installed, at the root create a file named .env

You will be prompted with questions in your terminal. You can simply choose the default options, which will generate a basic code template for you. While you can experiment with this template, for the purpose of this guide, we'll focus on making a few specific changes to some files.

Before we move ahead with the guide, here’s an example of how the folder structure would look like:

helloApe/
├── contracts/
│   └── Lock.sol
├── ignition/module
│   └── Lock.js
├── node_modules
├── test/
│   └── Lock.js
├── .gitignore
├── hardhat.config.js
├── package-lock.json
├── package.json
├── .env
├── README.md

Step 2: Write the Token Contract

Inside your Lock.sol file, delete the existing boilerplate code and then copy and paste the code below. This is a simple Solidity file that defines a string ‘greeting’ and a function that returns the string.

    
 // SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
 
contract HelloApe {
    string public greeting = "Hello, Apes!";
 
    function greet() public view returns (string memory) {
        return greeting;
    }
}

Step 3: Update your ignition file

Open your Lock.js file which you can find by navigating to ignition folder and then module folder.

This code defines a Hardhat Ignition module called "HelloModule" that deploys the "HelloApe" contract and returns the deployed instance as hello.

You can just copy this and paste into your file. Also note that you can rename files, just keep it consistant throughout the project.

async function main() {
    const [deployer] = await ethers.getSigners();
    console.log("Deploying contracts with the account:", deployer.address);
 
    const Token = await ethers.getContractFactory("Token");
    const token = await Token.deploy(1000000);
 
    console.log("Token deployed to:", token.address);
}
 
main()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });
 

Step 4: Configure Hardhat for Apechain

  1. Modify hardhat.config.js to include necessary plugins and configurations:

    Notice we are adding require('dotenv').config(); and accounts: [process.env.PRIVATE_KEY] to pass out private key in.

    require("@nomicfoundation/hardhat-toolbox");
    require('dotenv').config();
     
    /** @type import('hardhat/config').HardhatUserConfig */
    module.exports = {
    solidity: "0.8.17",
    networks: {
        apechain: {
         url: "https://curtis.rpc.caldera.xyz/http",
        accounts: [process.env.PRIVATE_KEY], 
        },
    },
    };

    inside of your .env file add the following

    PRIVATE_KEY=YOUR KEY HERE WITH NO QUOTES
    💡
    Ensure your .gitignore file has .env added

Step 5: Compile and Deploy

  1. Compile the contract:

    npx hardhat compile
  2. Deploy the contract to Apechain:

    npx hardhat ignition deploy ./ignition/modules/Lock.js --network apechain    
    💡
    Keep the deployed contract address, this will be needed for the frontend.

Step 6: Set Up Frontend with React

  1. Initialize a new React project within the same folder:

    npx create-react-app frontend
    cd frontend
    npm install ethers
  2. Grab your ABI

To connect to the smart contract, you'll need the contract's ABI. This can be found in the artifacts folder, which is automatically generated when you deploy your smart contract. To locate it, navigate to the artifacts folder, then to the contract folder. Find the JSON file (in our case, it's named HelloApe.json), copy it, and paste it into the src folder of your frontend project.

helloApe/
├── artifacts/
│   └──contracts/
│    └── HelloApe.json
├── cache/
├── contracts/
├── ignition/module
├── frontend/
│   └── src
│       └── App.js
│       └── HelloApe.json
├── node_modules
├── test/
├── .gitignore
├── hardhat.config.js
├── package-lock.json
├── package.json
├── .env
├── README.md
  1. Update App.js
import { useState } from "react";
import { ethers } from "ethers";
import Contract from "../src/HelloApe.json";
 
const tokenAddress = "YOUR_CONTRACT_ADDRESS";
 
function App() {
  const [userAddress, setUserAddress] = useState("");
  const [greeting, setGreeting] = useState("");
 
  async function getGreeting() {
    if (typeof window.ethereum !== "undefined") {
      const [account] = await window.ethereum.request({
        method: "eth_requestAccounts",
      });
      setUserAddress(account);
 
      const provider = new ethers.BrowserProvider(window.ethereum);
      const contract = new ethers.Contract(
        tokenAddress,
        Contract.abi,
        provider
      );
      const greetingFromContract = await contract.greeting();
      setGreeting(greetingFromContract);
    }
  }
 
  return (
    <div className="App">
      <header className="App-header">
        <h2>{userAddress}</h2>
        <h2>{greeting}</h2>
        <button onClick={() => getGreeting()}>Click</button>
      </header>
    </div>
  );
}
 
export default App;
  1. Update your CSS

Navigate to your App.css file, delete the boilerplate and add the following

.App {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  text-align: center;
}
 
.App-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
 
h2 {
  margin: 10px 0;
}
 
button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 20px;
}
  1. Run the Frontend

Start the React app: Make sure you are in your frontend directory and then run the following command

npm start

Your React application should now be running, and you can interact with the token wallet dApp through your browser!

Conclusion

In this guide, you have learned how to build a simple dApp using Hardhat and React, integrated with the Apechain network. By following the step-by-step instructions, you have set up a Hardhat project, written a basic contract, deployed it to Apechain, and created a React frontend to interact with the contract.