You get a bonus - 1 coin for daily activity. Now you have 1 coin

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Lecture



Solidity — is an object-oriented, domain-specific programming language for self-executing contracts on the Ethereum platform.

Smart contract (English: Smart contract) — is a computer algorithm designed to form, control, and provide information about the ownership of something. Most often this refers to the use of blockchain technology. In a narrower sense, a smart contract is understood as a set of functions and data (the current state) located at a specific address on the blockchain .

Ethereum smart contracts are developed in one of the languages designed to compile into the bytecode of the Ethereum virtual machine — Solidity (similar to C or JavaScript), Vyper and Serpent (similar to Python), LLL (a low-level version of Lisp), Mutan (based on Go) .

The parties sign the smart contract using methods similar to signing a transfer of funds in existing cryptocurrency networks. Once signed by the parties, the contract is stored on the blockchain and takes effect. To ensure the automated execution of the contract's obligations, an execution environment (Ethereum blockchain nodes) is absolutely required, which makes it possible to fully automate the execution of the contract's clauses. This means that smart contracts can exist only within an environment that gives the executable code unimpeded access to the smart contract's objects.

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Diagram of the architecture of an Ethereum node

All the terms of the contract must have a programmatic description and clear execution logic. For this reason, the first smart contracts had the task of formalizing the simplest relationships, consisting of a small number of conditions. Having unimpeded access to the contract's objects, the smart contract tracks, according to the specified conditions, the fulfillment or violation of clauses and makes independent decisions based on the programmed conditions. Thus, the core principle of a smart contract lies in the full automation and reliability of the execution of contractual relationships .

For smart contracts to be able to exist, certain conditions are required:

  1. The use of widely adopted electronic signature methods based on public and private keys (asymmetric encryption).
  2. The existence of open, decentralized databases, trusted by the parties to the contract, for executable transactions, the operation of which completely excludes the human factor. As an example: the blockchain in Bitcoin.
  3. Decentralization of the smart contract execution environment. As an example: Ethereum, Codius, Counterparty (English)Russian..
  4. The reliability of the source of digital data. As an example: root SSL certificate authorities in the databases of modern internet browsers[10].

Objects of a smart contract

  • Signatories — the parties to the smart contract who accept or reject the terms using electronic signatures. A direct analog is the signature of the sender of funds in the Bitcoin network, which confirms the addition of the transaction to the chain of blocks.
  • Subject of the contract. The subject of the contract can only be an object that exists within the environment of the smart contract itself, or the smart contract must be provided with unimpeded, direct access to the subject of the contract without human involvement.
  • Conditions. The conditions of a smart contract must have a complete mathematical description that can be programmed into the environment in which the smart contract exists. It is in the conditions that the execution logic of the clauses of the subject of the contract is described.
  • Decentralized platform. For the distributed storage of a smart contract, it needs to be recorded on this platform's blockchain[11].

History

The language was proposed in August 2014 by Gavin Wood (Gavin Wood ). Later, development of the language was carried out under the direction of Christian Reitwiessner by the Solidity team as part of the Ethereum project. It is one of four languages (alongside Serpent, LLL, and Mutan) designed to compile into the bytecode of the Ethereum virtual machine. It became widespread with the emergence of blockchain technologies, in particular the Ethereum-based technology stack, for creating smart contract software.

Contract code

Ethereum not only stores transaction data on the chain, but can also store the contract code on the chain.

At the database level, the role of the blockchain is to store transaction data. So what, then, is the logic of voting for candidates or obtaining voting results? In the world of Ethereum, you can use the Solidity language to write business logic / application code (that is, contract: Contract), then compile the contract code into Ethereum bytecode and deploy the bytecode to the blockchain. :

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Other languages can be used to write contract code, but Solidity is by far the most popular choice.

Ethereum Virtual Machine

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

It is important to note that the Ethereum virtual machine is fully isolated. This means that code currently running in the EVM has no access to the network or the file system, and can access other contracts only in a limited way.

The Ethereum blockchain not only stores data and code, every node also contains a virtual machine (EVM: Ethereum Virtual Machine) for executing the contract code - it sounds like a computer's operating system.

In fact, this is the key point that distinguishes Ethereum from Bitcoin: the existence of the virtual machine led to the emergence of blockchain 2.0, and also made the blockchain the first developer-friendly platform for developers. ,

