Ethereum Blockchain And Smart Contracts 101

Rosario Borgesi
Coinmonks
14 min readMay 11, 2024

--

This story is designed to guide you through the initial steps of working with the Ethereum blockchain and smart contracts. We will delve into the fundamental concepts of state, transactions, gas, ABI, and accounts, as well as the structure of blocks. Additionally, we will discuss smart contracts and the Solidity language, which is pivotal for writing these contracts. We’ll also examine the essential software and libraries required to interact with Ethereum, along with the Integrated Development Environments (IDEs) available in the market for developing smart contracts. Finally, we will illustrate these concepts with a simple smart contract example.

You can also watch the video here.

Table Of Contents

· Table Of Contents
· Ethereum Virtual Machine (EVM)
What is the EVM?
Smart Contracts
The Ethereum Blockchain
Ether
· Key Concepts
State
Transactions
Gas
ABI (Application Binary Interface)
Read Functions vs. Write Functions
Account Types
Blocks
Block Time
Ethereum Networks And Account Portability
Solidity
· Interacting With Smart Contracts
Etherscan
Ethers.js and Web3.js
Requirements for Interaction
· Developing Smart Contracts
· A Simple Smart Contract
· Further Exploration
· References

Ethereum Virtual Machine (EVM)

What is the EVM?

The Ethereum blockchain as a computer networ

Imagine the Ethereum Virtual Machine (EVM) as a big, global computer that everyone can use. It’s like a super powerful computer that no single person owns, but anyone can program it to do certain tasks.

Unlike a typical computer owned by an individual or an organization, this one is decentralized and operates on a network of computers around the world. This global setup ensures it’s powerful and always operational.

Smart Contracts

Photo by Arnold Francisca on Unsplash

Smart contracts are the programs that run on the EVM. Anyone can write and deploy its own code or smart contract on the EVM.

Unlike deploying code on a solitary machine, when you deploy a smart contract to the EVM, it is replicated across a network of computers. This transparency allows anyone to view and interact with the code. Moreover, once deployed, the code becomes immutable, cementing its reliability and fostering trust within the ecosystem.

The Ethereum Blockchain

Photo by Shubham Dhage on Unsplash

At its essence, a blockchain serves as a shared, unchangeable ledger that meticulously records transactions. In the case of Ethereum, its blockchain goes beyond financial transactions; it also records the transactions executed by smart contracts. In simpler terms, the Ethereum blockchain acts as a secure record-keeper, capturing all activities performed by the Ethereum Virtual Machine (EVM).

The term “blockchain” itself hints at its structure: it’s a sequence of interconnected blocks, with each block containing a batch of transactions. These blocks are validated and secured by a consensus mechanism known as proof-of-stake (PoS).

If you need to learn more about the blockchain I suggest you this story.

Ether

Ethers
Photo by Kanchanara on Unsplash

Ether is the currency of the Ethereum network. It’s necessary to pay for the computational resources needed to run smart contracts on the EVM, much like inserting coins into a vending machine to get a snack.
Thre are three Ether units:

  • Ether (ETH) : This is the main cryptocurrency used on the Ethereum network. It’s similar to how dollars are used as currency in the United States.
  • Wei : The smallest unit of ether, much like a cent is to a dollar. It’s named after Wei Dai, a computer engineer known for his contributions to cryptography. One ether is equal to 1,000,000,000,000,000,000 wei (or 10¹⁸ wei).
  • Gwei : Short for gigawei, this unit is often used to measure transaction fees (gas) on the Ethereum network. One gwei equals 1,000,000,000 wei (or 10⁹ wei).

Key Concepts

State

The state of the EVM is a comprehensive data structure that resembles a highly sophisticated database. It’s called a modified Merkle Patricia Trie and it’s responsible for storing all the information about all the accounts and their balances, as well as the current state of all the smart contracts (like their code and storage). This trie structure allows Ethereum to quickly confirm the current state and make updates in a secure and efficient way.

Transactions

