Your First Dapp using Create ETH App

Rahul Ravindran

One of the biggest challenges for setting up a blockchain project is to get the project setup correctly. Create-eth-app is an open source tool that lets you create Ethereum-powered apps with a single command. It saves you the trouble of creating boilerplate code, and it provides a clean foundation for your Blockchain app.

If you want a quick summary about setting up a create eth app please checkout our youtube video:

Features of Create ETH App

Your environment will have everything you need to build a modern Ethereum-powered single-page React app:

  • Smooth project management via Yarn Workspaces
  • Everything included with Create React App: React, JSX, ES6, TypeScript and Flow syntax support
  • Template subgraph that indexes the events emitted by an ERC-20 contract
  • Minimalist structure for managing the smart contract ABIs and addresses
  • Hassle-free updates for the above tools with a single dependency

Installing Create Eth App

Create Eth app is an NPM package, so you’ll need to have atleast node v14. You can use nvm (macOS/Linux) or nvm-windows to switch Node versions between different projects. The project also uses yarn, so you need to have yarn installed as well, this is because Create Eth App relies on Yarn Workspaces, a feature not supported by Npm.

To setup up a project enter the following command on the terminal:

yarn create eth-app my-eth-app
cd my-eth-app

Learn more about the yarn create command yarn create <starter-kit-package> available in Yarn 0.25+_

Once the project is installed the directory structure should look something like this:

my-eth-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
└── packages
    ├── contracts
    │   ├── README.json
    │   ├── package.json
    │   └── src
    │       ├── abis
    │       │   ├── erc20.json
    │       │   └── ownable.json
    │       ├── addresses.js
    │       └── index.js
    ├── react-app
    │   ├── README.md
    │   ├── package.json
    │   ├── node_modules
    │   ├── public
    │   │   ├── favicon.ico
    │   │   ├── index.html
    │   │   └── manifest.json
    │   └── src
    │       ├── App.css
    │       ├── App.js
    │       ├── App.test.js
    │       ├── ethereumLogo.svg
    │       ├── index.css
    │       ├── index.js
    │       ├── serviceWorker.js
    │       └── setupTests.js
    └── subgraph
        ├── README.md
        ├── abis
        │   └── erc20.json
        ├── package.json
        ├── schema.graphql
        ├── src
        │   └── mappings
        │       ├── tokens.ts
        │       └── transfers.ts
        └── subgraph.yaml

create-eth-appsupports multiple frameworks: “react” and “vue”. You can run the following command:

 yarn create my-eth-app my-eth-app --framework react
 yarn create my-eth-app my-eth-app --framework vue

create-eth-app” also supports multiple established protocol templates.

  • React: aave, compound, default, kyber, maker, sablier-v1, synthetix, uniswap-v1, uniswap-v2
  • Vue: aave, compound, default, kyber, maker, sablier-v1, synthetix, uniswap-v1, uniswap-v2

To start the projet run

yarn react-app:start

Now out the box, we have two options to connect to our Ethereum blockchain:

Among other things the package has integration with Web3Modal once you click on connect wallet, you should see a popup to choose wallet providers:

Once you approve the request from your wallet, you should see you wallet address and an option to disconnect the wallet.

Understanding the packages

The packages folder contains 3 pacakges:

1. Contacts

This folder contains information about the contract your dapp connects to. This includes the contract address and contract ABI. Couple of dummy contracts are already included when you set up the project to help get you started.

In this example we will discuss a custom todo-app smart contract. To write and develop the smart contract we will use the REMIX IDE.

Please note that create-eth-app this is only for the frontend of app. If you need to create your own smart contract, you need to use another framework as well, like Hardhat or Truffle.

So lets create a new file called Todo.Sol

//Todo.sol

pragma solidity ^0.5.1;