Description

A statically typed, JavaScript-like programming language created for developing self-executing contracts that run on the Ethereum Virtual Machine (EVM). Programs are compiled into EVM bytecode. It allows developers to create self-contained applications containing business logic that results in irreversible blockchain transaction records.

The use of ECMAScript syntax, by Wood's design, was meant to help the language gain acceptance among actual web developers. However, unlike ECMAScript, the language received static typing of variables and dynamic types of return values. Compared to Serpent and Mutan, which compile to the same bytecode, the language has important differences. Complex contract variables are supported, including arbitrary hierarchical mappings and structs. Contracts support inheritance, including multiple inheritance and C3 linearization. A binary application programming interface (ABI) is supported, providing many type-safe functions in each contract (it subsequently also appeared in Serpent). A code documentation system for user-facing explanation of the call sequence has been specified, called the «Ethereum Natural Specification Format». In Solidity, instead of the usual classes, contracts are declared (contract). There are libraries for writing smart contracts, such as: Open Zeppelin, Truffle. The libraries allow you to create your own coin (token) based on ready-made templates, with all the specifications (ERC20) and security checks (the safemath library).

Contracts in Solidity can inherit from one another. This means that the functions and variables of the contract we inherit from will be available in the inheriting contract. In Solidity, just as in C++, there is multiple (diamond) inheritance.

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Example of a program in the Solidity language :

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

DAPP Architecture

The following figure shows the decentralized architecture of an Ethereum-based application:

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

DAPP architecture diagram

Each client (browser) interacts with the corresponding node application instance, rather than requesting services from a centralized server.

In an ideal decentralized environment, everyone who wants to interact with a DApp should run a full blockchain node on their computer or mobile phone - in short, everyone runs a full node , This means that before actually using the decentralized application, users must download the entire blockchain.

However, we do not live in a utopia. It is unrealistic to expect every user to run a full node before using your application. But the core idea of decentralization is that it does not depend on a centralized server. That is why some solutions have appeared in the blockchain community, such as Infura, which provides publicly accessible blockchain nodes, and Metamask, a browser plugin. Thanks to these solutions, you don't need to spend a lot of hard drive space, memory, and time downloading and running a full blockchain node, and you can still take advantage of decentralization.

Basics of the Solidity language

all Solidity contracts contain the following elements:

  • Pragma directives
  • State variables
  • Functions
  • Events

To program smart contracts for production environments, you will need to become more familiar with them, but here you will get general information that will serve as a starting point for studying this technology.

Once you understand these principles, you will be able to start creating your own smart contracts for a wide variety of purposes!

Pragma Directives

Pragma — is a keyword that the compiler uses to check whether the Solidity version matches the required one. If the versions match, the file can be executed. Otherwise, the compiler returns an error.

The contract definition must always include the latest version of Solidity. Information about the current version can be obtained on the Solidity website. The most recent version must be used in the source file.

The version-defining Pragma directive looks as follows:

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

This line indicates that a compiler version from 0.7.0 to 0.7.9 will be used to compile the source file. As a result of the changes that will be made in version 0.8.0, compilation of this source file will most likely fail.

State Variables

State variables are the fundamental elements of any Solidity source file. The values of state variables are permanently stored in the contract's storage.

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Note

At the beginning of the contract's source file, the definition contract ContractName is always specified.

This example uses the state variable price with type uint. The integer type uint indicates that this variable can hold a 256-bit unsigned integer. Thus, it can store positive numbers in the range from 0 to 2256–1.

In the definition of any variable, its type and name must be specified.

In addition, you can set the visibility of a state variable as follows:

  • public — an element of the contract interface, accessible from other contracts.
  • internal — an element accessible only from the current contract.
  • private — an element accessible only within the contract in which it is defined.

Functions

Within a contract, executable units of code are called functions. Functions are used to describe individual actions needed to accomplish an overall task. Functions can be reused and called from other source files, such as libraries. The behavior of functions in Solidity is similar to other programming languages.

Below is a simple example of a function definition:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

This code shows a function named buy, which has public visibility and is therefore accessible from other contracts. The following function visibility specifiers are supported: public, private, internal, and external.

A function call can be either internal or external (from another contract). Functions can accept parameters and return variables, which are used to pass parameters and values between them.

