DEV Community

Cover image for Building your First dApp on Linea (in under 10 min!)
Bap
Bap

Posted on

Building your First dApp on Linea (in under 10 min!)

Hey friends, 👋

Let’s create our first dApp in the next couple of minutes!

We will be building this project on the Linea Network. Linea is a layer 2 blockchain built on top of Ethereum. It leverages zk-rollup technology, which means it has higher transaction speed and reduces costs. 🏎️

As you begin this journey in Web3, or you are keen to learn about Linea, it is advisable to work on the testnet rather than the mainnet. The main difference is that the former uses “fake” ETH to develop your project (hence the name test), whereas the latter uses real ETH. 💸

In this article, we will create a smart contract for building a user profile with 2 simple functions: createProfile and getProfile. This is a common exercise, especially in building decentralised identity systems, managing access control, or even building social networking platforms!

With this in mind, shall we get into it?

Image description


🛠️ Step by Step

🧱 Requirements

  1. Create (or Log into) your MetaMask account.
  2. Click on the “Show Test Network” category and select Linea Sepolia Network.
  3. Get some free ETH from faucets → You can find these at Infura, Covalent, GetBlock or HackQuest.

1️⃣ Create Contract

  1. Head to Remix.
    • Remix already has all the environments set up, making it the fastest way for any first-timer to create a Solidity contract.
    • Kick things off by picking their default project template.
  2. Create a file under the contracts folder called ProfileCreator.sol
    • Copy and paste this code


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

contract ProfileCreator {

    // Hold the profile information
    struct Profile {
        string username;
        string email;
    }

    // Mapping from an address to a Profile
    mapping(address => Profile) public profiles;

    // Event will be emitted when a new profile is created
    event ProfileCreated(address indexed user, string username, string email);

    // Function to create a new profile
    function createProfile(string memory _username, string memory _email) public {
        // Storing the profile data in the mapping
        profiles[msg.sender] = Profile(_username, _email);

        // Emitting the event
        emit ProfileCreated(msg.sender, _username, _email);
    }

    // Function to retrieve profile data
    function getProfile(address _user) public view returns (Profile memory) {
        return profiles[_user];
    }
}


Enter fullscreen mode Exit fullscreen mode

This solidity contract creates Profile and our two main functions: createProfile and getProfile.

  1. Compile
    • Click Solidity Compiler on the left of your screen.
    • Make sure to pick London as the EVM version under Advanced Configurations (this will resolve EVM compatibility issues 🙃).
  2. Head to the Deploy and Run Transactions and connect your MetaMask wallet after picking the environment “Injected Provider - MetaMask”.
  3. Deploy 🎉
    • In the Deployed/Unpinned Contracts, you should now be able to input name, email for createProfile and retrieve that data under getProfile with your MetaMask address.

Note: You can copy your contract address generated after the deployment and head over to see it directly on Linea’s testnet explorer: https://sepolia.lineascan.build/


2️⃣ Build the Front End

  1. Create a project on your local machine: mkdir project_name
  2. Create the index.html file and paste and save the below code:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Profile Creator dApp</title>
        <script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
                type="application/javascript"></script>
    </head>
<body>
    <h1>Profile Creator dApp</h1>
    <div>
        <h2>Create Profile</h2>
        <input type="text" id="username" placeholder="Enter your username">
        <input type="email" id="email" placeholder="Enter your email">
        <button onclick="createProfile()">Create Profile</button>
    </div>
    <div>
        <h2>Get Profile</h2>
        <input type="text" id="userAddress" placeholder="Enter user address">
        <button onclick="getProfile()">Get Profile</button>
        <p id="profileInfo"></p>
    </div>
    <script>
        const contractAddress = 'INPUT_CONTRACT_ADDRESS_HERE';
        const contractABI = "INPUT_ABI_ARRAY_HERE";

        async function connect() {
            if (typeof window.ethereum !== 'undefined') {
                await ethereum.request({ method: 'eth_requestAccounts' });
                return new ethers.providers.Web3Provider(window.ethereum); 
            } else {
                alert('MetaMask is not installed!');
                throw new Error('MetaMask not found');
            }
        }
        async function createProfile() {
            const provider = await connect();
            const signer = provider.getSigner();
            const contract = new ethers.Contract(contractAddress, contractABI, signer);

            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;

            try {
                const tx = await contract.createProfile(username, email);
                await tx.wait();
                alert('Profile created successfully!');
            } catch (error) {
                console.error('Error creating profile:', error);
                alert('Failed to create profile.');
            }
        }

        async function getProfile() {
            const provider = await connect();
            const contract = new ethers.Contract(contractAddress, contractABI, provider);
            const userAddress = document.getElementById('userAddress').value;

            try {
                const profile = await contract.getProfile(userAddress);
                console.log("This is profile 0:", profile[0], "This is profile 1:",profile[1])
                document.getElementById('profileInfo').innerText = `Username: ${profile[0]}, Email: ${profile[1]}`;
            } catch (error) {
                console.error('Error getting profile:', error);
                alert('Failed to retrieve profile.');
            }
        }
    </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

This code creates a basic frontend and builds JS functions for connecting, creating a profile and getting the profile. Finally, this doc calls ether.js to connect with the contract (more on that later).

  1. Run on your terminal npm install -g lite-server
  2. Run lite-server
  3. Your browser should open up, displaying the front end. 🖼️

3️⃣ Connect Webpage to Smart Contract

  • Head back to Remix contract and copy your Contract address and ABI.
  • Get to your index.html file, locate the below and paste your contractAddress and contractABI.


        const contractAddress = "INPUT_CONTRACT_ADDRESS_HERE";
        const contractABI = "INPUT_ABI_ARRAY_HERE";


Enter fullscreen mode Exit fullscreen mode
  • This allows ether.js to connect this script with the contract you built.
  • The ABI array allows for your index.html to both send and call data.
  • You can now rerun your page, and you should be able to create and retrieve the profile successfully!

That's it! Congratulations on making it this far. 👏 If you are still struggling, we also made a short video displaying the entire process.

Click on the image below to redirect you there. 👇

Image description

You can also find the GitHub repo with access to the entire codebase here. ⭐️


We hope you enjoyed this short tutorial in building a dApp on the Linea Sepolia Network.

The mechanics would be very similar if you wanted to build on the mainnet - however, you would be paying real gas fees with real ETH. 😛

See you in the next one,

Bap

Top comments (4)

Collapse
 
tsitso_khaboh_cf225e20920 profile image
tsitso khaboh

As a beginner to programming.  I don't  understand  most of the stuff  yo did . But  I find  them very interesting   by just going  through the  code . I'm very interested in blockchain technology  as a developer or engineer  , I have even downloaded  it's roadmap.  The roadmap  seemed very complicated  to me but looking  at this . I start to realize  everything is possible  . This project  inspired me . Keep post more stuff like this .

Collapse
 
fernandezbaptiste profile image
Bap

Hey there! Glad you enjoyed the piece and I appreciate your comment (a lot!). Let me know how you get along! I’m always keen to see cool projects (regardless of your level). 🙂

Collapse
 
fernandezbaptiste profile image
Bap

Please share your own dApp project below, I'm always keen to see what you are building! 🙏🚀

Collapse
 
rohan_sharma profile image
Rohan Sharma

I'm unable to find my dApp project! 😑 I built it using Rust and Solana