0% found this document useful (0 votes)
20 views

Introduction to Solidity programming

Uploaded by

Ansh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Introduction to Solidity programming

Uploaded by

Ansh Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Introduction to

Solidity CC4167
programming
Solidity programming language is a high-level programming
language for writing smart contracts for the Ethereum Virtual Machine.
It is influenced by high-level languages such as C++, Python, and
JavaScript.
Solidity is a brand-new programming language created by Ethereum which
is the second-largest market of cryptocurrency by capitalization, released in
the year 2015 and led by Christian Reitwiessner. Some key features of
solidity are listed below:

•Solidity is a high-level programming language designed for implementing


smart contracts.

•It is a statically typed object-oriented(contract-oriented) language.

•Solidity is highly influenced by Python, C++, and JavaScript which run on


the Ethereum Virtual Machine(EVM).

•Solidity supports complex user-defined programming, libraries, and


inheritance.

•Solidity is the primary language for blockchains running platforms.

•Solidity can be used to create contracts like voting, blind auctions,


• Solidity is a programming language specifically designed for developing smart
contracts on the Ethereum blockchain.

• It is a high-level, statically-typed language with syntax and features similar to


those of JavaScript, C++, and Python.

• Solidity is used to write self-executing smart contracts that can control the
transfer of cryptocurrencies, digital assets, or other valuable items based on
predefined rules and conditions.

• Solidity supports various data types such as integers, strings, booleans, and
arrays, and allows for control structures such as if-else statements, loops, and
switch statements.

• It also supports object-oriented programming features such as inheritance,


polymorphism, and encapsulation.

• Solidity contracts can be compiled into bytecode and deployed on the Ethereum
blockchain for execution, providing a secure and decentralized way to execute
code without the need for a central authority.
pragma solidity ^0.8.0;
1. Compiler Directive
contract HelloMUJ {
A compiler directive in programming uint a;
languages provides additional information to function set(uint x)
the compiler or interpreter. It helps to control public {
the behavior of the code, such as language a = x;
version, optimization options, or warnings. }
function get() public view
In Solidity, pragma is used to specify the returns (uint) {
compiler version that the code should be return a;
}
compiled with. This is important because
}
Solidity is a rapidly evolving language, and
new
For versionsthe
example, may introduce
given breakinga pragma directive that specifies the version of the
code includes
changes
Solidity or improvements
compiler that
that should be affect
used: the
behavior of the code.
pragma solidity ^0.8.0;

The ^0.8.0 part of the pragma directive specifies that the code should be compiled with
a Solidity compiler version equal to or higher than 0.8.0, but less than 0.9.0. This
ensures that the code is compatible with the latest version of Solidity, but does not break
if a new version with breaking changes is released.
2. Contract
In Solidity, a contract is a collection of functions and variables that are
written to be deployed on the Ethereum blockchain. A contract can be
thought of as a self-contained program that can interact with other
contracts and the outside world. The line “contract HelloMUJ” declares a
contract HelloMUJ.