Below is an example of a function that takes the integer parameter price and returns an integer:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Function Modifiers

Modifiers can be used to change the behavior of functions. If a modifier is set, the corresponding condition is checked before the function executes. For example, in this way a function can check whether the user has seller rights before listing an item for sale.

  Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

The following elements are used in this example:

  • A variable of type address, which will store the 20-byte Ethereum address of the user with seller rights. You will get to know these variables in more detail later in this module.
  • A modifier named onlySeller, which specifies that only the seller can list an item for sale.
  • The special symbol _;, which indicates where the function body is inserted.
  • A function definition that uses the modifier onlySeller.

The following modifiers can also be used in a function definition:

  • pure — describes functions for which changing the state or accessing information about it is not allowed.
  • view — describes functions for which changing the state is not allowed.
  • payable — describes functions that can accept "ether".

Events

Events are used to describe actions that take place within a contract. Like functions, events use parameters that must be specified when they are invoked.

To trigger an event, you must use the emit keyword, specifying the event's name and its parameters.

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

When an event is triggered, it is recorded as a transaction in the transaction log, which is a special data structure on the blockchain. Such logs are linked to the contract's address, included in the blockchain, and remain there forever. The log and the event data it contains are not accessible from contracts and cannot be modified.

Value Types in the Solidity Language

Value types pass values and are copied when used. The main value types that will be

used when writing contracts include integers, booleans, string literals, addresses, and enumerations.

Integers

Integer types are used in every Solidity source file. They represent whole numbers and can be signed or unsigned. Integer types can hold from 8 to 256 bits.

  • Signed types: include negative and positive numbers. Can be represented as an int value.
  • Unsigned types: include only positive numbers. Can be represented as a uint value.

If the number of bits is not explicitly specified, it defaults to 256 bits.

The following operations can be applied to integers:

  • Comparison operators: <=, <, ==, !=, >=, >
  • Binary operators: & (and), | (or), ^ (bitwise exclusive), ~ (bitwise negation)
  • Arithmetic operators: + (addition),- (subtraction), * (multiplication), / (division), % (modulo), ** (exponential)

Below are examples of integer value definitions:

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Boolean

Boolean values are defined using the bool keyword. They always have either the value true or false.

Below is shown how they can be defined:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Boolean values are usually used in comparison statements. Example:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

In addition, boolean values can be used in function parameters and return value types.

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

String Literals

String literals are also used in most contract files. They represent a sequence of characters or words enclosed in double or single quotes.

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

In addition, the following escape characters can be used together with string literals:

  • \ — escape sequence for a new line
  • \n — new line
  • \r — carriage return
  • \t — tab

Address

Address — is a type with a 20-byte value that represents an Ethereum user account. To define an address, you can use the regular type address or address payable.

The difference between them is that the address payable type defines an address to which "ether" can be sent, for which it uses the additional members transfer and send.

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Enumerations

In the Solidity language, you can use enumerations to create a user-defined data type. As the name implies, the values contained in such types are defined by the contract's creator. Enumerations can be used to define a set of choices, one of which is mandatory.

For example, an enumeration can be used to specify a set of possible states of an element. For convenience, an enumeration can be thought of as several predefined answer options to a question, one of which must be chosen. Enumerations can be declared within contract or library definitions.

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Reference Types in Solidity

To write contracts, you will also need to understand the principles of using reference types.

Unlike value types, which always pass an independent copy of the value, reference types point to the location of the data for the value. The following reference types are supported: structs, arrays, and mappings.

Data Location

When using a reference type, you must explicitly specify the storage location for its data. The data location for a type can be specified in the following ways:

  • memory:
    • The location where function arguments are stored.
    • Only valid during the call of an external function.
  • storage:
    • The location where state variables are stored.
    • Only valid during the existence of the contract.
  • calldata:
    • The location where function arguments are stored.
    • Required for external function parameters, but can also be used for other variables.
    • Only valid during the call of an external function.

Reference types always create an independent copy of the data.

Below is an example of using a reference type:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Arrays

Arrays are used to store similar data in a data set structure. The size of an array can be fixed or set dynamically. Array indices start at 0.

To create a fixed-size array k containing elements of type T, you should use the expression T[k]. Dynamically sized arrays are defined as follows: T[].

Array elements can have any type. For example, an array can contain elements of type uint, memory, or byte. Arrays can also include mappings or structs.

