Skip to content

DApps & Smart Contracts

Ananthan edited this page May 25, 2024 · 11 revisions

Introduction to DApp

One of the major goals of Ethereum is to provide a set of tools that will move the information network infrastructure from a centralized, constrained to a decentralized, shared network infrastructure. The applications built on top of Ethereum maintain a decentralized nature and are known as Decentralized Applications (DApps).

DApp

Centralized application vs Decentralized Application

DApp is an application built on decentralized technology, rather than being built and controlled by a single, centralized entity or company. The control gets distributed and shared among the network participants. The code is kept open and transparent so anyone can audit and suggest changes to the instructions.

DApp Application Stack

In a DApp, the control and responsibilities get distributed and shared among the network participants. Currently, DApps on Ethereum has a flexible application stack. The below diagram shows the various technologies used when developing a DApp on Ethereum.

DApp Stack

DApp technical stack

This stack is a minimal representation based on some popular tools used for DApp development.

  • User Interface: DApp requires a user interface for the end user to interact with the blockchain. This user interface can be designed and developed using popular frameworks like React, Vue, Angular, Svelte, or using simple HTML-CSS-JS combination.
  • Libraries and Frameworks: There are libraries and frameworks such as Web3JS, Ethers.js, Hardhat, Foundry which help the communication with the blockchain.
  • Wallets: Wallets are used for managing your accounts in the blockchain network. Metamask is a prominent example.
  • Smart Contracts: Smart Contracts are self-executing programs that represent business logic digitally. Smart contracts are written using specific programming languages like Solidity, Vyper, which are then compiled and deployed to the blockchain network.
  • Ethereum Blockchain: Blockchain clients such as Besu, Teku, Lighthouse, and Prysm for connecting to the Ethereum network or simulations like Remix VM, Hardhat node are used during development.
  • OS: The commonly used operating systems like Windows, Linux and Mac.

Decentralized applications are the core of Web3, the decentralized web.

Web3

Web3 is a major upgrade to the internet, nourishing with extra layers of security, identity, trust, and user control. Joining hands with blockchain technology, the Web3 revolution aims to create a truly decentralized internet that lets users freely interact, share and collaborate on a global scale in a trustless environment.

Blockchain is indeed staying at the forefront in revolutionizing Web3, which aims complete decentralization in terms of usage and access of information.

Advantages of Web3

  • Decentralized - The users of these protocols do not need to put their trust in centralized authority, and also need not be concerned about single-point failures.
  • Private - Blockchain technologies preserve the privacy of the users, giving them the ability to choose with whom and what information they want to share.
  • Censorship Resistant - Information stored on public blockchains cannot be manipulated and there are no constraints on the type of data being stored.
  • Digital Ownerships - The inbuilt token frameworks provided by blockchain technology provides innovative ways for ensuring ownership of digital goods.

Smart Contract

The control of DApps is distributed and shared among the network participants. Their source code is kept open and transparent allowing anyone to audit them.

But is such an architecture possible? Can't anyone simply come and tweak the code just as they like? How do DApps run in the absence of a central control system?

The business logic for DApps is embedded in a self-executing program called a smart contract that gets shared among the network participants.

How do smart contracts work:

Smart Contract

Smart contract execution

The smart contracts are simple and expressive. But, they possess some flaws. Smart contracts can get out of hand sometimes. Any bug in the smart contract can lead to the failure or collapse of the DApp.

Smart contracts written in high-level languages are compiled and deployed as bytecode in the blockchain network. This self-executing code is invoked when the conditions/rules are met and all the participants abide by the same set of rules. This eliminates the need for intermediaries or third parties to enforce norms and checks for discrepancies, thereby saving huge amount of money for businesses.

Smart contracts are tamper-resistant and the outcome of the smart contract can be validated by everyone.

Limitations

  • Smart contracts can only be enforced on digital assets.
  • The blockchain network is decentralized and not legally regulated.
  • The interaction with the real world can't be bound by the smart contract.
  • The smart contracts may not be able to implement sophisticated logic.

Applications of Smart Contract

Let’s explore a real-case scenario with a smart contract.

Consider a house ownership transfer. Imagine Bob wants to sell his house for a certain amount. Under the traditional registry process, he has to depend on a central authority in order to complete his transaction. Take a look.

Smart Contract Scenario

House ownership transfer in physical world

Enter smart contract

Assume Bob wants to sell his house. The price of the house is 150 ETH. Bob represents his house in a smart contract - this is possible using a token that represents the ownership of the house. The business logic or the condition coded in the smart contract is that IF someone sends 150 ETH to the smart contract THEN the token is sent to that person’s address. So, if someone wants to buy Bob's house, all they need to do is send the right amount of ETH to the smart contract. If it’s the right amount, the token (the ownership of your house) is sent to that person and the 150 ETH is sent to Bob. If it is not the right amount, then the ETH will be returned to the sender and Bob’s house stays in the smart contract. This transaction will be recorded in the Ethereum ledger and can be verified by anyone.