Example:
contract HelloMUJ { // do something }
3. Variables
Variables in Solidity are used to store data that can be used later in the
program. There are different types of variables like uint (unsigned integer),
string, bool (boolean), etc. The line “uint a” declares a variable a.

Example:
uint a ;
4. Functions
Functions in Solidity are similar to functions in other programming languages. They
are used to perform specific tasks or operations. The line “function set(uint x)
public” and “function get() public view returns (uint)” declares 2 functions to set and
get the value of the variable a.

Example:

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

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


5. Control Structures

Control structures are used to control the flow of the program. Solidity supports various
control structures such as if/else statements, loops, etc.
For example:

if (myNumber > 5) {

// do something

} else {
}

for (uint i = 0; i < 10; i++) {

// do something repeatedly
}

In the example above, we have an if/else statement that checks if the value of myNumber
is greater than 5. If it is, it performs the code in the first block, otherwise, it performs the
code in the second block. We also have a for loop that runs 10 times and performs the
code in its block.
6. Importing Files
In programming, importing files is a way to reuse code from other files or libraries. This
can help to reduce code duplication and improve modularity. In Solidity, files can be
imported using the import keyword.
For example, the following code imports a file named ‘MyLibrary.sol’:

The import “./MyLibrary.sol” statement


imports the MyLibrary.sol file located in the pragma solidity ^0.8.0;
same directory as the current file. The code in
the imported file can then be used in the import "./MyLibrary.sol";
current file.
contract HelloMUJ{ // ...}
7. Reserved Keywords

Reserved keywords are words that are reserved by the programming language and cannot be
used as identifiers (such as variable names or function names). In Solidity, some reserved
keywords include:
Keyword Explanation

abstract Indicates that a contract or function is incomplete and must be implemented by a child contract.

address A 20-byte Ethereum address.

bool A boolean value (true or false).

break Exits a loop or switch statement.

bytes A dynamic byte array.

bytes32 A 32-byte array.

constant Indicates that a function does not modify the contract state.

contract Defines a smart contract.

enum A user-defined type that can only have a certain set of values.

event A way to log an occurrence in the contract.

external Indicates that a function can only be called from outside the contract.

function Defines a function.

if A conditional statement.
Ethereum
Ethereum is a decentralized open-source platform based on the blockchain
domain, used to run smart contracts i.e. applications that execute the
program exactly as it was programmed without the possibility of any fraud,
interference from a third party, censorship, or downtime. It serves as a
platform for nearly 2,60,000 different cryptocurrencies. Ether is a
cryptocurrency generated by Ethereum miners, used to reward for the
computations performed to secure the blockchain.

Ethereum Virtual Machine(EVM)


Ethereum Virtual Machine abbreviated as EVM is a runtime environment for
executing smart contracts in ethereum. It focuses widely on providing
security and execution of untrusted code using an international network of
public nodes. EVM is specialized to prevent Denial-of-service attack and
confirms that the program does not have any access to each other’s state,
also ensures that the communication is established without any potential
interference.
Smart Contract

Smart contracts are high-level program codes that are compiled to EVM byte
code and deployed to the ethereum blockchain for further execution. It
allows us to perform credible transactions without any interference of the
third party, these transactions are trackable and irreversible. Languages
used to write smart contracts are Solidity (a language library with similarities
to C and JavaScript), Serpent (similar to Python, but deprecated), LLL (a low-
level Lisp-like language), and Mutan (Go-based, but deprecated).
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.4.16 < 0.9.0;

contract Test
{
uint public var1;
uint public var2;
uint public sum;

function set(uint x, uint y) public


{
var1 = x;
var2 = y;
sum=var1+var2;
}

function get(
) public view returns (uint) {
return sum;
}
}
A development environment is an environment in which all the resources and tools are
available which are used to develop a program or software product. Here, an attempt to
create a development environment that is a collection of the processes and tools that are
used to develop smart contracts.

There are mainly two choices available to set up the environment for
developing smart contracts:

1.Online IDE: This is a quick, easy, and beginner-friendly online IDE used to develop
smart contracts. Online IDE setup is not recommended when we go deep into the
development of smart contracts because of their limitations.

2.Local Set-Up: All the tools and packages are installed on the local machine that is
used to build smart contracts.

Smart Contract
A Smart Contract is a business contract built in the form of a program, which is deployed
on the blockchain network, and the computation required for the execution of a program
is provided by the blockchain network. The objectives of smart contracts are the
reduction of the need in trusted intermediates, arbitrations, and enforcement costs, fraud
losses, as well as the reduction of malicious and accidental exceptions.
pragma solidity >= 0.8.2 <0.9.0;

contract HelloWorld{

string userInput;

function set(string memory finalValue) public


{
userInput = finalValue;
}

function get() public view returns(string memory){


return userInput;
}

}
A Variable is basically a placeholder for the data which can be
manipulated at runtime. Variables allow users to retrieve and change
the stored information.

Rules For Naming Variables

1. A variable name should not match with reserved keywords.


2. Variable names must start with a letter or an underscore (_), and may
contain letters from “a to z” or “A to Z” or digits from “0 to 9” and
characters also.
3. The name of variables are case sensitive i.e.
Declaration of Variables

In Solidity declaration of variables is a little bit different, to declare a


variable the user has to specify the data type first followed by access
modifier.

Syntax:
<type> <access modifier> <variable name> ;
Example:
int public int_var;
Types of Variables

Solidity is a statically typed language i.e. each


declared variable always has a default value
based on its data type, which means there is no
concept of ‘null’ or ‘undefined’. Solidity
supports three types of variables:
pragma solidity ^0.5.0;
1. State Variables: Values of these variables
are permanently stored in the contract storage. // Creating a contract
Each function has its own scope, and state contract Solidity_var_Test {
variables should always be defined outside of // Declaring a state
that scope. variable
Example: In the below example. the contract uint8 public
Solidity_var_Test initializes the values of an state_var;
unsigned integer state variable using a // Defining a constructor
constructor. constructor() public {
state_var = 16;
}
}
Local Variable: Values of these variables contract Solidity_var_Test {
are present till the function executes and
it cannot be accessed outside that // Defining function to show the
declaration and
function. This type of variable is usually
// scope of local variables
used to store temporary values. function getResult() public view
returns(uint){

// Initializing local variables


uint local_var1 = 1;
uint local_var2 = 2;
uint result = local_var1 +
local_var2;

// Access the local variable


return result;
}
}
Global Variables: These are some special variables that can be used globally and give
information about the transactions and blockChain properties. Some of the global variables
are listed below :
Variable Return value
Hash of a given block, works for only 256 most recent
blockhash(uint blockNumber) returns (bytes32)
transactions excluding current blocks

block.coinbase (address payable) Address of current blocks miner

block.difficulty (uint) The difficulty of the current block

block.gaslimit (uint) Gaslimit of the current block

block.number (uint) Block number of the current block

block.timestamp (uint) The timestamp of the current block as seconds since Unix epoch

gasleft() returns (uint256) Amount of gas left

msg.data (bytes calldata) Complete call data of block

msg.sender (address payable) The sender of message i.e. current caller

msg.sig (bytes4) First four bytes of call data i.e. function identifier

msg.value (uint) Amount of Wei sent with a message

now (uint) The timestamp of the current block

gasleft() returns (uint256) Amount of gas left

tx.gasprice (uint) Price of gas for the transaction

tx.origin (address payable) Transaction sender


pragma solidity ^0.5.0;

// Creating a contract
contract Test {

// Defining a variable
address public admin;

// Creating a constructor to
// use Global variable
constructor() public {
admin = msg.sender;
}
}
Solidity is a statically typed language, which implies that the type of each of the variables
should be specified. Data types allow the compiler to check the correct usage of the
variables. The declared types have some default values called Zero-State, for example
for bool the default value is False. Likewise other statically typed languages Solidity has
Value types and Reference types which are defined below:

Value Types
Value-type variables store their own data. These are the basic data types provided by
solidity. These types of variables are always passed by value. The variables are copied
wherever they are used in function arguments or assignments. Value type data types in
solidity are listed below:

•Boolean: This data type accepts only two values True or False.

•Integer: This data type is used to store integer values, int, and uint are used to
declare signed and unsigned integers respectively.

•Fixed Point Numbers: These data types are not fully supported in solidity yet, as per
the Solidity documentation. They can be declared as fixed and unfixed for signed and
unsigned fixed-point numbers of varying sizes respectively.
•Address: Address hold a 20-byte value which represents the size of an Ethereum
address. An address can be used to get a balance or to transfer a balance
by balance and transfer method respectively.

•Bytes: Although bytes are similar to strings, there are some differences between them.
bytes used to store a fixed-sized character set while the string is used to store the
character set equal to or more than a byte. The length of bytes is from 1 to 32, while the
string has a dynamic length. Byte has the advantage that it uses less gas, so better to
use when we know the length of data.

•Enums: It is used to create user-defined data types, used to assign a name to an


integral constant which makes the contract more readable, maintainable, and less prone
to errors. Options of enums can be represented by unsigned integer values starting from
0.
pragma solidity >=0.4.22 <0.9.0;
contract Types {

bool public boolean = false; // Initializing Bool variable

int32 public int_var = -60313; // Initializing Integer variable

string public str = “MUJ"; // Initializing String variable

bytes1 public b = "a"; // Initializing Byte variable

enum my_enum { Manipal_, _for, _Jaipur } // Defining an enumerator

function Enum() public pure returns( // Defining a function to return


// values stored in an enumerator
my_enum) {
return my_enum._Jaipur;
}
}
Reference Types

Reference type variables store the location of the data. They don’t share the data directly.
With the help of reference type, two different variables can refer to the same location
where any change in one variable can affect the other one. Reference types in solidity are
listed below:

•Arrays: An array is a group of variables of the same data type in which the variable has a
particular location known as an index. By using the index location, the desired variable can
be accessed. The array size can be fixed or dynamic.

•Strings: Strings are like arrays of characters. When we use them, we might occupy
bigger or shorter storage space.

•Struct: Solidity allows users to create and define their own type in the form of structures.
The structure is a group of different types even though it’s not possible to contain a
member of its own type. The structure is a reference type variable that can contain both
value type and reference type

•Mapping: Mapping is the most used reference type, that stores the data in a key-value
pair where a key can be any value type. It is like a hash table or dictionary as in any other
pragma solidity >=0.4.22 <0.9.0;
contract mapping_example {

uint[5] public array


= [uint(1), 2, 3, 4, 5] ;

struct student {
string name;
string subject;
uint8 marks;
}
student public std1; // Creating a
structure object

function structure() public returns( // Defining a function to return


// values of the elements of
the structure
string memory, string memory, uint){
std1.name = "John";
std1.subject = "Chemistry";
std1.marks = 88;
return (
std1.name, std1.subject, std1.marks);
}

mapping (address => student) result; // Creating a mapping

address[] student_result;
}
Variable scope is an essential concept in Solidity, the programming language for Ethereum smart
contracts. Solidity has various types of variables with different scopes, such as local, state, and
global variables.

Local Variable
Local variables are declared within a function and are only accessible within that function. Their
scope is limited, and their lifetime ends when the function execution is completed.

pragma solidity ^0.8.0;

contract LocalVariableExample {
function getDouble(uint value) public pure
returns (uint)
{
uint doubleValue = value * 2;
return doubleValue;
}
}
State Variable

State variables are declared at the contract level and represent the contract’s state on the
blockchain. They are stored on the Ethereum network and are accessible within the entire
contract.

pragma solidity ^0.8.0;

contract StateVariableExample {
uint public count = 0;
function increment() public
{
count += 1;
}
}
Global Variable

Global variables are special variables provided by the Solidity language. They are available
throughout the contract and provide information about the blockchain, transaction, and
execution context.

Examples of Global Variables:

•block.timestamp (current block timestamp)


pragma solidity ^0.8.0;
•msg.sender (address of the sender of the current function call)
•msg.value (amount of ether sent in the current function call) contract GlobalVariableExample {
event SenderAndValue(address sender,
uint value);
function getSenderAndValue() public
payable
{
address sender = msg.sender;
uint value = msg.value;
emit SenderAndValue(sender,
value);
}
}
Variable Scope
There are three types of variable scopes in Solidity:

1. Public
Public variables are accessible from within the contract and can be accessed from external contracts as
well. Solidity automatically generates a getter function for public state variables.

Syntax:

<type> public <variable_name>;

2. Private
Private variables are only accessible within the contract they are defined in. They are not accessible from
derived contracts or external contracts.

Syntax:

<type> private <variable_name>;


3. Internal

Internal variables are accessible within the contract they are defined in and derived from contracts.
They are not accessible from external contracts.

Syntax:

<type> internal <variable_name>;


Output:
pragma solidity ^0.8.0;
The publicVar can be accessed using the
automatically generated getter function contract VariableScopeExample {
publicVar(). The privateVar can be accessed using uint public publicVar = 1;
the getPrivateVar() function from within the uint private privateVar = 2;
VariableScopeExample contract. The internalVar uint internal internalVar = 3;
can be accessed by the getInternalVar() function in
function getPrivateVar() public view
the derived contract DerivedContract. returns (uint)
{
return privateVar;
}
}

contract DerivedContract is
VariableScopeExample {
function getInternalVar() public view
returns (uint)
{
return internalVar;
}
}
In any programming language, operators play a vital role i.e. they create a foundation for the
programming. Similarly, the functionality of Solidity is also incomplete without the use of
operators. Operators allow users to perform different operations on operands. Solidity supports
the following types of operators based upon their functionality.

1.Arithmetic Operators
2.Relational Operators
3.Logical Operators
4.Bitwise Operators
5.Assignment operators
6.Conditional Operator

Arithmetic Operators
These operators are used to perform arithmetic or mathematical operations. Solidity supports
the following arithmetic operators :
Operator Denotation Description

Addition + Used to add two operands

Subtraction – Used to subtract the second operand from first

Multiplication * Used to multiply both operands

Division / Used to divide numerator by denominator

Modulus % Gives the remainder after integer division

Increment ++ Increases the integer value by one

Decrement — Decreases the integer value by one


pragma solidity ^0.5.0;

contract SolidityTest {

uint16 public a = 20;


uint16 public b = 10;
uint public sum = a + b;
uint public diff = a - b;

uint public mul = a * b;


uint public div = a / b;
uint public mod = a % b;

uint public dec = --b;


uint public inc = ++a;

}
Relational
Operators
Operator Denotation Description

Checks if two values are equal or not, returns true if equals, and
Equal ==
vice-versa

Checks if two values are equal or not, returns true if not equals, and
Not Equal !=
vice-versa

Checks if left value is greater than right or not, returns true if


Greater than >
greater, and vice-versa

Checks if left value is less than right or not, returns true if less, and
Less than <
vice-versa

Checks if left value is greater and equal than right or not, returns
Greater than or Equal to >=
true if greater and equal, and vice-versa

Checks if left value is less than right or not, returns true if less and
Less than or Equal to <=
equals, and vice-versa
pragma solidity ^0.5.0;

// Creating a contract
contract SolidityTest {

// Declaring variables
uint16 public a = 20;
uint16 public b = 10;

// Initializing a variable
// with bool equal result
bool public eq = a == b;

bool public noteq = a != b;

bool public gtr = a > b;

bool public les = a < b;

bool public gtreq = a >= b;


bool public leseq = a <= b;

}
Logical Operators
Operator Denotation Description

Logical AND && Returns true if both conditions are true and false
if one or both conditions are false

Returns true if one or both conditions are true


Logical OR || and false when both are false

Logical NOT ! Returns true if the condition is not satisfied else


false
pragma solidity ^0.5.0;

// Creating a contract
contract logicalOperator{

// Defining function to demonstrate


// Logical operator
function Logic(
bool a, bool b) public view returns(
bool, bool, bool){

// Logical AND operator


bool and = a&&b;

// Logical OR operator
bool or = a||b;

// Logical NOT operator


bool not = !a;
return (and, or, not);
}
}
Bitwise Operators
Operator Denotation Description

Bitwise AND & Performs boolean AND operation on each bit of integer argument

BitWise OR | Performs boolean OR operation on each bit of integer argument

Bitwise XOR ^ Performs boolean exclusive OR operation on each bit of integer argument

Bitwise Not ~ Performs boolean NOT operation on each bit of integer argument

Moves all bits of the first operand to the left by the number of places specified
Left Shift <<
by the second operand

Moves all bits of the first operand to the right by the number of places
Right Shift >>
specified by the second operand
pragma solidity ^0.5.0;

// Creating a contract
contract SolidityTest {

// Declaring variables
uint16 public a = 20;
uint16 public b = 10;

// Initializing a variable
// to '&' value
uint16 public and = a & b;

// Initializing a variable
// to '|' value
uint16 public or = a | b;

uint16 public xor = a ^ b;


uint16 public leftshift = a << b;
uint16 public rightshift = a >> b;
uint16 public not = ~a ;

}
Assignment Operator

OPERATOR DENOTATION DESCRIPTION

Simple Assignment = Simply assigns the value at the right side to the operand at
the left side

Add Assignment += Adds operand at the right side to operand at the left side
and assigns the value to left operand

Subtract Assignment -= Subtracts operand at the right side from operand at the left
side and assigns the value to left operand

Multiply Assignment *= Multiplies both the operands and assign the value to left
operand

Divide Assignment /= Divides operand at the left side by operand at the right side
and assign the value to left operand

Modulus Assignment %= Divides operand at the left side by operand at the right side
and assign the remainder to left operand
pragma solidity ^0.5.0;

// Creating a contract
contract SolidityTest {

// Declaring variables
uint16 public assignment = 20;
uint public assignment_add = 50;
uint public assign_sub = 50;
uint public assign_mul = 10;
uint public assign_div = 50;
uint public assign_mod = 32;

// Defining function to
// demonstrate Assignment
Operator
function getResult() public{
assignment_add += 10;
assign_sub -= 20;
assign_mul *= 10;
assign_div /= 10;
assign_mod %= 20;
return ;
}
}
Conditional Operators

It is a ternary operator that evaluates the expression first then checks the
condition for return values corresponding to true or false.

Syntax:

if condition true ? then A: else B


pragma solidity ^0.5.0;

// Creating a contract
contract SolidityTest{

// Defining function to demonstrate


// conditional operator
function sub(
uint a, uint b) public view
returns(
uint){
uint result = (a > b? a-b : b-a);
return result;
}
}
Loops are used when we have to perform an
action over and over again. While writing a pragma solidity ^0.5.0;
contract there may be a situation when we have
to do some action repeatedly, In this situation, contract Types {
loops are implemented to reduce the number of
lines of the statements. Solidity supports // Declaring a dynamic array
following loops too ease down the programming uint[] data;
pressure.
uint8 j = 0;

While Loop function loop() public returns(uint[]


memory){
This is the most basic loop in solidity, Its purpose while(j < 5) {
is to execute a statement or block of statements j++;
repeatedly as far as the condition is true and data.push(j);
once the condition becomes false the loop }
return data;
terminates.
}
}
Do-While Loop
pragma solidity ^0.5.0;
This loop is very similar to while loop except that contract Types {
there is a condition check which happens at the
end of loop i.e. the loop will always execute at
least one time even if the condition is false. uint[] data;
uint8 j = 0;
function loop(
) public returns(uint[] memory){
do{
j++;
data.push(j);
}while(j < 5) ;
return data;
}
}
For Loop pragma solidity ^0.5.0;

This is the most compact way of looping. It takes three contract Types {
arguments separated by a semi-colon to run. The first
one is ‘loop initialization’ where the iterator is uint[] data;
initialized with starting value, this statement is function loop(
) public returns(uint[] memory){
executed before the loop starts. Second is ‘test
for(uint i=0; i<5; i++){
statement’ which checks whether the condition is true data.push(i);
or not, if the condition is true the loop executes else }
terminates. The third one is the ‘iteration statement’ return data;
where the iterator is increased or decreased. Below is }
the syntax of for loop : }
Decision making in programming is used when we have
to adopt one out of a given set of paths for program pragma solidity ^0.5.0;
flow. For this purpose, conditional statements are used
contract Types {
which allows the program to execute the piece of code
when the condition fulfills. Solidity uses control uint i = 10;
statements to control the flow of execution of the function decision_making(
program to advance and branch-based changes to the ) public returns(bool){
state. Following conditional statements are provided by if(i<10){
Solidity. return true;
}
}
If statement
}

This is the most basic conditional statement. It is used


to make a decision whether the statement or block of
code will be executed or not. If the condition is true the
statements will be executed, else no statement will
execute.
Break Statement

This statement is used when we have to terminate pragma solidity ^0.5.0;


the loop or switch statements or some block of contract Types {
code in which it is present. After the break
statement, the control is passed to the statements uint[] data;
present after the break. In nested loops, break
statement terminates only those loops which has uint8 j = 0;
break statement.
function loop(
) public returns(uint[] memory){
while(j < 5) {
j++;
if(j==3){
break;
}
data.push(j);
}
return data;
}
}
Continue Statement
pragma solidity ^0.5.0;
This statement is used when we have to skip the contract Types {
remaining block of code and start the next
iteration of the loop immediately. After executing uint[] data;
the continue statement, the control is transferred
uint8 j = 0;
to the loop check condition, and if the condition is
function loop(
true the next iteration starts. ) public returns(uint[]
memory){
while(j < 5) {
j++;
if(j==3){
continue;
}
data.push(j);
}
return data;
}
}
Solidity is syntactically similar to JavaScript, C++, and Python. So it uses similar language
structures to those languages. Strings in Solidity is a data type used to represent/store a
set of characters.

In Solidity data types are classified into two categories: Value type and Reference type.

•Strings in Solidity is a reference type of data type which stores the location of the data
instead of directly storing the data into the variable.

•They are dynamic arrays that store a set of characters that can consist of numbers, special
characters, spaces, and alphabets.

•Strings in solidity store data in UTF-8 encoding.

•Like JavaScript, both Double quote(” “) and Single quote(‘ ‘) can be used to represent
strings in solidity.
pragma solidity ^0.5.0; pragma solidity ^0.5.0;

contract LearningStrings
contract LearningStrings
{
{ string text;
string public text;
function setText () public
function setText() public returns (string memory)
{ {
text = 'hello'; text = "Hello World";
return text;
}
}
}
function setTextByPassing(string memory
message) public
{
text = message;
}
function getText() view public returns (string
memory)
{
return text;
}
}
S.No. Escape Characters Description
1. \” Double quote

2. \’ Single quote
Escape
Characters 3. \n Starts a new line
Additionally, 4. \\ Backslash
string literals
also support the 5. \t Tab
following escape
characters: 6. \r Carriage return

7. \b Backspace

8. \xNN Hex escape

9. \uNNNN Unicode escape


Length Of String
pragma solidity ^0.5.0;
Strings in Solidity do not have a length method to
find the character count in strings, but we can contract LearningStrings
convert the string to bytes and get its length. In {
solidity, we can convert Strings to bytes and vice function getLength(string memory s)
public pure returns (uint256)
versa.
{
bytes memory b = bytes(s);
To convert string to bytes:
return b.length;
string text = “Hii”; }
bytes b = bytes(text); }
To convert bytes to string:
bytes memory b = new
bytes(5);
string text = string(b);
Arrays are data structures that store the fixed collection of elements of the same data types in
which each and every element has a specific location called index.

Instead of creating numerous individual variables of the same type, we just declare one array
of the required size and store the elements in the array and can be accessed using the index.

In Solidity, an array can be of fixed size or dynamic size.

Arrays have a continuous memory location, where the lowest index corresponds to the first
element while the highest represents the last

Creating an Array

To declare an array in Solidity, the data type of the elements and the number of elements
should be specified. The size of the array must be a positive integer and data type should be a
valid Solidity type

<data type> <array name>[size] = <initialization>


Fixed-size Arrays
pragma solidity ^0.5.0;
The size of the array should be predefined.
The total number of elements should not contract Types {
exceed the size of the array. If the size of the
array is not specified then the array of enough uint[6] data1;
size is created which is enough to hold the
function array_example() public
initialization. returns (
int[5] memory, uint[6] memory){

int[5] memory data


= [int(50), -63, 77, -28, 90];
data1
= [uint(10), 20, 30, 40, 50, 60];

return (data, data1);


}
}
Dynamic Array:
pragma solidity ^0.5.0;
The size of the array is not predefined when it is
declared. As the elements are added the size of
array changes and at the runtime, the size of the contract Types {
array will be determined.
uint[] data
= [10, 20, 30, 40, 50];
int[] data1;

function dynamic_array() public


returns(
uint[] memory, int[] memory){

data1
= [int(-60), 70, -80, 90, -
100, -120, 140];
return (data, data1);
}
}
Array Operations pragma solidity ^0.5.0;

contract Types {
1. Accessing Array Elements: The elements of
the array are accessed by using the index. If you uint[6] data;
want to access ith element then you have to
access (i-1)th index. function array_example(
) public payable returns (uint[6]
memory){

data
= [uint(10), 20, 30, 40, 50, 60];
return data;
}
function array_element(
) public payable returns (uint){
uint x = data[2];
return x;
}
}
2. Length of Array: pragma solidity ^0.5.0;

Length of the array is used to check the number of contract Types {


elements present in an array. The size of the
uint[6] data;
memory array is fixed when they are declared,
while in case the dynamic array is defined at function array_example(
runtime so for manipulation length is required. ) public payable returns (uint[6]
memory){
data = [uint(10), 20, 30, 40, 50,
60];
return data;
}

function array_length(
) public returns(uint) {
uint x = data.length;
return x;
}
}
3. Push:

Push is used when a new element is to pragma solidity ^0.5.0;


be added in a dynamic array. The new
contract Types {
element is always added at the last
position of the array. uint[] data = [10, 20, 30, 40,
50];

function array_push(
) public returns(uint[] memory){

data.push(60);
data.push(70);
data.push(80);

return data;
}
}
4. Array slices : It allow developers to pragma solidity ^0.8.0;
extract a subset of the array, without having
contract ArraySlicing {
to loop through each of the element
uint[] myArray = [1, 2, 3, 4, 5];
individually. This can save gas costs and can
improve efficiency in certain scenarios. function getArraySlice() public view returns
(uint[] memory) {
uint[] memory mySlice = myArray[1:4];
return mySlice;
}
}

In this following example, we declare an array myArray which contain integers from 1 to 5.

After that, we define a function getArraySlice() that simply returns a slice of myArray containing
elements 2, 3, and 4.
For creating the slice, we use the notation myArray[1:4], which specifies that we want a slice of
myArray starting at the index 1 (i.e., the second element) and ending at index 4 (i.e., the fifth
element, but not inclusive).

After that we create a new dynamic array mySlice to store the slice, and return it from the
function.
Pop: Pop is used when the last element of the
array is to be removed in any dynamic array.

pragma solidity ^0.5.0;

contract Types {
uint[] data
= [10, 20, 30, 40, 50];
function array_pop(
) public returns(uint[] memory){
data.pop();
return data;
}
}
Enums are the way of creating user-defined data pragma solidity ^0.5.0;
types, it is usually used to provide names for
contract Types {
integral constants which makes the contract better
for maintenance and reading. enum week_days
{
Monday, Tuesday, Wednesday, Thursday, Friday,
Enums restrict the variable with one of a few
Saturday,
predefined values, these values of the enumerated Sunday
list are called enums. }
week_days week;

week_days choice;
Options are represented with integer values
starting from zero, a default value can also be week_days constant default_value
= week_days.Sunday;
given for the enum. By using enums it is possible
to reduce the bugs in the code. function set_value() public {
choice = week_days.Thursday;
}
function get_choice(
) public view returns (week_days) {
return choice;
}

function getdefaultvalue(
) public pure returns(week_days) {
return default_value;
}
}
pragma solidity ^0.5.0;

Struct contract test {


Structs in Solidity allows you to create more struct Book {
complicated data types that have multiple string name;
string writter;
properties. You can define your own type by uint id;
creating a struct. bool available;
}
They are useful for grouping together related data.
Structs can be declared outside of a contract and Book book1;

imported in another contract. Generally, it is used Book book2


= Book("Building Ethereum DApps",
to represent a record. To define a "Roberto Infante ",
structure struct keyword is used, which creates a 2, false);
new data type. function set_book_detail() public {
book1 = Book("Introducing Ethereum and
Solidity",
"Chris Dannen",
1, true);
}

function book_info(
)public view returns (
string memory, string memory, uint, bool) {

return(book2.name, book2.writter,
book2.id, book2.available);
}

function get_details(
) public view returns (string memory, uint) {
return (book1.name, book1.id);
Mapping in Solidity acts like a hash table or dictionary in any other
language. These are used to store the data in the form of key-value
pairs, a key can be any of the built-in data types but reference types
are not allowed while the value can be of any type. Mappings are
mostly used to associate the unique Ethereum address with the
associated value type.

mapping(key => value) <access specifier> <name>;


Creating a Mapping pragma solidity ^0.4.18;
Mapping is defined as any other variable type,
which accepts a key type and a value type. contract mapping_example {

struct student
{
string name;
string subject;
uint8 marks;
}

mapping (
address => student) result;
address[] public student_result;
}
pragma solidity ^0.4.18;
Adding values to mapping
contract mapping_example {
As the mapping is created let’s try to
add some values to the mapping for struct student {
better understanding. string name;
string subject;
uint8 marks;
}
mapping (
address => student) result;
address[] public student_result;

function adding_values() public {


var student
=
result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

student.name = "John";
student.subject = "Chemistry";
student.marks = 88;
student_result.push(
0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -
1;

}
pragma solidity ^0.4.18;

contract mapping_example {
Getting values
We have added values to the struct student {
mapping, to retrieve the string name;
values we have to create a string subject;
uint8 marks;
function that returns the }
values added to the mapping.
mapping (
address => student) result;
address[] student_result;

function adding_values() public {


var student
=
result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

student.name = "John";
student.subject = "Chemistry";
student.marks = 88;
student_result.push(
0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;

function get_student_result(
) view public returns (address[]) {
return student_result;
}
}
pragma solidity ^0.4.18;

contract mapping_example {

struct student {
Counting Mappings
Mappings can be counted so that we can know string name;
string subject;
how many values are stored in mapping. uint8 marks;
}

mapping (address => student) result;


address[] student_result;

function adding_values() public {


var student
=
result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];

student.name = "John";
student.subject = "Chemistry";
student.marks = 88;
student_result.push(
0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;

}
function get_student_result(
) view public returns (address[]) {
return student_result;
}
function count_students(
) view public returns (uint) {
return student_result.length;
}
}
Nested Mappings
If you need to keep track of multiple relationships, use nested mapping. Nested mapping is
similar to regular mapping, but it has a different syntax.

mapping(key => mapping(key => value)) <access specifier>


<name>;

pragma solidity ^0.8.16;


contract NestedMapping{
mapping(uint => mapping(address => bool))
voteToManager;

function voteRegistration(uint _empId, bool _voteChoice)


external {
voteToManager[_empId][msg.sender] = _voteChoice;
}

function getVoteStatus(uint _empId, address _empAddr)


external view returns(bool){
return voteToManager[_empId][_empAddr];
}
}
Solidity is a programming language that is used to write smart contracts for the
Ethereum blockchain. One important concept in Solidity is conversions, which allow
you to change the type of a variable or expression. The article focuses on discussing
three types of conversions in Solidity.
The following conversions will be discussed here:

1.Implicit Conversions.
2.Explicit Conversions.
3.Conversions between Literals and Elementary Types.
Implicit 1. uint()
Converts an expression to an unsigned integer (uint).
Conversions
Example:
bytes memory b = “Hello World”;
These occur uint a = uint(b); // a is now 7210465
automatically when
2. int()
a variable or Converts an expression to a signed integer (int).
expression of one Example:
type is assigned to a bytes memory b = “Hello World”;
int a = int(b); // a is now 7210465
variable of a
different type. For 3. bytes()
example, an integer Converts an expression to a byte array (bytes).
can be implicitly Example:
uint a = 10;
converted to a fixed bytes b = bytes(a); // b is now [0x0a]
point number or a
string. These are 4. address()
Converts an expression to an address type.
performed using Example:
built-in functions bytes memory b = “0x742d35Cc6634C0532925a3b844Bc454e4438f44e”;
such as ‘uint()’, and address a = address(b); // a is now 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
‘int()’.
5. bool()
Converts an expression to a boolean type.
Example:
bytes memory b = “Hello World”;
bool a = bool(b); // a is now true
Explicit
Conversions 1. Integer Converted to Smaller Type
If an integer is converted to a smaller type then the higher-order bits are cut-off.
These are uint32 a = 0x432178;
performed using uint16 b = uint16(a); // b will be 0x2178 now
built-in functions
such as ‘bytes()’. 2. Integer Converted to Larger Type
If an integer is explicitly converted to a larger type, it is padded on the left.
These functions
uint16 a = 0x4356;
allow you to uint32 b = uint32(a); // b will be 0x00004356 now
convert a variable
or expression to a 3. Fixed-size Bytes Converted to Smaller Types
specific type. Fixed-size bytes when converted to smaller types will cut off the sequence.
Explicit conversions bytes2 a = 0x4326;
are performed bytes1 b = bytes1(a); // b will be 0x43
using type casts.
4. Fixed-size Bytes Converted to Larger Types
Explicitly converting fixed-size bytes to a larger type, it is padded on the right.
bytes2 a = 0x4235;
bytes4 b = bytes4(a); // b will be 0x42350000
Explicit Conversion Between Integers and Fixed-size
Byte Arrays

Explicit conversions between integers and fixed-size byte


arrays are allowed only if both have the same size.
Intermediate conversions are required to convert between
integers and fixed-size byte arrays of different sizes.

bytes2 a = 0x3423;
uint32 b = uint16(a); // b will be 0x00003423
uint32 c = uint32(bytes4(a)); // c will be
0x34230000
uint8 d = uint8(uint16(a)); // d will be 0x23
uint8 e = uint8(bytes1(a)); // e will be 0x34
Conversions between Literals and Elementary Types

1. Integer Types
Decimal and hexadecimal literals can be implicitly converted to any integer type that is large enough to represent the
literal without any truncation.

Valid:
unit8 a = 23;
uint32 b = 2134;

Invalid:
uint16 c = 0x123456;
Error: Literal is too large to fit in unit16.
2. Fixed-Size Byte Arrays

Decimal number literals cannot be implicitly converted to fixed-size byte arrays but hexadecimal
number literals can be converted to fixed-size byte arrays but only if the number of hex digits
exactly fits the size of the byte type. Decimal and hexadecimal number literals that have a value
of zero can be converted to any fixed-size bytes type.

Valid:
bytes2 a = 0x1234;
bytes2 b = 0;

Invalid:
bytes2 a = 54321;
bytes2 b = 0x123;

String literals and hex string literals can be implicitly converted to fixed-size byte arrays only if
the number of characters matches the size of the byte type.
Valid:
bytes2 a = hex”1234″;
bytes2 b = “xy”;

Invalid:
bytes2 a = hex”12″;
bytes2 b = “xyz”;
3. Addresses

Explicit conversions to address are allowed only from bytes20 and uint160. Hex literals of
the correct size that pass the checksum test are of address type.

No other literals cannot be implicitly converted to the address type.

Conversions between literals and elementary types are an essential aspect of Solidity
programming. They enable developers to manipulate data stored in variables and make it
easier to perform operations on that data.

Understanding the different types of conversions available in Solidity and how they can
be used is important for writing efficient and effective smart contracts.
A unit is a metric scale but here in blockchain cryptocurrency, it refers to a denomination.
Ether units are denominations that are used to pay for computational processes within EVM.
In Solidity programming, a unit is a measurement of value or time that is used in the code.

There are two types of units in Solidity

1. Ether

Ether units are used to represent value, such as the amount of money being transferred
between accounts or the cost of a transaction.

•Ether, like many other cryptocurrencies, can be divided into smaller units of value.

•The smallest unit of ether is called a wei, and there are 1,000,000,000,000,000,000 (1
quintillion) Wei in one ether.
Unit Wei Value Wei

wei 1 wei 1

Kwei (babbage) 1e3 wei 1,000

Mwei (lovelace) 1e6 wei 1,000,000

Gwei (shannon) 1e9 wei 1,000,000,000

microether (szabo) 1e12 wei 1,000,000,000,000

milliether (finney) 1e15 wei 1,000,000,000,000,000

ether 1e18 wei 1,000,000,000,000,000,000


In Solidity, you can use these units to specify the amount of ether that is being transferred or used
in a contract. For example:

function sendEther(address _to, uint256 _value)


public {
require(_to != address(0));

// send atleast 1 ether to the specified address


require(_value >= 1 ether);
payable(_to).transfer(_value);
}
In this example, the transfer function is being called with value is ( >= 1 ether) as an
argument, which will send (>= 1 ether) to the specified address.

Note: It’s important to note that the units are only a convenient way of specifying amounts of
ether and do not affect the actual value of the ether being transferred. For example, 1 ether is
always equal to 1,000,000,000,000,000,000 Wei, regardless of whether it is specified as 1
ether or 1,000,000,000,000,000,000 Wei.
2. Time Unit

Time units, on the other hand, are used to measure the duration of certain events in the
blockchain, such as the amount of time that must pass before a certain action is allowed to
occur.
Solidity provides several time units that can be used in your code, including:

•seconds (s).
•minutes (min).
•hours (h).
•days (days).
•weeks (weeks).
Example 1: Time unit can be used to specify a duration in the smart contract like this:
uint public lockPeriod = 1 week;
In this example, the lockPeriod variable is set to 1 week (7 days).

Example 2: Time units can be used to specify the frequency at which an event should
occur.
event Heartbeat(uint timestamp);
// emit a Heartbeat event every 5 minutes
schedule Heartbeat(now + 5 minutes);

In this example, the Heartbeat event will be emitted every 5 minutes.

Note: It’s important to note that time units in Solidity are only approximate and are not
intended to be precise. The actual duration of a time unit may vary due to factors such
as network latency and block time.
Both Ether and Time units can be either local or global, with local units being accessible
only within a specific function or contract, and global units being available throughout
the entire program.

You might also like