A blockchain serves as a globally shared, transactional database. Participants in the network can read entries from this database. When you wish to modify data within the database, you create a transaction. For this change to take effect, it must be accepted by all other participants. The term ‘transaction’ implies that the alteration you intend (even if it involves changing multiple values simultaneously) is either fully applied or not applied at all. During the execution of your transaction, no other transaction can modify the same data.

Transactions are the actions that change the state of the EVM. They are like signed instructions sent by users or smart contracts to transfer Ether, interact with a contract, or even create a new contract. These transactions are cryptographically signed, which means they are secured by a digital signature that proves who initiated the transaction, ensuring that only the rightful owner can make changes.

From a practical perspective a transaction is a message that is sent from one account to another account (which might be the same or empty, see below). It can include binary data (which is called “payload”) and Ether.

If the target account contains code, that code is executed and the payload is provided as input data.

If the target account is not set (the transaction does not have a recipient or the recipient is set to null), the transaction creates a new contract. The payload of such a contract creation transaction is taken to be EVM bytecode and executed. The output data of this execution is permanently stored as the code of the contract.

Gas

When a transaction is created on the Ethereum network, it incurs a cost known as gas, which must be paid by the transaction originator (referred to as tx.origin). As the Ethereum Virtual Machine (EVM) executes the transaction, the gas is gradually consumed based on specific rules. If the gas is fully depleted (i.e., it becomes negative), an out-of-gas exception occurs. This exception stops the execution of the transaction and reverts any changes made to the state within the current call frame.

This gas mechanism serves two purposes:

  1. Economical Use: It encourages efficient use of EVM execution time by making participants mindful of their gas consumption.
  2. Compensation: It compensates EVM executors (such as miners or stakers) for their computational work. Each block has a maximum gas limit, which also helps control the workload required to validate a block.

The gas price is determined by the transaction sender and represents the fee they are willing to pay per unit of gas. The sender pays gas_price * gas upfront to the EVM executor. If any gas remains after execution, it is refunded to the sender. However, if an exception occurs and changes are reverted, the already consumed gas is not refunded.

To prevent abuse, EVM executors can choose whether to include a transaction in a block. Transaction senders cannot manipulate the system by setting an unreasonably low gas price.

If you would like to further explore this topic you can read this story.

ABI (Application Binary Interface)

The ABI is essentially the bridge between your smart contract and the outside world. It’s a set of rules that defines how to call functions and how data is formatted in the transactions.

  1. Purpose and Function:
  • The ABI serves as the standard way to communicate with Ethereum contracts, both from outside the blockchain (external applications) and for contract-to-contract interaction.
  • It defines how data should be encoded and decoded when interacting with contracts.
  1. Encoding and Decoding Data:
  • When you call a function in an Ethereum smart contract or retrieve data from it, the ABI specifies how to encode the function calls and decode the results.
  • It ensures that data is transmitted correctly between the Ethereum Virtual Machine (EVM) and external applications.

Read Functions vs. Write Functions

  • Read Functions: These functions only retrieve data from the blockchain and do not modify the state. They are free to use because they don’t change any data on the blockchain. An example is getting the balance of an account.
  • Write Functions: In contrast, write functions can change the state of the blockchain, like updating a value or transferring Ether. These functions require a transaction to be sent and processed by the network, which incurs a gas fee.

Account Types

Ethereum has two account types:

  • Externally-owned account (EOA) : controlled by anyone with the private keys (i.e people accounts)
  • Contract account : a smart contract deployed to the network, controlled by code.

Both account types have the ability to:

  • Receive, hold and send ETH and tokens
  • Interact with deployed smart contracts

The key differences between the two types of accounts are:

Externally-owned

  • Creating an account costs nothing
  • Can initiate transactions
  • Transactions between externally-owned accounts can only be ETH/token transfers
  • Made up of a cryptographic pair of keys: public and private keys that control account activities

Contract

  • Creating a contract has a cost because you’re using network storage
  • Can only send transactions in response to receiving a transaction
  • Transactions from an external account to a contract account can trigger code which can execute many different actions, such as transferring tokens or even creating a new contract
  • Contract accounts don’t have private keys. Instead, they are controlled by the logic of the smart contract code

