logo le blog invivoo blanc

Create your own decentralized application on Ethereum

5 July 2022 | Java | 0 comments

During my visit to Devoxx Paris 2022, I was inspired by Mathias Herbert’s conference “coding for Ethernity”, this has given me the idea of writing this article …

Heroes invest in crypto ; legends create them !

Actually, I am not going to show you how to create your own cryptocurrency, but I will try to explain how you can create your own decentralized application (DApp) on one of the most known blockchain technologies nowadays : Ethereum.

If you are new to blockchain, this will be a quick guide for you to understand how this technology works and to create your first dApp to interact with the Ethereum network.

Basics

Before writing any line of code, there are some important notions you should know. I will be brief and precise in this part. For more details please DYOR (do your own research to figure out what this means 😉)!


Blockchain : a block-based database that is shared among the nodes of a computer network.
dApp : decentralized application that can operate through the use of smart contracts and runs on a blockchain system.
Wallet : a program which stores the public and/or private keys for cryptocurrency transactions.
Smart contracts : programs stored on a blockchain that run when predetermined conditions are met.

Coding for eternity has a cost

Smart contracts are irreversible and unmodifiable once deployed. So, in theory, when writing a smart contract, you are writing a code that will last for eternity and this is one of their major advantages. However, this comes with a cost, especially when the contract has a vulnerability. Here are some major bugs in Ethereum’s smart contracts and their costs :

BugCostDate
DAO hack50 million $June 2016
Wormhole320 million $February 2022
Ronin Hack600 million $March 2022

Diving in now :

To write our first contract we are going to use the language Solidity.

Solidity is an object-oriented programming language that runs on EVM (Ethereum Virtual Machine).

There are many IDE that supports Solidity language (here is a bunch of them). As a Jetbrains fan I will be using Intellij with a solidity plugin:
1- Open intellij
2- Ctrl+Alt+S to open Settings
3- Use Marketplace tab to look for Solidity plugIn
4- Install

Initialize project:

Create the base directory for our project

Mkdir my-first-contract
Cd my-first-contract
Npm init

The last command will allow you to initialize your project. If you don’t have npm installed you can use this link to install node (npm included)

Now we will install HARDHAT which will help us debug, deploy and test our app.

npm install --save-dev hardhat

then inside our project directory, run :

npx hardhat 

This last command will create hardhat project, choose :

Create an empty hardhat.config.js

This hardhat.config.js will be the set up for our project.

In our base directory create two folders: contracts and scripts.

Contracts folder is where we are going to keep our smart contract source code.

Scripts is a folder for where we will keep scripts to deploy and interact with our smart contract.

Now you can open rhe project with IDE.

In case of Intellij : File –> Open and choose my-first-contract folder.

At this point our project should look like this :

In the contracts folder we create a file HelloWorld.sol below :

pragma solidity ^0.7.0;

contract HelloWorld {

    string public message;

    constructor(string memory initMessage) {
        message = initMessage;
    }

    function update(string memory newMessage) public {
        message = newMessage;
    }
}

This smart contract is very simple, it can save a message and update the value of a message.

Now to connect with the Ethereum network we will use Alchemy.

Alchemy is a blockchain developer platform that allows us to communicate with the Ethereum network without having to run our own nodes. The platform also has developer tools for monitoring and analytics.

Create a free account on Alchemy here: https://dashboard.alchemyapi.io/

Once your account is ready, click on create app.

You can choose a name for your team and for the app :

In this example I will be using Ropsten Testnet. What is a Testnet ? Glad you asked.

In Ethereum there are two types of public networks Mainnet and Testnet. In this table we are going to show the main differences between these two networks :

 MainnetTestnet
PurposeFunctional blockchainTesting environment
TransactionsReal transaction stored on actual blockchainFake transactions
CoinsReal valueNo monetary value
Transaction CostPaid using native coinsUsed fake coins
Transaction FrequencyHighLow
MiningEarn real coinsNo economic benefit

Example of testnets: Ropsten, Rinkeby, Kovan…

Once you click Create App, your app will appear in the Alchemy dashboard :