How smart contract differs from a conventional computer-run program?

While a computer-run program represents a set of instructions for a specific task, the smart contract can cover the entire business logic including the asset behavior, legal obligations, user roles, access restrictions, and any other protocols needed for the smooth running of the business.It offers the following advantages to the businessmen.

Benefits of Smart Contracts

Smart Contract Benefits

Benefits of smart contract

First Smart Contract

Now to understand the structure and working of a smart contract, let's write a simple smart contract in Solidity. We will stick to Solidity, the most popular smart contract language, to code our smart contracts. The below program is used to store and retrieve an integer value from the blockchain network. This integer will be stored in a variable called number.

First Contract

Storage.sol

Let us understand the Storage smart contract.

When writing a contract using Solidity language we need to specify the SPDX-License-Identifier tag for the source file.

The tag should be specified at the beginning of each program, and has the following general syntax:

// SPDX-License-Identifier: name of the license

This will be written as a comment. It is possible to skip specifying the SPDX-License-Identifier but the compiler will return a warning (not an error). Click here for the available list of licenses, this list can be used to choose the appropriate license for the Solidity code.

Next, we need to specify the version of the Solidity language. The Solidity language is constantly getting updated. So this specification ensures that the contract isn't compiled using an incompatible Solidity compiler. The general syntax is:

pragma solidity version;

We use the keywords pragma solidity then followed by the version number used for our code. The compiler version can be mentioned in a number of ways.

pragma solidity ^0.8.20;

Here the version number starts with a 0, followed by a major build number and a minor build number. For example, version number 0.8.20 refers to major build 8 and minor build 20. The caret symbol (^) before the version number tells Solidity that it can use the latest build in a major version range. In the preceding example, Solidity can use a compiler from any build in the version 8 build range. This is a way to tell readers that your program was written for 0.8.20 but will still compile for subsequent version 8 builds.

Although using the caret in the pragma directive provides flexibility, it is a better practice to drop the caret and tell Solidity exactly what compiler version you expect as shown in the above example.

We can create variables for storing and retrieving data from the blockchain and code functions for handling these variables inside a contract. There should be at least one contract inside the solidity file (there are some exceptions to this which will be discussed in the coming sections). We can also have multiple contracts inside the same file.

The general syntax for the contract is:

contract [name] { }

The contract keyword is followed by the name of the contract and curly braces are used to specify the body of the contract. When naming the contract, it will be always helpful to provide a name that describes the intentions for which the contract is written. In the above example, the contract name is Storage.

The next line declares a variable called number of the type uint (unsigned integer of length 256 bits), for storing the numerical value.

uint256 number;

Then we define a function named store() for storing data into the number variable. The function is tagged with the keyword public, which means it's accessible to anyone who can interact with the contract.

function store (uint256 num) public {
     number = num;
}

To read the data from the number variable, we define another function named retrieve(). The view keyword specifies the mutability of the function; function mutability means how the function interacts with the state of the blockchain (either reading or writing on it).

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

So our Storage smart contract maintains the number variable. Any user can assign a value to the number using the store function and anyone can view the current value of the number using the retrieve function.

Executing Smart Contract

Now that we have written our first smart contract, let us see how to execute it. Copy the code below.

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

contract Storage {

    uint256 number;

    function store(uint256 num) public {
        number = num;
    }

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

Now, we need to execute our smart contract. For that we will use a simple tool called Remix IDE. Remix IDE is an open-source Ethereum IDE which is available as a web and desktop application. It has options to write, compile, debug and deploy Solidity code. It is the preferred tool for learning smart contract development and familiarizing the Ethereum network.

Kindly go to https://remix.ethereum.org/

The site will show you a quick review of its function. Kindly read through it. After that, create a new file by clicking on the 'Create New File' symbol in the top left corner.

Provide 'Storage.sol' as the file name. Now, a new file will be created and opened on the right side of the page. Paste our code there.

Go to the 'SOLIDITY COMPILER' tab by clicking the tab switch icon, then click 'Compile Storage.sol'.

If there are no errors, the compilation process will be successful. We can see the following results under the 'Compile Storage.sol' button: a green tick next to the 'SOLIDITY COMPILER' tab button.

Now go to the 'DEPLOY & RUN TRANSACTIONS' tab. Click on the 'Deploy' button.

If there are no errors, we can see the following results under the 'Deployed/Unpinned Contracts' section.

Expand the 'STORAGE' contract entry.

Here we can access the functions written in the smart contract. Write a number onto the blockchain using the text box next to the 'store' button and click the button. Click on the 'retrieve' button to read the value from the blockchain.



Clone this wiki locally