An Overview of Ethereum and Solidity

A useful primer on the Ethereum blockchain, the Solidity programming language, and smart contracts

Burakcan Ekici
Better Programming

--

Solidity and Ethereum logos
Image credit: Author

In this article, we will take a look at Ethereum fundamentals and realize what makes blockchain different and the benefits that Ethereum contributes.

Ethereum

Ethereum was first proposed by Vitalik Buterin in 2013. After Bitcoin, among blockchain-based projects, Ethereum was the most distinctive project because of the smart contract concept that was proposed with it. Ethereum provides a platform for developing decentralized apps and smart contracts. (It is a distributed computing platform that is designed to run smart contracts.)

Ether is a value token of the Ethereum blockchain. It is listed as ETH on cryptocurrency exchanges.

Smart contract

A smart contract is a computer program or a transaction protocol that is intended to automatically execute, control, or document legally relevant events and actions according to the terms of a contract or an agreement.

The main contribution of smart contract is making the blockchain applications programmable, and it brought the blockchain applications beyond just transfer currency. It makes the verification of the terms of any agreement automatic. Thus all operations, which depend on a condition, can be figured out without any middleman or third party’s intervention.

Smart contracts provide the following benefits:

  • Transparency: Since smart contracts are deployed to the Ethereum network like a transaction after compile, these contracts are fully accessible and visible to all the relevant parties.
  • Security: The conditions and environments of where to keep smart contracts are a secure place, much as cryptocurrencies have.
  • Trust: By keeping smart contracts in a place that is as secure as cryptocurrencies, the secure, autonomous, and transparent nature of blockchain can be provided for smart contracts too. Knowing that the possibility of making manipulations on information placed in a block is very low helps us to trust.
  • Speed: Smart contracts live on the internet and run on software code. Thus it verifies transactions very fast. This speed can save many wasted hours caused by humans.
  • Saving: Smart contracts eliminate the need for having a middleman or third-party authority to determine what to do according to the terms of the agreement. Thus, they save wasted money besides wasted time, too. That means there is no need for lawyers, banks, witnesses, and any other intermediaries.

Ethereum Virtual Machine (EVM)

The Ethereum Virtual Machine (EVM) is a powerful, sandboxed virtual stack embedded within each full Ethereum node, responsible for executing contract bytecode. EVM provides that the machine code is completely isolated from the network, filesystem, or any processes of the host computer. It enforces all nodes in the Ethereum network to run the same instructions or operations, though they are independent of each other (Ethereum network uses Sandbox on EVM).

EVM mainly handles smart contract deployment and execution, besides preventing infinite loops not caused by us and various malicious attacks that are made on the network. Every node in the Ethereum network runs an EVM instance which allows them to agree on executing the same instructions.

EVM is Turing complete, which refers to a system capable of performing any logical step of a computational function.

The smart contract doesn’t publish immediately, for security purposes. Smart contracts are typically written in higher-level languages, like Solidity. Then the Solidity code we have written is compiled by the Ethereum compiler to generate EVM bytecode. After that, the Solidity code is ready to deploy into the network in EVM bytecode format, and then it can be executable.

diagram of a smart contract’s compile and deploy process
A Smart Contract’s compile and deploy process

After the smart contract is deployed to the Ethereum network, whenever any node runs it, it must be run by all nodes in the Ethereum ecosystem. At this point, if one contract has an infinite loop, every node on the network will get stuck executing the loop forever. (It may happen accidentally or on purpose.) If it happens accidentally, this circumstance causes a problem for the transaction’s sender. It can happen on purpose through a denial-of-service attack (DDoS). At this point, EVM helps to protect the Ethereum network from both kinds of problems.

Denial-of-service attack (DDoS): Since every node works on EVM, if one contract has an infinite loop, every node on the network will get stuck executing the loop forever. Thus by the halting problem, it is impossible to determine ahead of time whether the contract will ever terminate.

Gas

In Ethereum, gas is used to keep safe the Ethereum network from these kinds of problems. To perform a transaction on the Ethereum network, a sender who sends a transaction is required to make a payment to the miner ether via an intermediary token called gas (that is what we need to execute a contract). It is a unit that allows you to measure the computational work required for running a smart contract or other transactions.

