© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
B. Wu, B. WuBlockchain for Teenshttps://doi.org/10.1007/978-1-4842-8808-5_5

5. Smart Contracts and Dapps: From Theory to Practice

Brian Wu1   and Bridget Wu1
(1)
Livingston, NJ, USA
 

Brian Kernighan, a computer scientist, wrote the first “Hello, World!” program in 1972 for the language B to be used internally at Bell Labs. Brian wrote a manual titled A Tutorial Introduction to the Language B to demonstrate how to use B’s language. From there, this popular text spread quickly. It was used in a Bell Laboratories memo in 1974, as well as The C Programming Language in 1978. “Hello, World!” remains popular to this day. It became a standard for new programmers for their first program. This particular piece of code proves your code syntax, compiles, and executes to consistently produce the desired output. “Hello, World!” offers the code in more than 60 programming languages.

In the previous chapter, we have theoretically explained the Ethereum network, including Ethereum key components, EVM, architecture, etc. The best way to better understand what we learned so far is to start practicing and writing a smart contract and Dapps for the Ethereum blockchain.

By using the online Remix tool, you’ll learn how to write HelloWorld code in Solidity with all needed syntax. You’ll start from the very beginning, line by line. You will also learn how to compile and deploy your smart contract locally as well as on a globally distributed testnet. Then, we will install and connect our Metamask wallet to testnet. After setting up all that is required in your local Dapp development environment, you will start developing your own Dapp with minimal effort to connect the contract in testnet. By taking control of your Ethereum wallet at the end of this chapter, you should be able to run end-to-end HelloWorld Dapp.

This chapter will help you to achieve the following practical goals:
  • Introducing Remix

  • Writing your first smart contract

  • Taking control of your first Ethereum wallet

  • Decentralized Applications (Dapps)

  • Tokens standard

In the last section, we talk about token standards with the two most important tokens—ERC-20 and ERC-721. ERC-721 is the NFT token standard that we will go over in the next chapter.

This will help make you more familiar with smart contracts and Dapps.

Introducing Remix

Gavin Wood proposed Solidity programming language in August 2014. Alex Beregszaszi, Christian Reitwiessner, and other Ethereum core contributors created Solidity. It is a high-level object-oriented programming language that is inspired by JavaScript, C++, and Python. The purpose of solidity is to execute smart contracts on EVM-based blockchain networks.

Many tools are available for creating and developing Solidity smart contracts. Remix, HardHat, Truffle, and others are popular tools used by Solidity developers. Remix is a powerful online integrated development environment (IDE) for coding, compiling, testing, and debugging smart contracts in Solidity. We don’t need to install any other special software, apart from your web browser.

You can type the Remix IDE in your browser URL box using the following URL:

https://remix.ethereum.org. You’ll then be navigated to the Remix home page as shown in Figure 5-1.

A screenshot of an interface labeled file explorers with toolbars. Homepage is displayed on the right with a caption labeled as remix I D E and below it shows a scan alert message.

Figure 5-1

Remix home page

You will notice that there is a left toolbar menu on the Remix screen. When you click each menu icon, you will see different modules provided.

File Explorers

On File Explorer module, you can manage your workspaces and create contract files under workspaces. When you work on multiple projects, workspaces can help organize your files in different project workspaces. You can create smart contract files, create folders, and upload local files to the current workspace. It is very similar to other cloud browser-based tools, like google drive, dropbox, etc. Under contracts folder, Remix creates three default contracts for you. If you don’t use, you can delete them.

A screenshot of a interface labeled default workspace illustrates 3 markings for 3 icons. The markings are create new contact, create new folder and load local file to current workspace.

Figure 5-2

Remix File explorer page

Solidity Compiler

On the Solidity compiler module, you can select a different version of the Solidity compiler, the current version at this writing is 0.8.7. Since Solidity evolves quite frequently, you need to pay close attention to choosing the configuration you need. Once you create Solidity files, you can compile files by clicking the compile button. The Remix contract section will display a file compilation information, for example, error and warning. The Remix will auto-save the current file change continuously every 5 seconds.

A screenshot of an interface labeled solidity compiler illustrating advanced configurations with file selection and run options.

Figure 5-3

Remix Solidity compiler page

Deploy and Run Transactions

After you have compiled a smart contract, you can use deploy and run transactions module to deploy the contract. You need to select one contract in the Contract Editor to deploy if you have multiple contracts compiled.

