This blog about Solidity tutorials showcases many Solidity features. This tutorial assumes that you have some knowledge of ethereum virtual machines and programming.

Ethereum, the “world computer” provides a very powerful global shared infrastructure for building decentralized applications using a programming language called Solidity.

Let’s start our Solidity tutorial and introduce Solidity.

What is Solidity?

Ethereum Solidity is a high-level language for smart contracts with a JavaScript like syntax. Solidity is a tool for generating machine-level code to execute on EVM. The Solidity compiler takes the high-level code and breaks it down into simpler instructions. The Solidity code is wrapped in Contracts.

Solidity in ethereum contracts

Contracts are the basic building blocks of decentralized ethereum applications. All variables and functions are part of the contract, which is the starting point for all projects. An empty contract called MyFirst looks like this:

Version pragma ^ 0.4.19; contract MyFirst{ }Copy the code

Keep your eyes on your screen because next in our Solidity tutorial we are going to start coding…

Layout of Solidity files

Source files can contain any number of contract definitions, including directives and pragma directives.

Version Pragma

Version Pragma is a declaration that defines the Version of the Solidity compiler to use for your code.

Version pragma ^ 0.4.00;Copy the code

Note: The source file shown above will not be compiled with a compiler prior to version 0.4.0 and will not run on a compiler starting with version 0.5.0.

Import other source files

Ethereum Solidity supports import statements that are very similar to those available in JavaScript, even though Solidity is unaware of the concept of default export.

At the global level, import statements of the following form can be used:

import "filename";
Copy the code

The above statement imports all global symbols from filename into the current global scope.

import * as symbolName from "filename";
Copy the code

annotation

Just like any other language, Solidity can use single-line and multi-line comments.

// This is a single-line comment.
/*
This is a
multi-line comment
*/
Copy the code

Now, before we delve further into the Solidity tutorial, it should be known that Ethereum has three areas where projects can be stored.

  • Storage: The location where all contract status variables are located. Each contract has its own store and is persistent between function calls.
  • Memory: Holds temporary values and erases them between (external) function calls, and is cheaper to use.
  • Stack Stack: Holds small local variables and is almost free to use, but only a limited number of values.

For almost all types, it is impossible to specify where they should be stored because they are copied every time they are used.

Ok, now that you know where to store in Ethereum Solidity, let me tell you the general value types.

Value types in solidity

The following types are also called value types because their variables are always passed by value.

Boolean

Key words: bool

The value is a constant, true or false.

The integer

Key words: int/uint (uint8 to uint256, step size is 8 (unsigned, maximum 256 bits), int8 is int256)

Signed and unsigned integers of various sizes.

Ex. :

contract MySample{
uint UnsignedInt =50;
}
Copy the code

In the above statement, we create a uint named InsignedInt and set it to 50.

address

Keyword: address

Save a 20-byte value (the size of the Ethereum address). Address types also have members and serve as the basis for all contracts.

Address member: Balance and Transfer

You can use the balance attribute to query the balance of an address and use the Transfer function to send Ethernet to the address.

address x = 0x123;
address myAddress = this;
if  (x.balance < 10 && myAddress.balance > = 10)
x.transfer(10);
Copy the code

string

String: String literals are written in double or single quotation marks such as “foo” or ‘bar’.

For UTF data of any length.

string language ="Solidity";
Copy the code

These value types can interact with each other in expressions that contain operators. Next, in our Solidity tutorial, let me show you the various operators.

The operator

Solidity has the same operators as JavaScript. Solidity has four types of operators:

Arithmetic operator

Solidity has very simple math. The following is similar to most programming languages:

  • Add: x + y
  • Minus x minus y
  • Multiplication: x * y
  • Division: x/y
  • Integer/remainder: x % y

Solidity also provides options for using exponential operators as follows:

uint x = 10 **  3; // equal to 10^3 = 1000
Copy the code

Increment operator

Stability of increment operators: A ++, a-, ++a, -a, a+=1, a=a+1

Similar rules apply to other programming languages.

Bitwise operators

Here are operators: (OR) by location ‘|’, (the bitwise xor), (as a complementation) ‘~’, (at right) ‘> >’, (by a shift to the left) ‘< <‘

Logical operator

Logical operators in Solidity:! (negative), && (logic), | | (logical or) = = (equal),! = (unequal)

Ex. :