We will also need an Ethereum account (also called wallet), to send and receive transactions. In this example I will be using Metamask (https://metamask.io/).

Installing Metamask:

If you already have an account, you can login using your Secret Phrase. Otherwise click on Create a wallet :

Metamask will generate a secret recovery phrase for you that allows you to recover your wallet and your funds if you ever lose your password. Sharing your Secret Recovery Phrase with someone would be like handing over the pin code to your bank card, it would give that person the ability to access and transfer all of your funds.

Once created, your wallet will look like this :

Your wallet is configured by default to use Mainnet network as you can see on the top left of your wallet. To change that click on the Mainnet network and change Show Test Networks to On :

Now you can see the Testnets. Choose Ropsten :

Now that our wallet is ready, we will need some fake Ethereum in order to deploy our app. To get the fake Ethereum you can use the Ropsten Faucet: https://faucet.egorfine.com/ and enter your Ropsten account address then click “Send Ropsten ETH.” It may take some time to receive your fake ETH due to network traffic. You should see ETH in your MetaMask account soon after.

Another way to check your balance is using Alchemy’s composer tool:

The response should look like :

This result is in Wei you can convert it to Eth using this website: https://coinguides.org/ethereum-unit-converter-gwei-ether/

Connecting everything :

Now we will connect the Alchemy account and Metamask wallet to our smart contract.

Run this command to install the dotenv package in your project directory :

 npm install dotenv --save

Create a file .env in the root directory of your project.

In this file we will save the Alchemy url of our project and the private key of our wallet.

To get the Alchemy url, click on View Key in your project dashboard :

To export your wallet private key, follow the steps here: https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key

Your .env file should look like :

In the next step we will install Ether.js library which makes it easy to send requests to Ethereum.

Execute this command in your project directory :

npm install --save-dev @nomiclabs/hardhat-ethers "ethers@^5.0.0"

Now update the hardhat.config.js :

require('dotenv').config();

require("@nomiclabs/hardhat-ethers");
const { API_URL, PRIVATE_KEY } = process.env;

/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
   solidity: "0.7.3",
   defaultNetwork: "ropsten",
   networks: {
      hardhat: {},
      ropsten: {
         url: API_URL,
         accounts: [`0x${PRIVATE_KEY}`]
      }
   },
}

Now, let’s compile our contract !

npx hardhat compile

You might get a warning about SPDX license identifier not provided in source file, but no need to worry about that.

Next is the deployment. Navigate to the scripts/folder and create a new file called deploy.js, adding the following contents to it :

async function main() {
   const HelloWorld = await ethers.getContractFactory("HelloWorld");

   // Start deployment, returning a promise that resolves to a contract object
   const hello_world = await HelloWorld.deploy("Hello World!");
   console.log("Contract deployed to address:", hello_world.address);}

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

Calling deploy() on a ContractFactory will start the deployment, and return a Promise that resolves to a Contract. This is the object that has a method for each of our smart contract functions.

Now, our contract is ready to be deployed. In the command run :

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

Then, you should be able to see something like this :

Contract deployed to address: 0x8c12379ACAF9B8409D9AAb655557C51E3D72Ef11

You can check that the contract has been deployed successfully on Ropsten etherscan: https://ropsten.etherscan.io/ by pasting the address in the search box :

Click the transaction to see more details.

The “From” should match your Metamask wallet address.

The “To” is your contract address.

To see the details of what happened when deploying the app, go to the Alchemy dashboard and choose the app we have just created, we can see a bunch of Json calls that Hardhat/Ethers made. We will focus on only two of them; eth_sendrawTransaction which the request to write the contract in the Ropsten network and eth_getTransactionByHash which is a request to read information about our transaction.

Conclusion

A smart contract is used for one transaction type (one basic functionality). However, in a dApp, hundreds of contracts interact with each other to guarantee a sophisticated functionality. This functionality can be for financial purposes like trading, investing, lending, and borrowing. Or for applications in gaming, healthcare, and real estate. All this has become possible today thanks to their distributed nature and their ability to exchange information in a trusted way.

Resources

https://docs.alchemy.com/

https://hardhat.org/getting-started/

https://journalducoin.com/solana/wormhole-hack-bridger-oriattaque/https://www.forbes.com/sites/christopherbrookins/2022/03/29/new-1-on-defi-hack-leaderboardaxie-infinitys-ethereum-sidechain-ronin-hit-by-600-million-exploit/?sh=7a39c1263311

Have you read our last article about “Event Sourcing and CQRS using Kafka Streams” ?