The following example shows how to create an array:

 

Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Array Members

The following members can be used to manage arrays and obtain information about them:

  • length — get the length of the array
  • push() — add an element to the end of the array
  • pop — remove an element from the end of the array

Below are several examples.

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Structs

Structs — are custom types that a user can use to define a representation of real-world objects. As a rule, structs are used as a schema or to represent records.

Examples:

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Mapping Types

Mappings represent key-value pairs that are encapsulated or packaged together. The closest analogs of mappings are dictionaries or JavaScript objects. As a rule, mappings are used to model real-world objects and for faster data lookup. Thanks to support for various value types, including complex ones such as structs, this type is universal and easy for humans to understand.

The following code example uses the struct Items_Schema and stores a dictionary with a list of items represented by the struct Items_Schema. Thus, mappings can be used to simulate a database.

 Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Note

In the mapping signature uint256 => Items_Schema, it is specified that the keys are of unsigned integer type, and the values are the struct Items_Schema.

Example of a Simple Online Store in Solidity

  Solidity — the Programming Language of Self-Executing Contracts for Ethereum: The Basics

Let's take a closer look at the main components of this smart contract:

  • routes:
    • three state variables: buyer, seller and balances;
    • two events: ListItem and PurchasedItem;
    • one enumeration with two values: ItemAvailable and ItemPurchased.
  • A constructor that assigns the user msg.sender as the seller and sets the initial state to ItemAvailable. This constructor is called when the contract is created.
  • The buy function, which takes three parameters: seller, buyer, and price. Before making the purchase, it is verified that the buyer has sufficient funds. If so, money is transferred from the buyer to the seller, after which a message is issued.

self-check tests

1. Where do Solidity smart contracts run:
  • in the Ethereum blockchain - Incorrect. The Ethereum blockchain — is the name of the platform that the Solidity language is designed to work with. Tests are not executed in the Ethereum blockchain.
  • the Ethereum virtual machine -Correct. Solidity contracts run on the Ethereum virtual machine. This isolated environment contains all the transaction logs for contracts
  • any virtual machine -Incorrect. A virtual machine can be used to run tests, but Solidity smart contracts require a special type of virtual machine.
  • any sandbox environment -Incorrect. Solidity smart contracts run in an isolated environment, but a special type of environment is used for this purpose.
2. Events are used to describe actions performed in a contract. Which of the following shows the syntax for defining an event?
  • event PurchasedItemEvent -Incorrect. An event is triggered similarly to a function, using a set of parentheses at the end, for example event PurchasedItemEvent(). All required arguments are specified inside the parentheses.
  • event PurchasedItemEvent(address buyer, uint price); - Correct. To define an event, use the event keyword. You also need to give the event a name and, if necessary, specify arguments inside the parentheses.
  • emit PurchasedItemEvent(address buyer, uint price); -Incorrect. This syntax triggers the event and creates a record in the transaction log.
  • PurchasedItemEvent(address buyer, uint price); -Incorrect. This syntax calls a previously defined function, not an event.
3. Which of the following is an example of a user-defined type in Solidity?
  • Structs- Correct. Structs are a user-defined type, since a collection of elements can be defined within them.
  • State variables -Incorrect. State variables have a standard type (uint, int, bool, or address) and are used to store values used in contracts.
  • Addresses -Incorrect. Addresses — are types with a 20-byte value that represent an Ethereum user account. The value is set for the specified address type.
  • Arrays -Incorrect. Arrays use standard types to store a collection of similar elements of the same type in a data structure.
4. What is usually contained in the first line of a smart contract source file?
  • Contract definition -Incorrect. The contract definition is a required element of the source file, but it is not specified on the first line.
  • Pragma directive- Correct. Pragma — is a keyword that the compiler uses to check whether the Solidity version matches the required one.
  • Solidity version -Incorrect. The Solidity version is specified in the Pragma directive, but it does not include the keyword that is checked by the compiler.
  • Event -Incorrect. Events are used in most smart contracts, but they are not mandatory and are placed inside the contract definition.

External Link

  • [[b8300]]
  • [[b8133]]
  • [[b9306]]
  • [[b8475]]
  • [[b8718]]
  • [[b8782]]
  • Ethereum
  • CryptoKitties
  • Augur

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Object oriented programming"

Terms: Object oriented programming