Solidity - Quick Guide
Solidity - Quick Guide
Solidity - Overview
Solidity is a contract-oriented, high-level programming language for implementing smart
contracts. Solidity is highly influenced by C++, Python and JavaScript and has been designed to
target the Ethereum Virtual Machine (EVM).
Solidity is statically typed, supports inheritance, libraries and complex user-defined types
programming language.
You can use Solidity to create contracts for uses such as voting, crowdfunding, blind auctions,
and multi-signature wallets.
What is Ethereum?
Ethereum is a decentralized ie. blockchain platform that runs smart contracts i.e. applications
that run exactly as programmed without any possibility of downtime, censorship, fraud or third-
party interference.
The EVM specialised in preventing Denial-of-service attacks and ensures that programs do not
have access to each other's state, ensuring communication can be established without any
potential interference.
The Ethereum Virtual Machine has been designed to serve as a runtime environment for smart
contracts based on Ethereum.
The concept of smart contracts was first proposed by Nick Szabo in 1994. Szabo is a legal
scholar and cryptographer known for laying the groundwork for digital currency.
It is fine if you do not understand Smart Contract right now, we will go into more detail later.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 1/66
4/20/23, 2:48 PM Solidity - Quick Guide
Install Node.js
First make sure you have node.js available on your CentOS machine. If it is not available then
install it using the following commands −
If everything has been installed then you will see an output something like this −
3.10.10
Install solc
Once you have Node.js package manager installed then you can proceed to install Solidity
compiler as below −
The above command will install solcjs program and will make it available globally through out the
system. Now you can test your Solidity compiler by issuing following command −
$solcjs-version
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 2/66
4/20/23, 2:48 PM Solidity - Quick Guide
0.5.2+commit.1df8f40c.Emscripten.clang
Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but
it will give you a good starting point.
Once a docker image is downloaded we can verify it using the following command.
Let's start with a simple source file of Solidity. Following is an example of a Solidity file −
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 3/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
}
Pragma
The first line is a pragma directive which tells that the source code is written for Solidity version
0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0.
A pragma directive is always local to a source file and if you import another file, the pragma from
that file will not automatically apply to the importing file.
So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on
a compiler starting from version 0.5.0 will be written as follows −
Contract
A Solidity contract is a collection of code (its functions) and data (its state) that resides at a
specific address on the Ethereumblockchain.
The line uintstoredData declares a state variable called storedData of type uint and the functions
set and get can be used to modify or retrieve the value of the variable.
Importing Files
Though above example does not have an import statement but Solidity supports import
statements that are very similar to those available in JavaScript.
import "filename";
The following example creates a new global symbol symbolName whose members are all the
global symbols from "filename".
To import a file x from the same directory as the current file, use import "./x" as x;. If you use
import "x" as x; instead, a different file could be referenced in a global "include directory".
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 4/66
4/20/23, 2:48 PM Solidity - Quick Guide
Reserved Keywords
Following are the reserved keywords in Solidity −
Example
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Output
0: uint256: 3
Solidity - Comments
Solidity supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by
Solidity Compiler.
Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
Example
The following example shows how to use comments in Solidity.
/*
* This is a multi-line comment in solidity
* It is very similar to comments in C Programming
*/
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
Solidity - Types
While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 6/66
4/20/23, 2:48 PM Solidity - Quick Guide
Value Types
Solidity offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
Integer int8 to int256 Signed int from 8 bits to 256 bits. int256 is the same as int.
Integer uint8 to Unsigned int from 8 bits to 256 bits. uint256 is the same as
uint256 uint.
Fixed Point Numbers fixed/unfixed Signed and unsigned fixed point numbers of varying sizes.
Fixed Point Numbers fixed/unfixed Signed and unsigned fixed point numbers of varying sizes.
Fixed Point Numbers fixedMxN Signed fixed point number where M represents number of
bits taken by type and N represents the decimal points. M
should be divisible by 8 and goes from 8 to 256. N can be
from 0 to 80. fixed is same as fixed128x18.
Fixed Point Numbers ufixedMxN Unsigned fixed point number where M represents number
of bits taken by type and N represents the decimal points.
M should be divisible by 8 and goes from 8 to 256. N can
be from 0 to 80. ufixed is same as ufixed128x18.
Note: You can also represent the signed and unsigned fixed-point numbers as
fixedMxN/ufixedMxN where M represents the number of bits taken by type and N represents the
decimal points. M should be divisible by 8 and goes from 8 to 256. N can be from 0 to 80.
address
address holds the 20 byte value representing the size of an Ethereum address. An address can
be used to get the balance using .balance method and can be used to transfer balance to
another address using .transfer method.
address x = 0x212;
address myAddress = this;
if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);
Solidity - Variables
Solidity supports three types of variables.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 7/66
4/20/23, 2:48 PM Solidity - Quick Guide
State Variables − Variables whose values are permanently stored in a contract storage.
Local Variables − Variables whose values are present till function is executing.
Global Variables − Special variables exists in the global namespace used to get
information about the blockchain.
Solidity is a statically typed language, which means that the state or local variable type needs to
be specified during declaration. Each declared variable always have a default value based on its
type. There is no concept of "undefined" or "null".
State Variable
Variables whose values are permanently stored in a contract storage.
Local Variable
Variables whose values are available only within a function where it is defined. Function
parameters are always local to that function.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 8/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return storedData; //access the state variable
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: 10
Global Variables
These are special variables which exist in global workspace and provide information about the
blockchain and transaction properties.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 9/66
4/20/23, 2:48 PM Solidity - Quick Guide
Name Returns
blockhash(uint blockNumber) returns (bytes32) Hash of the given block - only works for 256
most recent, excluding current, blocks
You should not use any of the Solidity reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable names
are not valid.
Solidity variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but _123test is
a valid one.
Solidity variable names are case-sensitive. For example, Name and name are two different
variables.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 10/66
4/20/23, 2:48 PM Solidity - Quick Guide
Public − Public state variables can be accessed internally as well as via messages. For a
public state variable, an automatic getter function is generated.
Internal − Internal state variables can be accessed only internally from the current contract
or contract deriving from it without using this.
Private − Private state variables can be accessed only internally from the current contract
they are defined not in the derived contract from it.
Example
pragma solidity ^0.5.0;
contract C {
uint public data = 30;
uint internal iData= 10;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 11/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
}
Solidity - Operators
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and '+' is
called the operator. Solidity supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
Solidity supports the following arithmetic operators −
Show Example
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 12/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
+ (Addition)
2
- (Subtraction)
3
* (Multiplication)
4
/ (Division)
5
% (Modulus)
6
++ (Increment)
7
-- (Decrement)
Comparison Operators
Solidity supports the following comparison operators −
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 13/66
4/20/23, 2:48 PM Solidity - Quick Guide
Show Example
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 14/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
2
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
5
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 15/66
4/20/23, 2:48 PM Solidity - Quick Guide
Logical Operators
Solidity supports the following logical operators −
Show Example
1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
2
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Bitwise Operators
Solidity supports the following bitwise operators −
Show Example
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 16/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
& (Bitwise AND)
Ex: (A & B) is 2.
2
| (BitWise OR)
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
Ex: (A ^ B) is 1.
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in
the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.
6
>> (Right Shift)
Binary Right Shift Operator. The left operand's value is moved right by the number of
bits specified by the right operand.
Ex: (A >> 1) is 1.
7
>>> (Right shift with Zero)
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 17/66
4/20/23, 2:48 PM Solidity - Quick Guide
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
Solidity supports the following assignment operators −
Show Example
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 18/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |=
and ^=.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 19/66
4/20/23, 2:48 PM Solidity - Quick Guide
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.
Show Example
1
? : (Conditional )
Solidity - Loops
While writing a contract, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.
Solidity supports all the necessary loops to ease down the pressure of programming.
1
While Loop
The most basic loop in Solidity is the while loop which would be discussed in this
chapter.
2
do...while Loop
The do...while loop is similar to the while loop except that the condition check happens
at the end of the loop.
3
For Loop
The for loop is the most compact form of looping. It includes the following three
important parts.
4
Loop Control
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 20/66
4/20/23, 2:48 PM Solidity - Quick Guide
Solidity supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if..else statement.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 21/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
if statement
The if statement is the fundamental control statement that allows Solidity to make
decisions and execute statements conditionally.
2
if...else statement
The 'if...else' statement is the next form of control statement that allows Solidity to
execute statements in a more controlled way.
3
if...else if... statement.
The if...else if... statement is an advanced form of if...else that allows Solidity to make
a correct decision out of several conditions.
Solidity - Strings
Solidity supports String literal using both double quote (") and single quote ('). It provides string
as a data type to declare a variable of type String.
contract SolidityTest {
string data = "test";
}
In above example, "test" is a string literal and data is a string variable. More preferred way is to
use byte types instead of String as string operation requires more gas as compared to byte
operation. Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity
we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32
literal.
contract SolidityTest {
bytes32 data = "test";
}
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 22/66
4/20/23, 2:48 PM Solidity - Quick Guide
Escape Characters
Sr.No. Character & Description
1
\n
2
\\
Backslash
3
\'
Single Quote
4
\"
Double Quote
5
\b
Backspace
6
\f
Form Feed
7
\r
Carriage Return
8
\t
Tab
9
\v
Vertical Tab
10
\xNN
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 23/66
4/20/23, 2:48 PM Solidity - Quick Guide
11
\uNNNN
Example
Try the following code to understand how the string works in Solidity.
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 24/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
return string(bstr);
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: string: 3
Solidity - Arrays
Array is a data structure, which stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
In Solidity, an array can be of compile-time fixed size or of dynamic size. For storage array, it can
have different types of elements as well. In case of memory array, element type can not be
mapping and in case it is to be used as function parameter then element type should be an ABI
type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array of fixed size in Solidity, the programmer specifies the type of the elements
and the number of elements required by an array as follows −
This is called a single-dimension array. The arraySize must be an integer constant greater than
zero and type can be any valid Solidity data type. For example, to declare a 10-element array
called balance of type uint, use this statement −
uint balance[10];
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 25/66
4/20/23, 2:48 PM Solidity - Quick Guide
To declare an array of dynamic size in Solidity, the programmer specifies the type of the
elements as follows −
type[] arrayName;
Initializing Arrays
You can initialize Solidity array elements either one by one or using a single statement as follows
−
The number of values between braces [ ] can not be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
You will create exactly the same array as you did in the previous example.
balance[2] = 5;
The above statement assigns element number 3rd in the array a value of 5.
uint size = 3;
uint balance[] = new uint[](size);
The above statement will take 3rd element from the array and assign the value to salary variable.
Following is an example, which will use all the above-mentioned three concepts viz. declaration,
assignment and accessing arrays −
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 26/66
4/20/23, 2:48 PM Solidity - Quick Guide
Members
length − length returns the size of the array. length can be used to change the size of
dynamic array be setting it.
push − push allows to append an element to a dynamic storage array at the end. It returns
the new length of the array.
Example
Try the following code to understand how the arrays works in Solidity.
contract test {
function testArray() public pure{
uint len = 7;
//dynamic array
uint[] memory a = new uint[](7);
assert(a.length == 7);
assert(b.length == len);
//static array
uint[3] memory c = [uint(1) , 2, 3];
assert(c.length == 3);
}
}
Solidity - Enums
Enums restrict a variable to have one of only a few predefined values. The values in this
enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 27/66
4/20/23, 2:48 PM Solidity - Quick Guide
For example, if we consider an application for a fresh juice shop, it would be possible to restrict
the glass size to small, medium, and large. This would make sure that it would not allow anyone
to order any size other than small, medium, or large.
Example
Try the following code to understand how the enum works in Solidity.
contract test {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize choice;
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;
Run the above program using steps provided in Solidity First Application chapter.
First Click setLarge Button to set the value as LARGE then click getChoice to get the selected
choice.
Output
uint8: 2
Output
uint256: 1
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 28/66
4/20/23, 2:48 PM Solidity - Quick Guide
Solidity - Structs
Struct types are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Struct
To define a Struct, you must use the struct keyword. The struct keyword defines a new data
type, with more than one member. The format of the struct statement is as follows −
struct struct_name {
type1 type_name_1;
type2 type_name_2;
type3 type_name_3;
}
Example
struct Book {
string title;
string author;
uint book_id;
}
Example
Try the following code to understand how the structs works in Solidity.
contract test {
struct Book {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 29/66
4/20/23, 2:48 PM Solidity - Quick Guide
string title;
string author;
uint book_id;
}
Book book;
Run the above program using steps provided in Solidity First Application chapter.
First Click setBook Button to set the value as LARGE then click getBookId to get the selected
book id.
Output
uint256: 1
Solidity - Mapping
Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping
type.
Where
_KeyType − can be any built-in types plus bytes and string. No reference type or complex
objects are allowed.
Considerations
Mapping can only have type of storage and are generally used for state variables.
Mapping can be marked public. Solidity automatically create getter for it.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 30/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
Try the following code to understand how the mapping type works in Solidity.
contract LedgerBalance {
mapping(address => uint) public balances;
Run the above program using steps provided in Solidity First Application chapter.
First Click updateBalance Button to set the value as 10 then look into the logs which will show
the decoded output as −
Output
{
"0": "uint256: 10"
}
Solidity - Conversions
Solidity allows implicit as well as explicit conversion. Solidity compiler allows implicit conversion
between two data types provided no implicit conversion is possible and there is no loss of
information. For example uint8 is convertible to uint16 but int8 is convertible to uint256 as int8
can contain negative value not allowed in uint256.
Explicit Conversion
We can explicitly convert a data type to another using constructor syntax.
int8 y = -3;
uint x = uint(y);
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 31/66
4/20/23, 2:48 PM Solidity - Quick Guide
uint32 a = 0x12345678;
uint16 b = uint16(a); // b = 0x5678
uint16 a = 0x1234;
uint32 b = uint32(a); // b = 0x00001234
bytes2 a = 0x1234;
bytes1 b = bytes1(a); // b = 0x12
bytes2 a = 0x1234;
bytes4 b = bytes4(a); // b = 0x12340000
Conversion between fixed size bytes and int is only possible when both are of same size.
bytes2 a = 0x1234;
uint32 b = uint16(a); // b = 0x00001234
uint32 c = uint32(bytes4(a)); // c = 0x12340000
uint8 d = uint8(uint16(a)); // d = 0x34
uint8 e = uint8(bytes1(a)); // e = 0x12
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 32/66
4/20/23, 2:48 PM Solidity - Quick Guide
Time Units
Similar to currency, Solidity has time units where lowest unit is second and we can use seconds,
minutes, hours, days and weeks as suffix to denote time.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 33/66
4/20/23, 2:48 PM Solidity - Quick Guide
1
blockhash(uint blockNumber) returns (bytes32)
Hash of the given block - only works for 256 most recent, excluding current, blocks.
2
block.coinbase (address payable)
3
block.difficulty (uint)
4
block.gaslimit (uint)
5
block.number (uint)
6
block.timestamp
7
gasleft() returns (uint256)
Remaining gas.
8
msg.data (bytes calldata)
Complete calldata.
9
msg.sender (address payable)
10
msg.sig (bytes4)
11
msg.value (uint)
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 34/66
4/20/23, 2:48 PM Solidity - Quick Guide
12
now (uint)
13
tx.gasprice (uint)
14
tx.origin (address payable)
Example
Try the following code to see the use of msg, a special variable to get the sender address in
Solidity.
contract LedgerBalance {
mapping(address => uint) public balances;
Run the above program using steps provided in Solidity First Application chapter.
First Click updateBalance Button to set the value as 10 then look into the logs which will show
the decoded output as −
Output
{
"0": "uint256: 10"
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 35/66
4/20/23, 2:48 PM Solidity - Quick Guide
Code Layout
Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing
spaces with tabs.
Two Blank Lines Rule − Use 2 Blank lines between two contract definitions.
contract LedgerBalance {
//...
}
contract Updater {
//...
}
One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration,
no need to have blank lines.
contract A {
function balance() public pure;
function account() public pure;
}
contract B is A {
function balance() public pure {
// ...
}
function account() public pure {
// ...
}
}
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 36/66
4/20/23, 2:48 PM Solidity - Quick Guide
Maximum Line Length − A single line should not cross 79 characters so that readers can
easily parse the code.
Wrapping rules − First argument be in new line without opening parenthesis. Use single
indent per argument. Terminating element ); should be the last one.
function_with_a_long_name(
longArgument1,
longArgument2,
longArgument3
);
variable = function_with_a_long_name(
longArgument1,
longArgument2,
longArgument3
);
event multipleArguments(
address sender,
address recipient,
uint256 publicKey,
uint256 amount,
bytes32[] options
);
MultipleArguments(
sender,
recipient,
publicKey,
amount,
options
);
Imports − Import statements should be placed at the top of the file just after pragma
declaration.
Order of Functions − Functions should be grouped as per their visibility.
contract A {
constructor() public {
// ...
}
function() external {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 37/66
4/20/23, 2:48 PM Solidity - Quick Guide
// ...
}
// External functions
// ...
// Public functions
// ...
// Internal functions
// ...
// Private functions
// ...
}
Control structures − Braces should open on same line as declaration. Close on their own
line maintaining the same indentation. Use a space with opening brace.
contract Coin {
struct Bank {
address owner;
uint balance;
}
}
if (x < 3) {
x += 1;
} else if (x > 7) {
x -= 1;
} else {
x = 5;
}
if (x < 3)
x += 1;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 38/66
4/20/23, 2:48 PM Solidity - Quick Guide
else
x -= 1;
Function Declaration − Use the above rule for braces. Always add a visibility label.
Visibility label should come first before any custom modifier.
String declaration − Use double quotes to declare a string instead of single quote.
str = "foo";
str = "Hamlet says, 'To be or not to be...'";
Order of Layout
Elements should be layout in following order.
Pragma statements
Import statements
Interfaces
Libraries
Contracts
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 39/66
4/20/23, 2:48 PM Solidity - Quick Guide
Type declarations
State variables
Events
Functions
Naming conventions
Contract and Library should be named using CapWords Style. For example, SmartContract,
Owner etc.
Owned.sol
// Owned.sol
contract Owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
//....
}
function transferOwnership(address newOwner) public onlyOwner {
//...
}
}
Congress.sol
// Congress.sol
import "./Owned.sol";
Struct Names
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 40/66
4/20/23, 2:48 PM Solidity - Quick Guide
Function Names
− Use mixedCase Style like initiateSupply.
Solidity - Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, Solidity also supports all the features
necessary to write modular code using functions. This section explains how to write your own
functions in Solidity.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
Solidity is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 41/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
Try the following example. It defines a function called getResult that takes no parameters −
contract Test {
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result;
}
}
Calling a Function
To invoke a function somewhere later in the Contract, you would simply need to write the name
of that function as shown in the following code.
Try the following code to understand how the string works in Solidity.
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 42/66
4/20/23, 2:48 PM Solidity - Quick Guide
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);//access local variable
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: string: 3
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.
Example
Try the following example. We have used a uint2str function here. It takes one parameter.
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 43/66
4/20/23, 2:48 PM Solidity - Quick Guide
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);//access local variable
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: string: 3
In Solidity, a function can return multiple values as well. See the example below −
contract Test {
function getResult() public view returns(uint product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 44/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: product 2
1: uint256: sum 3
contract Owner {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
The function body is inserted where the special symbol "_;" appears in the definition of a
modifier. So if condition of modifier is satisfied while calling this function, the function is executed
and otherwise, an exception is thrown.
contract Owner {
address owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 45/66
4/20/23, 2:48 PM Solidity - Quick Guide
require(msg.sender == owner);
_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
contract Register is Owner {
mapping (address => bool) registeredAddresses;
uint price;
constructor(uint initialPrice) public { price = initialPrice; }
Emitting events.
Creating other contracts.
Using selfdestruct.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 46/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
pragma solidity ^0.5.0;
contract Test {
function getResult() public view returns(uint product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: product 2
1: uint256: sum 3
Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read).
Pure functions can use the revert() and require() functions to revert potential state changes if an
error occurs.
Example
pragma solidity ^0.5.0;
contract Test {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 47/66
4/20/23, 2:48 PM Solidity - Quick Guide
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: product 2
1: uint256: sum 3
It has no name.
It has no arguments
It can not return any thing.
Example
pragma solidity ^0.5.0;
contract Test {
uint public x ;
function() external { x = 1; }
}
contract Sink {
function() external payable { }
}
contract Caller {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 48/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
pragma solidity ^0.5.0;
contract Test {
function getSum(uint a, uint b) public pure returns(uint){
return a + b;
}
function getSum(uint a, uint b, uint c) public pure returns(uint){
return a + b + c;
}
function callSumWithTwoArguments() public pure returns(uint){
return getSum(1,2);
}
function callSumWithThreeArguments() public pure returns(uint){
return getSum(1,2,3);
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 49/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: 3
0: uint256: 6
Example
pragma solidity ^0.5.0;
contract Test {
function callAddMod() public pure returns(uint){
return addmod(4, 5, 3);
}
function callMulMod() public pure returns(uint){
return mulmod(4, 5, 3);
}
}
Run the above program using steps provided in Solidity First Application chapter.
Click callAddMod button first and then callMulMod button to see the result.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 50/66
4/20/23, 2:48 PM Solidity - Quick Guide
Output
0: uint256: 0
0: uint256: 2
Example
pragma solidity ^0.5.0;
contract Test {
function callKeccak256() public pure returns(bytes32 result){
return keccak256("ABC");
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: bytes32: result 0xe1629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa35d54f3c8
contract Test {
address payable public richest;
uint public mostSent;
Above contract can be rendered in unusable state by causing the richest to be a contract of
failing fallback function. When fallback function fails, becomeRichest() function also fails and
contract will stuck forever. To mitigate this problem, we can use Withdrawal Pattern.
In withdrawal pattern, we'll reset the pending amount before each transfer. It will ensure that only
caller contract fails.
contract Test {
address public richest;
uint public mostSent;
richest = msg.sender;
mostSent = msg.value;
return true;
} else {
return false;
}
}
function withdraw() public {
uint amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
}
We can restrict who can modify the contract's state or call a contract's functions using modifiers.
We will create and use multiple modifiers as explained below −
onlyBy − once used on a function then only the mentioned caller can call this function.
onlyAfter − once used on a function then that function can be called after certain time
period.
costs − once used on a function then caller can call this function only if certain value is
provided.
Example
pragma solidity ^0.5.0;
contract Test {
address public owner = msg.sender;
uint public creationTime = now;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 53/66
4/20/23, 2:48 PM Solidity - Quick Guide
}
function changeOwner(address _newOwner) public onlyBy(owner) {
owner = _newOwner;
}
modifier onlyAfter(uint _time) {
require(
now >= _time,
"Function called too early."
);
_;
}
function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) {
delete owner;
}
modifier costs(uint _amount) {
require(
msg.value >= _amount,
"Not enough Ether provided."
);
_;
if (msg.value > _amount)
msg.sender.transfer(msg.value - _amount);
}
function forceOwnerChange(address _newOwner) public payable costs(200 ether) {
owner = _newOwner;
if (uint(owner) & 0 == 1) return;
}
}
Solidity - Contracts
Contract in Solidity is similar to a Class in C++. A Contract have following properties.
Constructor − A special function declared with constructor keyword which will be executed
once per contract and is invoked when a contract is created.
State Variables − Variables per Contract to store the state of the contract.
Functions − Functions per Contract which can modify the state variables to alter the state
of a contract.
Visibility Quantifiers
Following are various visibility quantifiers for functions/state variables of a contract.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 54/66
4/20/23, 2:48 PM Solidity - Quick Guide
external − External functions are meant to be called by other contracts. They cannot be
used for internal call. To call external function within contract this.function_name() call is
required. State variables cannot be marked as external.
public − Public functions/ Variables can be used both externally and internally. For public
state variable, Solidity automatically creates a getter function.
internal − Internal functions/ Variables can only be used internally or by derived contracts.
private − Private functions/ Variables can only be used internally and not even by derived
contracts.
Example
pragma solidity ^0.5.0;
contract C {
//private state variable
uint private data;
//constructor
constructor() public {
info = 10;
}
//private function
function increment(uint a) private pure returns(uint) { return a + 1; }
//public function
function updateData(uint a) public { data = a; }
function getData() public view returns(uint) { return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
//External Contract
contract D {
function readData() public returns(uint) {
C c = new C();
c.updateData(7);
return c.getData();
}
}
//Derived Contract
contract E is C {
uint private result;
C private c;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 55/66
4/20/23, 2:48 PM Solidity - Quick Guide
constructor() public {
c = new C();
}
function getComputedResult() public {
result = compute(3, 5);
}
function getResult() public view returns(uint) { return result; }
function getData() public view returns(uint) { return c.info(); }
}
Run the above program using steps provided in Solidity First Application chapter. Run various
method of Contracts. For E.getComputedResult() followed by E.getResult() shows −
Output
0: uint256: 8
Solidity - Inheritance
Inheritance is a way to extend functionality of a contract. Solidity supports both single as well as
multiple inheritance. Following are the key highlighsts.
A derived contract can access all non-private members including internal methods and state
variables. But using this is not allowed.
We can call a super contract's function using super keyword or using super contract name.
In case of multiple inheritance, function call using super gives preference to most derived
contract.
Example
pragma solidity ^0.5.0;
contract C {
//private state variable
uint private data;
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 56/66
4/20/23, 2:48 PM Solidity - Quick Guide
//constructor
constructor() public {
info = 10;
}
//private function
function increment(uint a) private pure returns(uint) { return a + 1; }
//public function
function updateData(uint a) public { data = a; }
function getData() public view returns(uint) { return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
//Derived Contract
contract E is C {
uint private result;
C private c;
constructor() public {
c = new C();
}
function getComputedResult() public {
result = compute(3, 5);
}
function getResult() public view returns(uint) { return result; }
function getData() public view returns(uint) { return c.info(); }
}
Run the above program using steps provided in Solidity First Application chapter. Run various
method of Contracts. For E.getComputedResult() followed by E.getResult() shows −
Output
0: uint256: 8
Solidity - Constructors
Constructor is a special function declared using constructor keyword. It is an optional funtion
and is used to initialize state variables of a contract. Following are the key characteristics of a
constructor.
A constructor code is executed once when a contract is created and it is used to initialize
contract state.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 57/66
4/20/23, 2:48 PM Solidity - Quick Guide
After a constructor code executed, the final code is deployed to blockchain. This code
include public functions and code reachable through public functions. Constructor code or
any internal method used only by constructor are not included in final code.
contract Test {
constructor() public {}
}
In case, base contract have constructor with arguments, each derived contract have to pass
them.
Base constructor can be initialized directly using following way −
contract Base {
uint data;
constructor(uint _data) public {
data = _data;
}
}
contract Derived is Base (5) {
constructor() public {}
}
contract Base {
uint data;
constructor(uint _data) public {
data = _data;
}
}
contract Derived is Base {
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 58/66
4/20/23, 2:48 PM Solidity - Quick Guide
Direct and Indirect ways of initializing base contract constructor is not allowed.
If derived contract is not passing argument(s) to base contract constructor then derived
contract will become abstract.
In case, a derived contract is not implementing the abstract function then this derived contract
will be marked as abstract.
Example
Try the following code to understand how the abstract contracts works in Solidity.
contract Calculator {
function getResult() public view returns(uint);
}
contract Test is Calculator {
function getResult() public view returns(uint) {
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Output
0: uint256: 3
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 59/66
4/20/23, 2:48 PM Solidity - Quick Guide
Solidity - Interfaces
Interfaces are similar to abstract contracts and are created using interface keyword. Following
are the key characteristics of an interface.
Interface can have enum, structs which can be accessed using interface name dot notation.
Example
Try the following code to understand how the interface works in Solidity.
interface Calculator {
function getResult() external view returns(uint);
}
contract Test is Calculator {
constructor() public {}
function getResult() external view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
Output
0: uint256: 3
Solidity - Libraries
Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions
which other contracts can call. Solidity have certain restrictions on use of a Library. Following are
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 60/66
4/20/23, 2:48 PM Solidity - Quick Guide
Library functions can be called directly if they do not modify the state. That means pure or
view functions only can be called from outside the library.
Example
Try the following code to understand how a Library works in Solidity.
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 61/66
4/20/23, 2:48 PM Solidity - Quick Guide
Output
0: uint256: 3
Using For
The directive using A for B; can be used to attach library functions of library A to a given type B.
These functions will used the caller type as their first parameter (identified using self).
Example
Try the following code to understand how a Library works in Solidity.
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
using Search for uint[];
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 62/66
4/20/23, 2:48 PM Solidity - Quick Guide
Output
0: uint256: 3
Solidity - Assembly
Solidity provides an option to use assembly language to write inline assembly within Solidity
source code. We can also write a standalone assembly code which then be converted to
bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it
converts the Solidity code into a Standalone Assembly and then to byte code. We can used the
same language used in Inline Assembly to write code in a Standalone assembly.
Inline Assembly
Inline assembly code can be interleaved within Solidity code base to have more fine-grain control
over EVM and is used especially while writing the library functions.
Example
Try the following code to understand how a Library works in Solidity.
library Sum {
function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint
for (uint i = 0; i < _data.length; ++i) {
assembly {
o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
}
}
}
}
contract Test {
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function sum() external view returns(uint){
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 63/66
4/20/23, 2:48 PM Solidity - Quick Guide
return Sum.sumUsingInlineAssembly(data);
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
Output
0: uint256: 15
Solidity - Events
Event is an inheritable member of a contract. An event is emitted, it stores the arguments passed
in transaction logs. These logs are stored on blockchain and are accessible using address of the
contract till the contract is present on the blockchain. An event generated is not accessible from
within contracts, not even the one which have created and emitted them.
//Declare an Event
event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
//Emit an event
emit Deposit(msg.sender, _id, msg.value);
Example
Try the following code to understand how an event works in Solidity.
contract Test {
event Deposit(address indexed _from, bytes32 indexed _id, uint _value);
function deposit(bytes32 _id) public payable {
emit Deposit(msg.sender, _id, msg.value);
}
}
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 64/66
4/20/23, 2:48 PM Solidity - Quick Guide
Output
{
"returnValues": {
"_from": "0x1111...FFFFCCCC",
"_id": "0x50...sd5adb20",
"_value": "0x420042"
},
"raw": {
"data": "0x7f...91385",
"topics": ["0xfd4...b4ead7", "0x7f...1a91385"]
}
}
assert(bool condition) − In case condition is not met, this method call causes an invalid
opcode and any changes done to state got reverted. This method is to be used for internal
errors.
require(bool condition) − In case condition is not met, this method call reverts to original
state. - This method is to be used for errors in inputs or external components.
require(bool condition, string memory message) − In case condition is not met, this
method call reverts to original state. - This method is to be used for errors in inputs or
external components. It provides an option to provide a custom message.
revert() − This method aborts the execution and revert any changes done to the state.
revert(string memory reason) − This method aborts the execution and revert any changes
done to the state. It provides an option to provide a custom message.
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 65/66
4/20/23, 2:48 PM Solidity - Quick Guide
Example
Try the following code to understand how error handling works in Solidity.
contract Vendor {
address public seller;
modifier onlySeller() {
require(
msg.sender == seller,
"Only seller can call this."
);
_;
}
function sell(uint amount) public payable onlySeller {
if (amount > msg.value / 2 ether)
revert("Not enough Ether provided.");
// Perform the sell operation.
}
}
Output
0x08c379a0 // Function selector for Error(string)
0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset
0x000000000000000000000000000000000000000000000000000000000000001a // String length
0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data
https://www.tutorialspoint.com/solidity/solidity_quick_guide.htm 66/66