Regardless of whether or not the account stores code, the two types are treated equally by the EVM.

Every account has a persistent key-value store mapping 256-bit words to 256-bit words called storage.

Furthermore, every account has a balance in Ether (in “Wei” to be exact, 1 ether is 10**18 wei) which can be modified by sending transactions that include Ether.

Blocks

The transactions are bundled into what is called a “block” and then they will be executed and distributed among all participating nodes.

These blocks form a linear sequence in time, and that is where the word “blockchain” derives from. Blocks are added to the chain at regular intervals, although these intervals may be subject to change in the future. For the most up-to-date information, it is recommended to monitor the network, for example, on Etherscan.

Block Time

The block time in Ethereum refers to the average time it takes for a new block of transactions to be added to the blockchain. As of the latest information available, Ethereum’s block time is approximately 12 seconds. This interval allows the network to reach consensus and add new blocks in a manner that balances speed and security. It’s important to note that block times can fluctuate slightly due to network conditions and the consensus mechanism in place.

Ethereum Networks And Account Portability

In Ethereum, the concept of networks refers to different blockchain environments that operate under the same protocol rules but serve different purposes. Here’s an overview of the primary Ethereum networks and how they relate to accounts:

  • Mainnet: This is the primary public Ethereum network where actual transactions occur and real ETH is used. It’s the live blockchain where the state of accounts and smart contracts is continuously updated and maintained.
  • Testnets: These are networks used for testing purposes. They simulate the Ethereum Mainnet environment, allowing developers to test their smart contracts and applications without using real ETH. A common testnet is Sepolia. The same account structure (EOAs and contract accounts) exists here, but the assets have no real-world value.
  • Layer 2 Networks: These are networks built on top of the Ethereum Mainnet to improve scalability and transaction speed. They use the same account system but process transactions off the main chain, later settling the final state on the Mainnet.

One of the key features of Ethereum is the account portability: The same account (EOA), identified by its public and private key pair, can interact with all these networks. This means you can use the same wallet address across Mainnet, testnets, and other compatible networks, although the assets and transactions are network-specific.

Solidity

We have learned that smart contracts are programs deployed and executed on the Ethereum blockchain. To write these programs, developers use the Solidity programming language. Like most programming languages, Solidity is a high-level language that must be compiled to be executed within the Ethereum Virtual Machine (EVM). In Solidity, the compiler is solc.js, which enables developers to compile Solidity code into EVM bytecode for deployment on the Ethereum network.

Interacting With Smart Contracts

In this section we will discuss all the tools and requirements for engaging with smart contracts:

Etherscan

Etherscan is a block explorer and analytics platform for Ethereum. It allows users to easily look up, confirm, and validate transactions that have taken place on the Ethereum blockchain. For smart contracts, Etherscan provides a user-friendly interface where you can:

  • View contract code and read its functions.
  • Track transactions and events.
  • Query balances and states associated with the contract.

Ethers.js and Web3.js

These are JavaScript libraries that enable developers to interact with the Ethereum blockchain from a website or a Node.js backend. Here’s what they offer:

  • Ethers.js: Known for its clean, modular structure, Ethers.js is a library that aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem.
  • Web3.js: This is one of the original Ethereum JavaScript libraries. It provides a set of methods to easily interact with the Ethereum blockchain.

Both libraries allow you to:

  • Send Ether and other transactions.
  • Interact with smart contracts (read and write).
  • Listen for events emitted by smart contracts.

If you want to learn more about these libraries check out this story.

Requirements for Interaction

