Introduction to Solidity programming
Introduction to Solidity programming
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 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.
• 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:
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 {
}
// 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’:
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.
constant Indicates that a function does not modify the contract state.
enum A user-defined type that can only have a certain set of values.
external Indicates that a function can only be called from outside the contract.
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.
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 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;
}
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.
Syntax:
<type> <access modifier> <variable name> ;
Example:
int public int_var;
Types of Variables
block.timestamp (uint) The timestamp of the current block as seconds since Unix epoch
msg.sig (bytes4) First four bytes of call data i.e. function identifier
// 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.
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 {
struct student {
string name;
string subject;
uint8 marks;
}
student public std1; // Creating a
structure object
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.
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.
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.
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:
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:
Internal variables are accessible within the contract they are defined in and derived from contracts.
They are not accessible from external contracts.
Syntax:
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
contract SolidityTest {
}
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 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;
}
Logical Operators
Operator Denotation Description
Logical AND && Returns true if both conditions are true and false
if one or both conditions are false
// Creating a contract
contract logicalOperator{
// Logical OR operator
bool or = a||b;
Bitwise AND & Performs boolean AND 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;
}
Assignment Operator
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:
// Creating a contract
contract SolidityTest{
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
}
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.
•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
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.
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
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;
function array_length(
) public returns(uint) {
uint x = data.length;
return x;
}
}
3. Push:
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.
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;
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.
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;
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;
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;
}
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.
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
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.
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.
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
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);
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.