The table below shows which operation needs how much gas. Every line of code in Solidity requires a certain amount of gas to be executed. Therefore, the gas amount required to finish any operation depends on the operation that will be executed in the smart contract, and it is calculated according to the table below before the smart contract is executed.

gas amount table
Gas Amount Table

Ether and gas are different things. Gas is the amount of computational power required in a transaction, and ether is the currency used to pay for that gas. The gas price (in terms of ether) is the amount that corresponds to a unit of gas. After calculating the gas amount required, the amount that is taken from the sender’s account is calculated by multiplying the gas amount and gas price. In general, this amount is paid in the gwei unit.

Gwei is a small piece of ether, like the euro and the cent. (Ether corresponds to the euro, and gwei corresponds to the cent).

1 gwei equals 0.000000001 ETH and 1 ETH equals one billion gwei.

There are several units besides gwei such as wei, kwei, mwei, etc.

The gas price can be increased/decreased depending on the number of transactions in the network.

  • As network traffic increases, the gas price will be increased.
  • As network traffic decreases, the gas price will be decreased.

Although the gas price is changeable, the amount of gas required to run a particular transaction is fixed. (This ensures that complex operations always require more gas than simple operations).

Gas Limit

In the operational view, all senders must specify an amount called the gas limit, which is the maximum amount of gas the sender is willing to pay for this transaction before they submit it to the network, and then this amount sends with the related transaction. Thus, the miner can afford what it spends.

If they want to be verified for their own transaction, the main concern that senders should give attention to is specifying the gas limit as close as possible to the gas price related to the transaction. The following steps describe the main principle in the gas limit. (The gas amounts used below are not correct but are just to help you to understand general concepts.)

  • Storing 11 in a variable = 45 gas
  • Adding two variables = 10 gas
  • Storing the result costs = 45 gas
  • Total gas the operation will be needed = 100 gas
  • The sender must specify a gas limit = 120 gas
  • 120–100 = 20 gas is unused and it sent back to the sender account

Here, specifying the gas limit too low or too high causes the following problems that we should avoid:

  • If the gas limit is specified too low, a “run out of gas” situation happens, and the contract reverts to the original state. However, this reverting operation still needs operational costs, and it affords them by cutting from the gas that the sender paid before. Let’s assume the total gas the operation will need = 100 Gas. The sender must specify a gas limit = 90 Gas. As a result, the “run out of gas” situation happens, and then the sender will be charged with sender fees as much as it’s worth to revert operations.
  • If the gas limit is specified too high, then, in general, the miners avoid them and prefer the transactions that have a small gas limit because they know that it is possibly bloated.

Why Is Gas Important?

Regardless of the reasons (accidentally or intentionally), gas is used to protect the network against getting stuck because of the infinite running of any loop.

  • It protects the sender to pay an extra payment if the transaction enters an infinite loop or operations continue more than expected — When it happens accidentally, the transaction would make unnecessary operations, and computational power and resources on the network are wasted. The one who pays all these wasted computational power and resources will be the sender of the related transaction, which means the sender will suffer from this circumstance.
  • It protects the Ethereum network from denial-of-service attacka (DDoS) — When it happens on purpose, that means it is a DDoS attack. If an attacker wants to make a DDoS attack, they should supply enough ether amount to fund the attack. Thus, it allows an attacker to avoid carrying out any DDoS attack.
Solidity trademark

Solidity

Solidity is an object-oriented, high-level language for implementing smart contracts, and it is designed to target the Ethereum Virtual Machine (EVM), managing the behavior of accounts within the Ethereum state.

It is a contract-oriented language, which means that smart contracts are responsible for storing all of the programming logic that transacts with the blockchain.

With Solidity, any contract can be developed for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets.

Among several methods (i.e., solc-js, a Node.js framework, or up-to-date Docker builds) to compile the Solidity code and compile it, Remix IDE is a powerful, open source tool that helps you write Solidity contracts straight from the browser without installing anything. Written in JavaScript, Remix supports both usage in the browser and locally. Remix also supports testing, debugging, and deploying smart contracts, and much more.

The following elements that of a smart contract are good to understand the general structure of a smart contract.

Declaring a contract

The Solidity version and the contract name must be declared by the following.

pragma solidity ^0.4.24;contract MyContract {
// do something
}

Importing other source files