To start interacting with smart contracts, you’ll need the following setup:

  • Node.js: This is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It’s necessary for running JavaScript code outside of a browser, which is essential for backend services or development environments.
  • Ethers.js or Web3.js: Choose one of these libraries based on your preference and the needs of your project. They will be your toolkit for communicating with the Ethereum network.
  • Web3 Wallet: MetaMask is a popular choice. It’s a browser extension that acts as a bridge between regular browsers and the Ethereum blockchain. It allows you to run Ethereum dApps right in your browser without running a full Ethereum node. When you create a Metamask account you are creating a new externally owned account on Ethereum.
  • Test ETH: Before deploying on the main network, you’ll likely want to test your interactions on test networks like Sepolia. Test ETH can be obtained for free from various faucets for these purposes. For instance you can use the Alchemy faucet.
  • Provider: A provider is a service that connects you to a blockchain network. It acts as a link between your application and the Ethereum blockchain, allowing you to send transactions, deploy smart contracts, and read data from the blockchain. Providers like Infura handle the complexities of running and maintaining a full Ethereum node, so you don’t have to. You just need to create an API-key that allows your application to connect to the desired network.

Developing Smart Contracts

Integrated Development Environments (IDEs) are essential for developing smart contracts on the Ethereum blockchain:

  • Remix is a popular web-based IDE that allows developers to write, deploy, and test smart contracts directly in a browser, with no setup required. It provides a user-friendly interface and integrates tools for debugging and deploying contracts to the Ethereum network.
  • Hardhat is another widely-used development environment, which is more like a task runner; it allows developers to compile, deploy, test, and debug their Ethereum software. It’s designed to provide developers with a solid foundation for building advanced applications and smart contract systems. If you want to learn more check out this story.
  • Foundry is a newer tool that focuses on speed and reliability, offering developers a fast and flexible framework for smart contract development. It’s built on the Forge testing framework and Cast for Ethereum transaction simulation, making it a powerful suite for smart contract creation and testing.

Each of these IDEs has its own set of features and benefits, and they can be used individually or in combination to suit the needs of different development projects on the Ethereum platform.

A Simple Smart Contract

Let us begin with a basic example that sets the value of a variable and exposes it for other contracts to access.

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

contract SimpleStorage {
uint storedData;

function set(uint x) public {
storedData = x;
}

function get() public view returns (uint) {
return storedData;
}
}

The first line tells you that the source code is licensed under MIT licence.

The next line specifies that the source code is written for Solidity version 0.8.25. This is to ensure that the contract is not compilable with a new (breaking) compiler version, where it could behave differently. Pragmas are common instructions for compilers about how to treat the source code (e.g. pragma once).

A contract in the sense of Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. The line uint storedData; declares a state variable called storedData of type uint (unsigned integer of 256 bits) which is directly stored on the blockchain.

Additionally the contract defines the functions set and get that can be used to modify or retrieve the value of the variable.

Currently, this contract’s functionality is limited. Thanks to Ethereum’s infrastructure, it enables any individual to record a unique number that becomes globally accessible. There’s no practical method to block the publication of this number. While it’s possible for someone to replace your number by executing the ‘set’ command with a new digit, your original number will remain preserved in the blockchain’s historical record.

Further Exploration

For those eager to dive into coding Solidity smart contracts, I recommend exploring the following resources:

For those who want to understand more about how the blockchain works I can recommend the following article:

Conclusions

Congratulations! You’ve taken your first steps into the captivating realm of Ethereum and smart contracts. Let’s recap what we’ve covered:

  1. Ethereum Basics: You now grasp the core concepts of Ethereum, including state, transactions, and gas. These building blocks form the foundation of decentralized applications.
  2. Smart Contracts and Solidity: Armed with knowledge, you’re ready to explore smart contracts. Solidity — the language of the blockchain — will be your trusty companion as you write and deploy these self-executing contracts.
  3. Software and Tools: We’ve discussed the essential software and libraries for interacting with Ethereum. Whether you choose web3.js, ethers.js, or another tool, you’re equipped to navigate the Ethereum landscape.
  4. IDEs for Development: IDEs like Remix, Foundry, and Hardhat await your creative endeavors. These development environments streamline smart contract coding, testing, and deployment.
  5. Your First Contract: As a parting gift, we glimpsed a simple smart contract. Brace yourself for more complex and exciting projects as you continue your journey.

I hope that this story has provided you with a clearer understanding of how Ethereum works and how you can get started with Solidity to write smart contracts. If you have any questions, I will be glad to answer!

References

--

--