// Creating a contract
contract Todo{

// Defining a structure to
// store a task
struct Task
{
string task;
bool isDone;
}

mapping (address => Task[]) private Users;

// Defining function to add a task
function addTask(string calldata _task) external
{
Users[msg.sender].push(Task({
    task:_task,
    isDone:false
    }));
}

// Defining a function to get details of a task
function getTask(uint _taskIndex) external view returns (Task memory)
{
Task storage task = Users[msg.sender][_taskIndex];
return task;
}

// Defining a function to update status of a task
function updateStatus(uint256 _taskIndex,bool _status) external
{
Users[msg.sender][_taskIndex].isDone = _status;
}

// Defining a function to delete a task
function deleteTask(uint256 _taskIndex) external
{
delete Users[msg.sender][_taskIndex];
}

// Defining a function to get task count.
function getTaskCount() external view returns (uint256)
{
return Users[msg.sender].length;
}
}

To compile the application, select the contract and click on the compile Todo.sol button under the compile tab:

Once the contract compile, you can deploy it to the rinkby network using metamask.

Checkout our youtube video to learn more about working with Solidity on remix IDE

2. React App

The “react-app” folder contains the frontend react code.

We are going to write a fairly straight forward React Todo app:

import React, { useEffect, useState } from "react";
import getWeb3 from "./utils/getWeb3";
import Tasks from "./abis/Tasks.json";
import "./App.css";
const App = () => {
  const [todoState, setTodoState] = useState({
    web3: null,
    instance: null,
    account: "",
  });
  const [todos, setTodos] = useState(null);
  const [inputString, setInputString] = useState("");
  const [loading, setLoading] = useState(false);

  const init = async () => {
    const web3 = getWeb3();
    const networkId = await web3.eth.net.getId();
    const deployedNetwork = Tasks.networks[networkId];

    let _instance = new web3.eth.Contract(Tasks.abi, deployedNetwork.address);

    const account = _instance.givenProvider.selectedAddress;

    setTodoState({ web3, instance: _instance, account });
    if (_instance) {
      const _task = await _instance.methods.getTasks().call();
      setTodos(_task);
    }
  };

  useEffect(() => {
    init();
  }, [loading]);

  const onAddToDo = async (e) => {
    e.preventDefault();
    setLoading(true);
    await todoState.instance.methods
      .setTasks(inputString)
      .send({ from: todoState.account })
      .then((res) => {
        console.log("res :>> ", res);
        setLoading(false);
      });
  };

  return !todoState && !todoState.contract ? (
    <div>Loading Web3, accounts, and contract...</div>
  ) : (
    <div className="App">
      <h3>
        Current account <br></br> {todoState.account}
      </h3>

      <form onSubmit={(e) => onAddToDo(e)}>
        <input
          label="Insert Text"
          onChange={(e) => setInputString(e.target.value)}
          value={inputString}
        />
        <button type="submit" disabled={!inputString.length}>
          ADD
        </button>
      </form>

      <h3>Todos</h3>
      <ul>
        {todos?.map((todo) => (
          <li key={todo.id}>
            <p>{todo}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Once you refresh you should see a similar output on screen:

3. Subgraph

Finally, the “subgraph” folder contains code for a GraphQL server which efficiently retrieves data from the Ethereum blockchain.

The 2 big advantages of the graph is that:
– you can do advanced queries in a simple way
– and you can use subgraph built by other people

You don’t have to use the subgraph, it’s optional, but it’s a powerful tool at your disposal.

Conclusion

In conclusion, Create-eth-app is a great tool for quickly bootstrapping a Blockchain project and you should absolutely add it to your toolbox.

0 Comments

Leave a Reply

More great articles

Terra Protocol

Getting Started With Terra Protocol

Terra is a decentralized financial infrastructure and blockchain protocol that introduces some unique concepts and theories into the market. The…

Read Story

Solidity Security Part 3 – Frontrunning

Since all transactions are visible in the mempool for a short while before being executed, observers of the network can…

Read Story

The Ultimate Resource List to Learn Ethereum Dapps & Solidity Smart Contracts

LAST UPDATED IN MARCH 2019 When I first started to learn Ethereum a few years ago, there were almost no…

Read Story

Never miss a minute

Get great content to your inbox every week. No spam.
[contact-form-7 id="6" title="Footer CTA Subscribe Form"]
Arrow-up