A screenshot labeled deploy and run transactions page with environment, account, gas limit, value and contract details filling form. Lower part illustrates adress adding, transactions recorded, and deployed contacts section.

Figure 5-4

Remix Deploy and Run Transaction module

This module provides multiple EVM Environments:

JavaScript VM – JS VM has its own sandbox blockchain simulated Environment running in your browser. It runs transactions very fast (no mining). When you execute transactions, the data is only saved temporarily in the browser. Once you close or reload the page, all transaction data will be lost. You will have to start from scratch. It is very useful for a quick try and tests simple contracts.

A screenshot of the a section from an interface labeled environment. Environment has a box for selection of java scripts, web providers and connect list.

Figure 5-5

Remix EVM environments

Injected Provider – Remix will connect to a web3 provider injected in the browser (commonly known as a browser extension for your wallet). Metamask is currently the most popular Injected Provider. You can also use other popular wallets like Coinbase wallet, Trust Wallet, and Ledger. You can connect to Ethereum’s main network or various testnets through the provider. This allows the Remix to interact with a real network.

Web3 Provider – Remix will connect to a remote node. You will need to provide the URL for the selected provider. Infura, Alchemy, and QuikNode are some popular Web3 providers.

Other Modules

We have introduced the important remix modules, which we typically use often. Other modes like plugin module allow you to install the needed plugin like debug plugin, Solidity static analysis module, Solidity Unit test module, and Settings module. If interested, you can refer to the remix document for detail (https://remix-ide.readthedocs.io).

At this stage, we should have the basic knowledge of Remix.

Let’s start to learn Solidity by writing “Hello, World!” smart contract.

Writing Your First Smart Contract

According to dune.com, the total number of smart contracts created in the second quarter of 2022 was 0.93 million. In Q2 2021, nearly 6 million smart contracts were created, as shown in Figure 5-6. In the current Ethereum blockchain, most smart contracts use Solidity programming language.

A screenshot of smart contract creation bar chart, with quarter 2 of year 2021 having the highest contract creation.

Figure 5-6

Number of Smart contract creation from Q1 2021 to Q2 2022

Write a Contract

On Remix File Explorer module, under contracts folder, click the create new contract icon (page icon) or use context menu by right-clicking to add our first contract. We will name our first smart contract HelloWorld.sol. Solidity Smart contracts will always have an extension of .sol as file type.

Software License

On the first line of a smart contract, you will write your smart contract license. SPDX License Identifiers indicate relevant license information. The MIT License grants anyone who uses this software the right to copy, modify, merge, distribute, and so on:
// SPDX-License-Identifier: MIT

Here Comments (//) is a line of text that appears in a Solidity program but is not executed by the program.

Pragmas

The second line is Pragmas like the following:
pragma solidity ^0.8.15;

The pragma keyword is similar to the C language, which provides the current Solidity compiler. Here 0.8.15 is the Solidity compiler version. The ^ symbol means this file will only support compiler version starting from 0.8.7 till future break changes, which will cause this file to not compile. For example, pragma solidity >=0.4.0 <0.6.0 such as the contract won’t compile in 0.6.0 because of a major solidity change. In that case, you need to modify the related syntax in the file to use the newer version.

Define Contract

To make the code cleaner, you typically leave a blank line after the pragma entry. Then, in the following line of code, you start to declare the contract. In Solidity, we use the contract keyword followed by the name of the contract. In our case, it will be HelloWorld. The contract name should match the filename you created. The contents of the contract will be enclosed within curly braces {}:
contract HelloWorld {
}
So far, the contract should look like Figure 5-7.

A screenshot of the solidity compiler configuration and compiling the hello world.

Figure 5-7

HelloWorld Empty contract

Declare Contract Variable

In the next line, we enter string public message.

Here the string keyword is a state variable type. State variables are values permanently stored in contract storage and are used to maintain the contract’s state.

The visibility of a state variable can be defined as public, private, or internal. In our case, because we set the visibility to public, the message field can be publicly accessed outside of the smart contract.

Define Contract Constructor

The next thing is to create a constructor function:
    constructor(string memory initMessage) {
      message = initMessage;
    }
The HelloWorld.sol will be like Figure 5-8.

A screenshot of hello world contract with messages.

Figure 5-8

HelloWorld contract constructor

The constructor is a function that can be compared to a factory machine. Once given an input, they can run a specific task to return a result.

To declare a constructor, we use the constructor keyword. Once we create our constructor, we can create many different contracts using the same constructor. Whenever a new contract is created, the system automatically calls on the constructor; they only need to use the constructor once to create the contract. If a constructor is not defined explicitly, the Solidity compiler will create a default constructor, which does not require any input.

Most often, you may need a constructor that passes one or more parameters. Inside the {}, we add the initialization logic. In our example, we pass “string memory initMessage” input. The memory keyword we use here indicates that we want initMessage parameter to be mutable, or changeable, and the initMessage value is assigned to message variable and initialized during contract creation time.

Define Functions

HelloWorld contract will have two functions. One to update message and the other to get message:
  1. 1.

    Update contract message function

    Update function will be like as follows:
        function update(string memory newMessage) public {
          message = newMessage;
        }
     
  2. 2.
    Get contract message function
        function getMessage() public view returns (string memory) {
            return message;
        }
     
A Solidity function is defined with the function keyword, followed by
  • The name of the function. Here “update” is the function name.

  • A list of parameters to the function is enclosed in parentheses and separated by commas (parameter1, parameter2, ...). It could be empty (). (string memory newMessage) are parameters in the HelloWorld function.

  • Function visibility – public, private, internal, and external.

  • Functions behavior – pure, view, and payable.

  • Followed by optional returns keyword and return value type (type1, type2, ...) when the function has return values. In our update function, we don’t have a return value. But in getMessage, we return (string memory)

  • A statement block that defines the function, surrounded by curly brackets, {...}.

Syntax
The basic syntax is shown as follows:
function function_name(<parameter types>…) {internal|external|private|public} [pure |view|payable] [returns(<return types>…)] {
        //statements
}
Function Visibility
A function’s scope of visibility can be set by one of these four modifiers:
  • Public – It can be called internally or externally.

  • Internal – Internal functions can only be accessed from inside the current contract and related deriving contracts.

  • External – It can be called from other external contracts, but cannot be called internally (inside the current contract).

  • Private – Like internal visibility, but the function cannot be accessed from related deriving contracts.

Functions Behavior

The pure, constant, view, and payable keywords dictate a Solidity functions behavior.

If the function behavior is not specified, it will read and modify the state of the blockchain.

Pure Functions: It ensures that the caller can’t read or modify the state.

View Functions: View functions are read-only functions that ensure that state variables will not be modified after calling them.

Payable: A payable fallback function is also executed for plain Ether transfers.

Once you completed HelloWorld.sol, you should have 15 lines of code, as shown in Figure 5-9.

A screenshot of the hello world completed code.

Figure 5-9

HelloWorld completed contract

Compile a Contract

As we learned in the EVM section, the smart contract needs to be compiled to Bytecode, before it can be deployed to the blockchain. In this step, we will compile our HelloWorld smart contract.

Remix IDE allows us to compile our Solidity smart contracts directly from our browser. Click on the compiler icon in the navigation. On the Solidity compiler page, select 0.8.15 compiler version; click the compile button to compile HelloWorld smart contract. If it compiles successfully, you will see a green checkmark on the compiler icon in the navigation. Notice also that compilation details button with Application Binary Interface (ABI) and Bytecode will show up after compiling. ABI contains JSON format data which encodes smart contract information that EVM understands and provides the standard way for Dapp to interact with contracts. You can check compilation detail by clicking the button, as shown in Figure 5-10. The result will have Bytecode, Abi, Assembly (Opcode), and other useful compiled contract information. You should copy abi content to some place; we will use this abi String in Dapp section to call with smart contract.

Snapshot of the hello world contract with sections marked as bytecode, a b i, storage layout, web 3 deploy, meradata hash, function hashes, gasestimates, devdoc, userdoc, runtime bytecode, and assembly.

Figure 5-10

Compiled HelloWorld contract

Deploy and Run a Contract

To deploy our contract, click on deploy and run transactions module on the left menu. You should see a dropdown menu listing all the available smart contracts under the Contract Heading, HelloWorld. HelloWorld.sol will be the default selected contract, with an orange Deploy button directly beneath it.

A screenshot of deploy and run transactions interface displaying hello world code on the right. The left side illustrates options for selecting environment, account, gas limit, value, and contract.

Figure 5-11

HelloWorld contract deployment

So far the contract hasn’t been deployed yet. So, to deploy HelloWorld, we need to provide the string initMessage just beside the Deploy button.

We can leave Environment as default selected JavaScript VM, default selected account, Gas limit, and value. Let’s enter Hello Solidity and click the Deploy button.

A screenshot of an interface labeled deploy and run transactions illustrating hello world contract entry and deployed contracts on the left and the code on the right.

Figure 5-12

Deployed HelloWorld contract

The built-in terminal console shows deployment information. The default account amount was reduced by a small amount of gas fee, or a transaction fee, from 100.00000 ETH to 99.99999 ETH.

Under deployed contracts panel, you will see deployed HelloWorld contract with the contract address.

If you expand the deployed HelloWorld contract entry, it will show all contract items—state variables or functions—defined as public in your smart contract.

We can see the update, getMessage function, and message variables in our case.

When you click the message button, you should see “Hello Solidity” under the message button. The same thing happens when you click the getMessage button.

A screenshot labeled as deployed contacts illustrates a section as hello world message deployed to contracts.

Figure 5-13

Call HelloWorld contract message

To change the message, enter “Hello Ethereum” for the update function and then click the button to set the new value.

You can validate that the message variable was updated by clicking on the getMessage function or message variable.

A screenshot of the hello world message updated. The new message is hello ethereum.

Figure 5-14

Update HelloWorld contract message

Congratulations! You have successfully written your very first Hello World smart contract in Solidity and deployed it to the blockchain. To learn more about Solidity, you can visit the Solidity Official Documentation (https://docs.soliditylang.org/en/v0.8.15/contracts.html).

Taking Control of Your First Ethereum Wallet

In Remix, when we use Injected Provider, Metamask is one of the most widely used wallet providers. MetaMask was founded in 2016 by Aaron Davis and Daniel Finlay and is currently owned by ConsenSys. As of March 2022, Metamask has over 30 million monthly active users. As a free browser extension for Chrome, Firefox, Brave, and Edge, MetaMask allows your regular browser to behave as a web3 browser for storing and exchanging cryptocurrencies, as well as interacting with Ethereum Dapps without running an Ethereum node. Simply put, MetaMask is a mobile crypto wallet you can access in your browser. To manage Metamask access, the user needs only a password and a 12-word recovery phrase, also known as a seed phrase. The seed phrase can be made up of any real words, such as dog, cat, or chicken.

If you forget or lose wallet recovery phrase, there is no way to recover your crypto wallet password. It is very important that you back up these seed phrase in a safe and secure place, maybe a hard disk, USB drive, or paper. Don’t store it where it’ll be vulnerable, like an email, online storage, etc.

MetaMask may not be the best place to store large amounts of crypto or valuable crypto assets, such as NFTs. When connecting to the mainnet for trading, use MetaMask as the only tab in that browser and avoid connecting to social media accounts in the same browser—some social media sites have plugins that can steal your data.

Install MetaMask from https://metamask.io. Then download the MetaMask wallet software onto your chosen browser. Select the “Create a Wallet” option, read the terms and conditions, and create a password. Once installed, you will see a fox on the top right of your browser. Open MetaMask, enable the test network, or testnet, by clicking Settings➤ Advanced ➤ Show test networks and select on button for “Select this to show test networks in network list.” Transactions on a testnet are meant to only simulate mainnet transactions, or real blockchain transactions.

A screenshot of the meta mask interface with a settings page. The option advanced settings is selected and the options are labeled as storage logs, sync with mobile, reset account, advanced gas controls, show hex data and networks.

Figure 5-15

Update Metamask setting for testnet

Now you can switch to the Goerli test network from MetaMask’s network list settings.

A screenshot of the goerli test networks adding new network.

Figure 5-16

Connect Metamask with Goerli test network

You will see there is default account in account 1 without any ether.

We will get some free test ether from the Goerli test network. Copy account 1 Ethereum address and use one of Goerli Testnet Faucet to get the ether through your Ethereum account address:
Note

Most testnets will be discontinued after several months (as of July 2022). Currently, Goerli is confirmed to continue in the future, so test ether in this network is usually in high demand. You may need to try several times to obtain some ether.

Once you have successfully submitted the faucet request, you will get some ether in your account.

A screenshot of Account 1 in the goerli test network with 0.05 goerli E T H.

Figure 5-17

Get ether from Goerli test network faucet

With these Ethers, you have done all the hard work of bringing your smart contract to life. Now it’s time to share your first smart contract with the world! Let’s deploy our HelloWorld smart contract to the Goerli test network from Remix.

In Remix, deploy and run the transaction module, select Injected Web3 environment. A popup from Metamask will ask to connect with Account 1 in Metamask in the Goerli test network.

A screenshot labeled deploy and run transactions with an interface at the right labeled connect with metamask and an account is selected. The lower part displays cancel and next options.

Figure 5-18

Connect Remix to Goerli test network

Click next and connect. It will connect remix IDE with Metamask in the Goerli test network. As shown in the following screenshot, you should see a green button showing a connected status.

A screenshot of an account connected in the test network labeled 0.05 goerli E T H.

Figure 5-19

Connected Metamask Goerli test network

Now we can deploy our HelloWorld.sol to the Goerli test network. Enter “Hello Solidity” as the initial message to the right of the orange deploy button. Then click deploy. Metamask will dynamically calculate the estimated gas fee. You can confirm or reject this request before submitting to testnet. Let’s confirm this deployment transaction.

A screenshot of an interface labeled deploy and run transactions the meta mask notification page is displayed at the right.

Figure 5-20

Deploy contract to Goerli test network

In the Remix console, you will see a block transaction confirmation message which returns the transaction hash and other transaction information. Here is the transaction hash: 0x7f773384290cff58ff6bb6e4f0411bfb625d3c1aa957208c6e8b8abeeed9d710

A screenshot of an transaction receipt for hello world contact.

Figure 5-21

Deployed contract with transaction receipt

In Metamask, we can see a new contract deployment information is displayed under the Active tab. Notice that the account ether value was deducted by the transaction gas fee. The original value is 0.05 ETH. Now it is 0.0487 ETH.

A screenshot of an interface labeled goerli test network with account 1 selected. At the centre 0.0487 goerli E T H displays buy, send, and swap option.

Figure 5-22

Deployed contract with gas fee

When you click Contract deployment, it will display details of deployment information.

A screenshot of the contract deployment status and transactions details labeled confirmed.

Figure 5-23

Contract deployment detail

You can click the “View on the block explorer.” The link will lead to the etherscan.io page and show this contract deployment detail. You can see that contract was deployed to address 0xe02cfad8b29d0aad478862facb2e6a9b1fed7bc9 (Note: it will display a different address number when you deploy it). This address is publicly accessible for everyone.

Now that you have deployed your first blockchain smart contract, the transaction hash matches the value we see in the Remix console. You can search the address from the etherscan search bar.

A screenshot of an interface for ether scan contract page illustrating transaction details marked success.

Figure 5-24

Deployed contract in etherscan

Great! You have published the HelloWorld contract in the Goerli test network, which is open to the public and accessible from anywhere. Next, let’s build a simple Dapp to interact with our smart contract.

Decentralized Applications (Dapps)

Generally, a Dapp is a three-tier application comprised of three main components:
  • A front-end layer – A web browser with web servers to host a web page.

  • Web3 Provider layer – The middle layer between the frontend and the smart contracts, that is, Metamask wallet.

  • A backend (smart contract) – Contracts run in the blockchain network.

Figure 5-25 shows a typical DApp layer architecture:

An illustration of the dapp layer architecture flow diagram, with web client, web provider, smart contract and ethereum block chain.

Figure 5-25

Dapp layer architecture

In the Ethereum client section, we use web3 API to query some blockchain information from the geth console. In this section, we will explore another Ethereum JavaScript Open source library—Ether.js, which also enables web clients to communicate and interact with the Ethereum network.

Getting Started

Before proceeding with this section, you need to install the following:

Installing node.js

Follow the node office installation guide, download and install node.js:

https://nodejs.org/en/download/

Installing Git

Follow the git office installation guide to install Git:

https://git-scm.com/book/en/v2/Getting-Started-Installing-Git

Git clone HelloWorld Dapp Project

Once you install node and Git, you need go to this book’s Apress website, git clone chapter 5 HelloWorld Dapp source code:
git clone https://github.com/Apress/Blockchain-for-Teens.git

Install HelloWorld Dapp Project

Open terminal, navigate to helloworld project location. Run npm install

A screenshot of the hello world project location.

This will install node library needed to run Helloworld Dapp

The project structure should be similar to the one shown in Figure 5-26.

A screenshot of the project structure folders illustrating options after selecting client dot js.

Figure 5-26

Dapp project structure

Note, the source code points to the Goerli test network contract address at:
0xe02cfad8b29d0aad478862facb2e6a9b1fed7bc9

You can use this address for testing or you modify this address to your own deployed contract address.

Open client.js, update line 3 of your own address. If you modified the contract and have different contract abi, replace line 4 with your own contract abi.

A screenshot of the address testing for own contract address.

Run HelloWorld Dapp Project

Run the following command shown after the helloworld folder from terminal:
node index.js
This will bring up node server to host HelloWorld Dapp. The port number is 3000.

A screenshot of the dapp node server address.

Figure 5-27

Start Dapp node server

Open HelloWorld Dapp from Browser

Now you can open Dapp from the browser by entering http://localhost:3000. You should see the HelloWorld Dapp page. You can see the top right corner has connect button, which will connect to Metamask. On the middle of the page, there is a blue message button that can be used to retrieve the blockchain message. The red update button with a Message input field will update contract message content.

A screenshot of E 2 E hello world dapp page. A box captioned message update is located at the centre.

Figure 5-28

Dapp initial page

Connect to Metamask

Ether.js use Web3Provider api to connect Metamask wallet:
ethers.providers.Web3Provider(window.ethereum)
Click the connect button. If you are not signed in, it will prompt you to sign in:
await provider.send("eth_requestAccounts", []);

Once connected, we can get user wallet, network, and account information from the provider. provider.getSigner() will get Ethereum Accounts from Metamask wallet. provider.getNetwork() returns current Ethereum Network that wallet connected.

Here is a snippet of the code:

A screenshot of the snippet code.

Since you are running Dapp for the first-time and are not connected to Metamask yet, the Dapp page connect button will be orange. So let’s click the connect button to connect to Metamask. Once again, if you are not signed in, you will see a popup from Metamask asking you to sign in.

Screenshot of an interface labeled E 2 E hello world dapp and a metamask page asking for login information.

Figure 5-29

Dapp connect to Metamask

Login to Metamask. The page will automatically connect to Metamask and display related account and network information on the green display area across the top.

A screenshot of an interface labeled E 2 E hello world dapp and a success icon on the right displaying a box for message update.

Figure 5-30

Dapp connected to Metamask with blockchain data

Get Contract and Call Get Message

In Remix smart contract compile and deployment, we have gotten abi and contract address information. Ether.js is provided below api to get contract information and you can use new ethers.Contract(contactAddress, abi, provider) API to get deployed contract instances.

A screenshot of the read only contract message code.

With ether contract object, you can start “call getMessag” function:

A screenshot of the call get message function code.

You will get the Hello Solidity message from the Goerli test network:

A screenshot of the hello solidity message update box in the E 2 E hello world dapp interface.

Figure 5-31

Dapp get First message

Get Contract and Call Update Message

When you need to call state-changing methods, such as an update message, you must connect to the signer and pay a gas fee to send the state-changing transaction:

A screenshot of the signer contract object input message to update contract.

With the signer contract object, you can now pass input message to update contract:

A screenshot of the a sync function update message.

Let’s update our message, enter “Hello Ethereum.”

A screenshot of the reject and confirm transactions page in the E 2 E hello world dapp with the message hello ethereum.

Figure 5-32

Dapp update message

Metamask will popup and ask to confirm transaction with an estimated gas fee. You review the transaction and submit. The block explorer allows you to view transactions.

A screenshot of the update message and the details of transactions with a message confirmed and from and to information.

Figure 5-33

Dapp update message transaction detail

Click view on block explorer to see your transaction in etherscan.

A screenshot of the etherscan transaction details with a message success highlighted.

Figure 5-34

Dapp update message transaction in etherscan

Once the transaction is confirmed, you will get transaction receipt in page popup.

A screenshot of a transaction receipt with a message success at the right and a box communicating a localhost message with an option marked ok.

Figure 5-35

Dapp with response transaction receipt

Finally, verify your updated message by clicking the message button. “Hello Ethereum” should show on the page.

A screenshot of the update message saying hello Ethereum in the E 2 E hello world dapp interface.

Figure 5-36

Dapp verify updated message

Congratulations, you have successfully published your first smart contract to the public testnet and built a Dapp to call and update the message content! You have now completed an end-to-end Dapp development cycle, which is a huge accomplishment. Pat yourself on the back, because that was a lot of work.

Despite the fact that we have spent enough time exploring Ethereum Dapp and Solidity principles to get you to build a Dapp, this book only provides a basic introduction. There are a lot of good online documentation covering all aspects of Javascript, JQuery, express.js, and ether.js.

Here are some useful links:

Tokens Standard

In Chapter 1, we learned Mohammad Bin Tughlaq invented token money—Tanka, which used copper currency to represent the same value as a silver coin. In a blockchain, the coin represents the native currency. For instance, ether is the coin in Ethereum. And a token is created by a smart contract, which defines basic token properties, then builds and operates.

A crypto token is a virtual currency token representing programmable assets or shared ownership with access rights to an entity with a specific value. The token is managed by a smart contract, which allows for the efficient and secure purchase or sale of an item such as an art collection, the exchange of token ownership, the transfer of token balance, the storage of token value, and the verification of transactions on the blockchain.

To assist developers in standardizing token creation, the Ethereum community has developed many token standards through the Ethereum Improvement Proposal (EIP) process.

EIPs contain standard technical specifications for potential new Ethereum features or processes, including core protocol specifications, improvements, client APIs, and contract standards. It acts as the “source of truth” for the community. Anyone can create an EIP by following standards guidelines in the EIP-1, published in 2015 (https://eips.ethereum.org/EIPS/eip-1). As stated in EIP-1, Ethereum Request for Comment (ERC) is the application-level standards and conventions. If the specific ERC is approved in the Ethereum community, it becomes a new token standard rule which will be outlined in the document through a related smart contract.

There are many token standards, including:
  • Standards of token (ERC-20, ERC-721, ERC-1155, ERC-777)

  • Name registries (ERC-26, ERC-137)

  • URI schemes (ERC-67)

  • Library/packet formats (EIP-82)

  • Wallet formats (EIP-75, EIP-85)

There are many other tokens still in draft and review status. You can check all token ERC through this link: https://eips.ethereum.org/erc

Let’s take a look at the two most popular ERC standards, ERC-20 and ERC-721.

ERC-20

ERC-20 is the most popular Ethereum token standard and was proposed on November 19, 2015 by Fabian Vogelsteller. Most ICOs (Initial Coin Offering) that have issued their tokens on the Ethereum platform or EVM-based blockchain (like Binance) are ERC-20 tokens. The ICO is cryptocurrency version of the IPO (initial public offering), which is used in the stock market to raise capital or participate in investment opportunities. There are around 508k ERC-20 tokens in the Ethereum mainnet on March 2022. The total market cap of all ERC-20 tokens is around $18.7 billion, and there are more than 160K ERC-20 in Binance.

20 is a unique identification number to distinguish the ERC-20 standard from others.

The ERC-20 token has several optional fields such as name and symbol and defines the following rules in the smart contract:
contract ERC20Interface {
    function totalSupply() public view returns (uint);
    function balanceOf(address tokenOwner) public view returns (uint balance);
    function allowance(address tokenOwner, address spender) public view returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);
    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

totalSupply(): Gets the total number of token supply.

balanceOf(): Gets the account balance for the specified address.

allowance(): Returns the amount of tokens which the spender is allowed to withdraw from the owner.

transfer(): Transfer the balance from the owner’s account to another specified address and must fire the transfer event.

transferFrom (): Send the amount of tokens from address `from` to address `to`. The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.

approve(): Allows spender to withdraw the specified amount of tokens from your account multiple times.

If you ever find yourself working on a project that requires creating and deploying an ERC-20 token, you can create a smart contract by implementing these ERC-20 functions. Here is a simple example:
MyToken is ERC20 {
 // implement the functions required by ERC20 interface standard
 // other functions...
 }
In Etherscan, you can find many ERC-20-compliant tokens that have been deployed mainnet. Here is a real-world example of an ERC-20 token transaction on the Etherscan.

A screenshot of an interface labeled token kucoin token highlighting an overview, profile summary and transfer information with 34, 718 transactions found marked as transfer and transfer from.

Figure 5-37

ERC-20 example

The screenshot shows the amount of ERC-20 tokens being transferred from one address to another address by the transfer or transferFrom method.

In ERC-20 token, tokens are fungible, meaning that each token has exactly the same type and value as another token. If you swap one ERC-20 for another, there will be no difference in authenticity or value; they are interchangeable and represent a single entity.

For example, Tether (USDT) is an ERC-20 Token. It is a stablecoin—a crypto asset value pegged to the US dollar at a 1 to 1 ratio and 100% backed by Tether’s equivalent reserves. These reserves are a mix of assets, including cash. USDT is similar to the ETH, meaning that 1 Token is and will always be equal to all the other USDT Tokens. They are the same type, represent the US dollar, and are mutually interchangeable. USDT is also divisible, which can be broken down into smaller units like cents.

So fungible tokens have the following properties: interchangeable, uniform, and divisible.

Next let’s talk about tokens that are not mutually interchangeable or, in other words, nonfungible.

ERC-721

All ERC-20 tokens (like USDT) are identical and provide the same value. So what matters is how many tokens you own in the wallet, not their individual identities. Nonfungible tokens (NFTs) can be uniquely identified; they are assets whose data is stored on blockchain networks. NFTs are not interchangeable with other NFTs because they are unique. Think of a unique work of art created by an artist, luxury brands item from fashion companies, and different videos.

ERC-721 is a standard interface for nonfungible tokens, also known as deeds, and is available at https://eips.ethereum.org/EIPS/eip-721. The proposal for the creation of this new standard was created in Jan 2018, proposed by William Entriken, Dieter Shirley, Jacob Evans, and Nastassia Sachs. According to a Bloomberg report, NFT Market surpassed $40 Billion in 2021 and over $37 billion in NFT marketplaces in 2022 on May 1.

Similar to the ERC-20 token standard, the ERC-721 specification provides details and defines functions and events that a derived contract should implement to develop an NFT, shown in the following code block:
interface ERC721 {
    event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
    event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
    function balanceOf(address _owner) external view returns (uint256);
    function ownerOf(uint256 _tokenId) external view returns (address);
    function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
    function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
    function approve(address _approved, uint256 _tokenId) external payable;
    function setApprovalForAll(address _operator, bool _approved) external;
    function getApproved(uint256 _tokenId) external view returns (address);
    function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}

balanceOf: Gets the account balance for the specified address.

ownerOf: The function returns the unique address of the owner of a token based on the provided tokenId.

safeTransferFrom: Transfers the ownership of an NFT from one address to another address. It is required that msg.sender is the current owner, an authorized operator, or the approved address for this NFT.

transferFrom (): Send the amount of tokens from address `from` to address `to`. The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.

approve(): Allows spender to withdraw the specified amount of tokens from your account multiple times.

setApprovalForAll: Assign or revoke approval rights for the given operator to manage all of `msg.sender`’s assets.

getApproved: Get the approved address for a single NFT

isApprovedForAll: Check if the given operator address has access right to operate for the given owner’s tokens.

The most known example of ERC-721 is the CryptoKitties game, the first NFT token. In the game, there are thousands of CryptoKittie. Each cat has their own profile, which includes unique genes, name, color, shape, price, and other profiles. The game player can collect and breed adorable kittens. As shown in Figure 5-38, each cryptoKittie as a collectible digital asset can be traded, sold, and bought by the player:

A screenshot of an animated cat and a label marked as kitty hash 1111 with information like owner, born, generation, block number, block hash, official profile, and attributes. On the lower side information is displayed under the label genes.

Figure 5-38

ERC-721 CryptoKitties example

We can find CryptoKittie in etherscan. These tokens are bid and trade daily by game player. Some individual cryptokitties have sold for more than $300,000 a piece.

A screenshot of the ether scan crypto kitties inventory.

Figure 5-39

ERC-721 CryptoKitties in Etherscan

NFT collectibles market continues to grow as fan engagement increases, which will likely increase mainstream adoption. NFTs can have only one owner at a time. True ownership is one of the key characteristics of any NFT, and it has the potential to play a critical role in bringing the digital and physical worlds closer together than they have ever been.

Summary

You have written your first smart contract through Remix IDE, and deployed HelloWorld Solidity file to the Goerli test network. We demonstrated the basics of Dapp and web3.js and how Dapp interacts with smart contract by connecting with Metamask wallet.

But our journey doesn’t end here—in the next chapter, we will cover more exciting details on the NFT.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.135.21