Ethereum Solidity supports import statements that are very similar to those available in JavaScript, although Solidity does not know the concept of a “default export.”

import "filename";----- OR -----import * as symbolName from "filename";

Comments

Just like any other language, single-line and multi-line comments are possible in Solidity.

// This is a single-line comment.----- OR -----/*
This is a
multi-line comment
*/

Variables

Solidity supports the following variables:

  • state variables permanently stored in contract storage
  • local variables — presented till the function is executing
  • global variables special variables that exist in the global namespace and are used to get information about the blockchain
pragma solidity …contract HelloWorld{
uint storedData; // state variable

function getResult() public view returns(uint){
uint a = 1; // local variable
}
}

Variable scope

Solidity supports the following types of visibilities that are common for both functions and variables

  • public public functions or variables that can be called internally or through messages
  • internal — functions and variables only available to the current contract and derived contracts
  • private — only available to the current contract and not derived contracts
  • external — can just be used to functions to be called from other contracts and transactions

Data types

The following types are also called value types because variables of these types will always be passed by value.

  • boolean bool; the possible values are constants, i.e., true or false
  • integer int/uint; signed and unsigned integers of various sizes
  • string string; string literals are written with either double or single-quotes “foo” or ‘bar’
  • addressaddress/address payable holds a 20-byte value, the size of an Ethereum address, etc.

Address types

Address types also have members and serve as a base for all contracts. There are two types of address: address holds a 20-byte value, and address payable is the same as address above but just has transfer and send members. The distinction between address/address payable is that address payable is an address you can send ether to, while a plain address cannot be sent Ether.

Implicit conversions from address payable to address are allowed, whereas conversions from address to address payable are not allowed. Address type has several members:

  • balance returns the balance of given address (in units of wei)
  • transfer sends a given amount to a given address (in units of wei)
  • send sends a given amount of wei to a given address (not a safe alternative for transfer)

Data structures

The following types are specialized in Solidity:

  • Struct struct Solidity provides a way to define new types in the form of structs. Structs are custom-defined types that can group several variables.
  • Array[] Arrays can have a compile-time fixed size, or they can have a dynamic size.
  • Mapping mapping(k => v) Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value, etc.

Data locations

All reference types contain information on where they are stored, and there are three areas to store them:

  • Storage State variable, local variables of struct, array, and mapping: Each account has its own storage, which is persistent between function calls and transactions.
  • Memory Function arguments, which a contract obtains a freshly cleared instance for each message call. It holds temporary values and gets erased between (external) function calls and is cheaper to use.
  • Stack — Small local variables. The EVM is not a register machine but a stack machine, so all computations are performed on a data area called the stack. It holds small local variables and is almost free to use, but can only hold a limited amount of values.

Functions

In a function, <parameter types> can be empty, but <return types> must be filled.

  • Internal functions can only be called inside the current contract.
  • External functions consist of an address and a function signature, and they can be passed and returned from an external function.
function (<parameter types>) {internal|external} [pure|view|payable] [returns (<return types>)]

Type of functions

pure ensures that they do not change the state (it can be converted to view).

view does not read from state or modify the state.

payable makes it so ether can be sent in the function.

fallback does not have any arguments and does not return anything, but it is especially used for sending Ether, writing to storage, and creating a contract.

Functions can be set as view and pure to restrict reading and modifying of the state.

Method overloading

Function overloading occurs when several functions in a contract have the same name but differing arguments.

function sayHi(string n1) public pure returns (string out) {
out = "Hi " + n1 + " !" ;
}
function sayHi(string n1, string n2) public pure returns (string out) {
out = "Hi " + n1 + " and " + n2 + " !" ;
}

Modifiers

Modifiers are defined to change the way functions work in Solidity. By using modifiers, the condition, which is checked before the function execution, can be set.

pragma solidity ^0.4.24;contract MyContract {
constructor() public { owner = msg.sender; }
address payable owner;
modifier onlyOwner {
require(msg.sender == owner, "Only owner can call this function.");
_; // When the owner calls this function, it executes. Otherwise, it throws an exception.
}
function close() public onlyOwner {
// do something
}
}

I hope this article is good to guide someone who is new to Ethereum and smart contract technologies and wants to be familiar with the concepts proposed with blockchain.

--

--