contract operators { // Arithmetic Operators // +,-,*,/, %, ** // Incremental Operators // a++, a--, a+=1, a=a+1,++a,--a; a=10; a= a++; //here, output will be 10, because the value is first returned and then then increment is done a=++a; //Logical Operators ! , &&, | | = =,! = isOwner = true && false; var orValue= 0x02 | 0x01; // output would be 0x03 //Bitwise Operators~,>>, <<; function Operators() { // Initialize state variables here}}Copy the code

More complex data types are sometimes required now. For this, Solidity provides the structure.

Solidity data structure

Solidity provides three types of data structures:

Structure of user-defined Structs

Solidity provides a way to define new types in Structs form. Structs are custom types that can group multiple variables.

Pragma solidity ^ 0.4.0; contract Ballot { struct Voter { // Struct uint weight1, weight2, weight3; bool voted; address delegate1, delegate2, delegate3, delegate4; string name; uint vote1, vote2, vote3, vote4, vote5; uint height1, height2, height3 } }Copy the code

Note: A structure can have only 16 members, more than that may cause the following errors: Stack too Deep.

Structure allows you to create more complex data types with multiple attributes.

Now, what if you need some collection, like an address? Well, like most languages, Solidity has arrays.

An array of Arrays

Arrays in Solidity can have compile-time fixed sizes or be dynamic.

uint[3] fixed;  //array of fixed length 3
uint[] dynamic; //a dynamic array has no fixed size, it can keep growing
Copy the code

You can also create a structured array. Use the Voter structure you created previously:

Voter[] voting;
Copy the code

Note: Declaring an array public automatically creates getter methods for it.

Voter[] public voting;
Copy the code

Mapping the mappings

Maps can be thought of as hash tables that are virtually initialized such that every possible key exists and is mapped to a value whose byte representation is all zero: the default value of the type.

The mapping is declared as:

Mapping(_Keytype => _ValueType )
Copy the code

Note: _Keytype can be almost any type except dynamically sized arrays, contracts, enumerations, and structures.

Ex. :

contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) {
balances[msg.sender] = newBalance;  }}
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}}
Copy the code

Control structure

With the exception of Switch and Goto, most of the control structures in JavaScript are available in Solidity.

So: if, else, while, do, for, break, continue, return,? :, using the usual semantics known from C or JavaScript.

Note: There are no conversions from non-Booleans to Booleans like in C and JavaScript.

Now let’s see how these control structures can be used in Solidity.

contract ControlStructure { address public a; function ControlStructure>){ // if-else can be used like this if(input1==2) a=1; else a=0; // while can be used like this while(input1>=0){ if(input1==5) continue; input1=input1-1; a++; } // for loop can be used like this for(uint i=0; i<=50; i++) { a++; if(a==4) break; } //do while can be used like this do { a--; } (while a>0); // Conditional Operator can be used like this bool IsTrue = (a == 1)? true: false; /*will show an error because there is no type conversion from non-boolean to boolean */ if(1) { }Copy the code

Continuing with our Solidity tutorial blog, let’s talk about executable units of code in contracts. These are called functions.

function

Here is how to declare functions in Solidity.

function sampleFunc(string name, uint amount) {
}
Copy the code

The above declaration is an empty function that takes two arguments: a string and a uint.

This function can be called like this:

sampleFunc("Shashank", 10000);
Copy the code

Speaking of functions, Solidity also provides function modifiers.

Function modifier

It is used to easily change the behavior of functions. These conditions can be checked even before a function call, because they are declared in the function definition of the smart contract.

Example: If you want to call the kill Contract function only through the owner or creator of the function.

contract FunctionModifiers{ address public creator; function FunctionModifiers() { creator = msg.sender; } Modifier onlyCreator() { if(msg.sender! =creator){ throw; } _; //resumes the function wherever the access modifier is used } function killContract() onlyCreator{ //function will not execute if an exception occurs self-destruct(creator); }}Copy the code

inheritance

Solidity supports multiple inheritance by copying code that contains polymorphism.

contract Owned {
address Owner ;
function owned() {
owner = msg.sender;
}}
contract Mortal is Owned {  // 'is' keyword is used for inheritance
function kill(){
self-destruct(owner);   }}
contract User is Owned, Mortal //Multiple inheritance
{
string public UserName;
function User(string _name){
UserName = _name;
}}
Copy the code

Well, I think the concepts discussed above are enough to get you started programming with Solidity.

Go write code!!

With this I have finished this Solidity Tutorial blog. I hope you enjoy reading this blog and find it informative. By now, an understanding of Solidity Programming Language is essential. Now go practice.

If you’re looking for a quick start on Ethereum development, check out this tutorial: Getting Started with Ethereum, which focuses on smart contracts and DApp development.

Other blockchain tutorials are as follows:

  • Ethereum development advanced tutorial, mainly introduces the use of Node.js, mongodb, blockchain, IPFS to achieve decentralized e-commerce DApp combat, suitable for advanced.
  • Java Ethereum development tutorial, mainly for Java and Android programmers for blockchain Ethereum development web3J details.
  • Python Ethereum is a detailed explanation of blockchain ethereum development by Python engineers using Web3.py.
  • PHP Ethereum mainly introduces the use of PHP for smart contract development interaction, account creation, transactions, transfers, token development, filters and events and other content.
  • C# ethereum, mainly explains how to use C# based development. Net ethereum applications, including account management, status and transactions, smart contract development and interaction, filters and events, etc.
  • PHP currency development tutorial, this course for beginners, content covers the core concepts of COINS, such as block mechanism, key chain store, decentralized consensus and script, trading and UTXO etc, also explained how to integrated the currency support functions in PHP code, such as creating address wallet, tectonic naked trading, management, This is a rare bitcoin development course for Php engineers.
  • This course will help you quickly get started on the development of EOS blockchain decentralized applications, covering core knowledge points such as EOS tool chain, account and wallet, issuing tokens, development and deployment of smart contracts, using codes to interact with smart contracts, and finally completing the development of a notepad DApp using all knowledge points comprehensively.

Huizhi net original translation, reprint please indicate the source. Here is the original text