0% found this document useful (0 votes)
14 views123 pages

Solidity Notes

The document provides an overview of Solidity, a programming language for creating smart contracts on the Ethereum blockchain. It covers key concepts such as smart contracts, their applications in various industries, the Solidity compilation process, and the differences between state and local variables. Additionally, it discusses functions, their types, and the importance of using keywords like 'view' and 'pure' to define function behavior.

Uploaded by

Tanish Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views123 pages

Solidity Notes

The document provides an overview of Solidity, a programming language for creating smart contracts on the Ethereum blockchain. It covers key concepts such as smart contracts, their applications in various industries, the Solidity compilation process, and the differences between state and local variables. Additionally, it discusses functions, their types, and the importance of using keywords like 'view' and 'pure' to define function behavior.

Uploaded by

Tanish Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

Solidity Notes

Day - 2
Code Eater

Contents
What is a smart contract ? Remix IDE Visibility Specifier

Smart Contract Application State Variables Conditionals

What is solidity ? Local Variables Basic Data Types

Solidity Compilation
Functions Much more
Process
Videos To Watch
• Solidity Course – Click Here
• Solidity Project Playlist – Click Here
Code Eater

Basic Data Types

Integer Data Type

Bool Data Type

Address Data Type

Bytes Data Type


Code Eater

What is a smart contract ?


• Smart contracts are simply programs stored on
a blockchain .
Code Eater

Smart Contract
A smart contract is a self-executing program that runs on a blockchain and is capable of automatically enforcing
the rules and regulations encoded within it. Smart contracts are often referred to as the "building blocks" of
decentralized applications (dApps), as they enable developers to create sophisticated decentralized systems that
are transparent, secure, and tamper-proof.

In the context of Ethereum, the most widely used blockchain for smart contracts, a smart contract is written in
Solidity, a high-level programming language that is specifically designed for creating decentralized applications.
Once a smart contract is deployed to the blockchain, it becomes part of the immutable ledger, which means that
its code and execution cannot be altered or tampered with.

Smart contracts are capable of automating a wide range of processes and transactions, from simple escrow
agreements to complex financial instruments, supply chain management systems, and more. They work by
defining the rules and conditions under which a transaction can occur, and then automatically executing the
transaction once those conditions are met.

Part 1 of 2
Code Eater

Smart Contract
One of the key benefits of smart contracts is that they eliminate the need for intermediaries, such as banks or
other financial institutions, to verify and process transactions. This not only reduces the cost and complexity of
transactions, but also enables greater transparency, security, and efficiency in the overall process.

Overall, smart contracts are a powerful tool for creating decentralized, trustless systems that are resistant to
censorship and tampering, and can enable new forms of economic and social interaction on a global scale.

Part 1 of 2
Code Eater

Smart Contract Applications


Smart contracts have a wide range of potential applications across various industries and use cases. Here are four
examples:

1. Decentralized Finance (DeFi): Smart contracts are at the core of many decentralized finance (DeFi)
applications, which aim to provide traditional financial services, such as loans, insurance, and asset trading,
without the need for intermediaries. Smart contracts enable DeFi platforms to automatically execute
transactions based on predefined rules and conditions, providing users with greater transparency, security, and
efficiency in financial transactions.

2. Supply Chain Management: Smart contracts can be used to track and verify the authenticity, origin, and
movement of goods across a supply chain. By creating a transparent and tamper-proof record of each
transaction, smart contracts can help reduce fraud, improve efficiency, and increase trust between different
parties in the supply chain.

Part 1 of 2
Code Eater

Smart Contract Applications


3. Voting Systems: Smart contracts can be used to create transparent and secure voting systems that can
prevent fraud and ensure the integrity of the election process. By encoding the rules and conditions of the voting
process into the smart contract, the results can be automatically and accurately calculated, without the need for a
central authority to verify the results.

4. Real Estate Transactions: Smart contracts can be used to automate the process of buying and selling real
estate, by encoding the rules and conditions of the transaction into the contract. This can help reduce the cost
and complexity of real estate transactions, while also providing greater transparency and security for buyers and
sellers.

These are just a few examples of the many potential applications of smart contracts. As the technology continues
to mature, it is likely that we will see even more innovative use cases emerge in a wide range of industries and
contexts.

Part 2 of 2
Code Eater

Supply Chain Management

A B
Code Eater

Supply Chain Management

A
B
Code Eater

Supply Chain Management


Smart Contract
If IOT detected a Yes Cancel delivery
temperature> 30 and do not pay to
degree Celsius
A.

No
Note-Assuming
optimum Do delivery and
temperature <30 transfer crypto to
degree Celsius. A.
Code Eater

Smart Contract Features


• Smart Contracts are immutable as they get stored on Blockchain.
• Smart contract contracts have their own accounts where it can store cryptocurrency.
• No human intervention is required for cryptocurrency transfer or receiving.
Code Eater

What is solidity?
• Solidity is an object-oriented programming language for implementing smart
contracts for the ethereum blockchain.

• High-level statically typed programming language.

• Case sensitive.

• With Solidity you can create contracts for uses such as voting, crowdfunding,
blind auctions, and multi-signature wallets.

Note –You should follow established


development best-practices when writing your smart contracts.
Code Eater

Solidity
• Solidity is a high-level programming language used for developing smart contracts on the Ethereum
blockchain. It is specifically designed to create decentralized applications (dApps) that can be deployed and
executed on the Ethereum Virtual Machine (EVM).

• Solidity is an object-oriented language and draws inspiration from C++, Python, and JavaScript. It is statically
typed, which means that the data types of variables and functions must be declared explicitly. Solidity also
supports inheritance, interfaces, and libraries, which enable developers to create modular and reusable code.

• Smart contracts written in Solidity are stored on the Ethereum blockchain, which means that they are publicly
accessible and immutable. Once deployed, a smart contract cannot be modified, which ensures that its
execution is transparent and tamper-proof.

• Solidity is widely used in the Ethereum ecosystem and has become the de facto language for developing smart
contracts on the platform. Its popularity is due in part to its developer-friendly syntax and extensive
documentation, which make it accessible to developers with varying levels of experience in programming and
blockchain development.
Code Eater

Remix IDE
• Sample program with Remix IDE
Code Eater

Solidity Compilation Process

source.sol file

Solidity Compiler

ABI Byte Code

Ethereum
Blockchain
Code Eater

Solidity Compilation Process


• Contract bytecode is public in readable form.

• Contract doesn’t have to be public.

• Bytecode is immutable because it is getting stored on Blockchain.

• ABI act as a bridge between applications and smart contract.

• ABI and Bytecode cannot be generated without source code.


Code Eater

Bytecode and ABI


• Bytecode and ABI are two important concepts in Ethereum development that are closely related to smart
contracts and the Ethereum Virtual Machine (EVM).

• Bytecode refers to the low-level machine code that is produced when a smart contract is compiled from its
high-level programming language (such as Solidity) into the binary format that can be executed by the EVM. In
other words, bytecode is the actual code that is stored on the Ethereum blockchain and executed by the EVM
to perform the operations defined by the smart contract.

• ABI stands for Application Binary Interface and refers to the interface that defines how to interact with a smart
contract, including the function signatures, input and output parameters, and other details about the
contract's interface. The ABI is used to create the necessary function calls and parameters that can be used to
interact with a deployed smart contract on the Ethereum blockchain.

• In practical terms, the bytecode and ABI are used in different ways by developers. The bytecode is generated
by the compiler when a smart contract is compiled and is typically deployed to the blockchain using a tool like
Remix or Truffle. The ABI, on the other hand, is used by developers to interact with the smart contract from a
web interface or application, allowing them to call functions, read data, and perform other operations on the
contract.
Code Eater

SPDX
• Trust in smart contracts can be better established if their source code is available. Since making source code
available always touches on legal problems with regards to copyright, the Solidity compiler encourages the use of
machine-readable SPDX license identifiers. Every source file should start with a comment indicating its license.

• Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each


source file.

• Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code.

• Please see SPDX for more information.​


Code Eater

State Variables
• In Solidity, state variables are variables that are permanently stored on the blockchain and hold the state of a
smart contract. They can be accessed and modified by functions within the contract and can be considered as
the contract's long-term memory.

• State variables are declared at the contract level using the `storage` keyword. They can be defined as various
types such as `uint`, `bool`, `address`, `string`, `struct`, `mapping`, and more.

• When a smart contract is deployed to the Ethereum blockchain, its state variables are initialized with default
values, such as zero or an empty string. These values can be changed over time through transactions that call
the contract's functions.

• It is important to note that state variables can be modified and updated by functions within the same contract,
but they cannot be accessed or modified directly by external contracts or accounts. To interact with state
variables, external contracts or accounts must call functions in the smart contract that provide access to the
state variables.

• Overall, state variables are a critical component of Solidity programming, as they allow smart contracts to
maintain state and store data on the Ethereum blockchain.
Code Eater

State Variables
• Permanently stored in contract storage.

• Cost gas(expensive) .

• Reading of state variable is free but writing to it is costly.


Code Eater

Local Variables
• In Solidity, local variables are variables that are defined within the scope of a function or code block, and are
only accessible within that scope. They are temporary variables that are created when a function or code block
is executed and are destroyed once the execution of the function or code block is complete.

• Local variables are declared using the standard syntax for declaring variables in Solidity, specifying the data
type and variable name. For example, `uint256 myNumber = 10;` would declare a local variable of type
`uint256` with the name `myNumber` and assign it the initial value of 10.

• Local variables can be used for a variety of purposes in Solidity, such as performing calculations, storing
temporary values, and passing data between functions. They can be used in conjunction with state variables to
perform complex operations and manage the state of a smart contract.

• It is important to note that local variables are different from state variables in that they are temporary and do
not persist between function calls or transactions. They are created and destroyed with each execution of a
function or code block, and their values cannot be accessed outside of that scope.

• Overall, local variables are a fundamental concept in Solidity programming, providing a way to store and
manipulate data within the context of a specific function or code block.
Code Eater

Local Variables
• Declared inside functions and are kept on the stack , not on storage.

• Don’t cost gas.


Code Eater

EVM
The Ethereum Virtual Machine (EVM) is a runtime environment that enables the execution of smart contracts on
the Ethereum blockchain. It is a virtual machine that is completely isolated from the underlying operating system
and hardware, which means that smart contracts executed on the EVM are executed in a deterministic and
secure environment.

The EVM is responsible for processing and executing transactions on the Ethereum blockchain, including
executing smart contracts written in programming languages like Solidity, Vyper, and others. It provides a
standardized set of instructions, called opcodes, that define the rules and conditions under which smart contracts
can be executed.

One of the key features of the EVM is its ability to execute Turing-complete code, which means that smart
contracts written in Ethereum's programming languages can perform complex calculations and operations,
similar to those found in traditional software programs.

The EVM is a crucial component of the Ethereum ecosystem and is responsible for ensuring that smart contracts
are executed correctly and transparently. Its ability to provide a secure and isolated runtime environment for
smart contracts is one of the key reasons why Ethereum has become a popular platform for building
decentralized applications (dApps).
Code Eater

EVM
Code Eater

Storage Area
Code Eater

Important
• State variables are always in storage.

• Function arguments are stored in either memory or calldata.

• Local variables of basic data type (i.e. neither array, nor struct nor mapping)
are stored in the stack.
Code Eater

Functions
Functions in Solidity are the basic building blocks for smart contracts. They are similar to functions in other
programming languages and allow smart contracts to perform various operations and manipulate data. Functions
can be defined at the contract level and can be called from within the same contract or from other contracts.

In Solidity, functions are defined using the `function` keyword, followed by the function name, any parameters
that the function accepts, and the function body. For example:

```
function addNumbers(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
```

In this example, we define a function called `addNumbers` that accepts two parameters of type `uint256` and
returns their sum. The `public` keyword indicates that the function can be called from outside the contract, and
the `pure` keyword specifies that the function does not modify the state of the contract.
Code Eater

Functions
Functions in Solidity can also have different access modifiers, such as `public`, `private`, `internal`, and `external`,
which determine who can call the function and from where. In addition, functions can have return values,
multiple return values, and can modify the state of the contract by updating state variables.

Overall, functions are a crucial component of Solidity programming, providing a way for smart contracts to
perform various tasks and interact with the Ethereum blockchain.
Code Eater

Functions
• When you declare a public state variable a getter function is automatically
created.

• For public state variables a getter() function is automatically created.


Code Eater

View Vs Pure

State Variable
Function
Type
Read Write

View

Pure
Code Eater

View Vs Pure
• In Solidity, `view` and `pure` are two different keywords that can be used to specify the state mutability of a
function.

• A `view` function is a read-only function that does not modify the state of the contract. It can access the
contract's state variables and read data from them, but it cannot modify them. The `view` keyword is used to
indicate that a function is a read-only function. For example:

```
function getMyNumber() public view returns (uint256) {
return myNumber;
}
```

• In this example, the `getMyNumber` function is marked as `view` because it does not modify the state of the
contract. It simply returns the value of the `myNumber` state variable.

Part 1 of 2
Code Eater

View Vs Pure
• On the other hand, a `pure` function is a function that does not read or modify the state of the contract. It is
used for functions that perform calculations or transformations on input parameters, and the output is solely
dependent on the input parameters. The `pure` keyword is used to indicate that a function is a pure function.
For example:

```
function addNumbers(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
```

• In this example, the `addNumbers` function is marked as `pure` because it only performs a calculation on the
input parameters and does not read or modify the state of the contract.

• Overall, `view` and `pure` are important keywords in Solidity that help to ensure that functions are correctly
marked as read-only or pure, which can improve the security and efficiency of smart contracts.

Part 2 of 2
Code Eater

Constructor
• In Solidity, a constructor is a special function that is automatically executed when a contract is deployed to the
Ethereum network. The constructor function is used to initialize the state variables of the contract and
perform any other setup operations that may be required.

• To define a constructor in Solidity, you use the `constructor` keyword followed by any parameters that the
constructor accepts and the constructor body. For example:

```
contract MyContract {
uint256 public myNumber;

constructor(uint256 _initialValue) {
myNumber = _initialValue;
}
}

```
Part 1 of 2
Code Eater

Constructor
• In this example, we define a constructor function that accepts a single parameter of type `uint256` and assigns
it to the `myNumber` state variable.

• It's important to note that a contract can have only one constructor, and the constructor function must have
the same name as the contract. Additionally, if a contract does not have a constructor defined, a default
constructor with no parameters is provided.

• Overall, the constructor function is an essential part of Solidity programming, allowing developers to initialize
the state of a contract and perform any other necessary setup operations when deploying a contract to the
Ethereum network.

• Constructor executed only once.

• You can create only one constructor and that is optional.

• A default constructor is created by the compiler if there is no explicitly defined constructor.

Part 2 of 2
Code Eater

Integer Data Type


int uint

Signed and Unsigned integers can be of various sizes.

int8 to int256 uint8 to uint256

int alias to int256 uint alias to uint256

By default int and uint are initialized to zero.

Overflow get detected at compile time.


Code Eater

Integer Data Type

Range
int8 : - 128 to +127 uint8 : 0 to 255
int16 : - 32768 to +32767 uint16 : 0 to 65535
-2^(n-1) to 2^(n-1)-1 0 to 2^(n)-1
Code Eater

Bool Data Type


• bool public value = true;

• Bool data type value can be either true or false.

• By default value is false if not initialized.


Code Eater

Bytes Data Type


• Bytes data type is used to store strings. Range - bytes1, bytes2, …..,bytes32.
• It stores characters.

• bytes1 public arr1="a"; • bytes2 public arr2="ab"; • bytes3 public arr3="abc";


• Everything that will be stored in the bytes array will be in hexadecimal number.

• arr3 will look this

61 62 63
0 1 2
• Click Here – Character To Hexadecimal Table

• Padding of 0 takes place if initialized characters are less than the byte size.
Code Eater

Bytes Data Type


contract demo{
bytes2 public arr1="ab";

function returnByte() public view returns(bytes1)


{
return arr1[0];
}
}

Output - 0x61

Example - 1
Code Eater

Bytes Data Type


contract demo{
bytes2 public arr1="ab";

function returnByte() public view returns(bytes2)


{
return arr1;
}
}

Output - 0x6162
Example - 2
Code Eater

Address Data Type


In Solidity, the address data type is used to represent Ethereum addresses. Ethereum
addresses are hexadecimal values that identify an account on the Ethereum network. The
address data type in Solidity is 20 bytes in size.

The address data type in Solidity has various member functions and properties that allow
developers to interact with and manipulate Ethereum addresses. Some commonly used
properties and functions of the address data type include:

- `balance`: Returns the balance of the address in Wei (the smallest unit of Ether).
- `transfer`: Sends a certain amount of Ether from the address to another address.
- `send`: Sends a certain amount of Ether to another address, returning a boolean value
indicating the success or failure of the transaction.
- `call`: Invokes a contract's function on the address with a specified amount of Ether
and arbitrary data.
- `transferFrom`: Transfers a certain amount of ERC20 tokens from one address to
another.
- `code`: Returns the contract bytecode stored at the address.
Code Eater

Address Data Type


• address public addr = "0xBE4024Fa7461933F930DD3CEf5D1a01363E9f284"

• The address type is a 160-bit value that does not allow any arithmetic operations.
Code Eater

Require
In Solidity, the `require` statement is used to check a condition and throw an error if the condition is not met. It is
a way to add input validation to smart contracts and ensure that they function correctly and securely.

The syntax of the `require` statement is as follows:

```
require(condition, error message);
```

The `condition` is a Boolean expression that is evaluated. If the expression evaluates to `false`, then the
transaction will be reverted and the error message will be returned to the sender.
Code Eater

Modifier
In Solidity, a `modifier` is a way to add code that can be executed before or after a function call. Modifiers are
typically used to validate inputs, check for authorization, or modify the behavior of a function in some way.

The syntax of a modifier is as follows:

```
modifier modifierName(arguments) {
// modifier code
_; // this is a placeholder for the function code
}
```

The underscore (`_`) is used to indicate where the function code should be inserted. When a function with a
modifier is called, the modifier code is executed first, and then the function code is executed in place of the `_`
placeholder.

Part 1 of 4
Code Eater

Modifier
For example, suppose we have a smart contract with a function that requires the caller to be the owner of the
contract:

```
function doSomething() public onlyOwner {
// function code
}
```

In this example, `onlyOwner` is a modifier that checks if the caller of the function is the owner of the contract.
The modifier code might look something like this:

```
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function");
_;
}
``` Part 2 of 4
Code Eater

Modifier
When `doSomething()` is called, the `onlyOwner` modifier is executed first. If the caller is not the owner of the
contract, then the function call will be reverted with the error message "Only the owner can call this function". If
the caller is the owner, then the function code will be executed in place of the `_` placeholder.

Modifiers can also be used to pass arguments to functions, like this:

```
modifier checkValue(uint amount) {
require(msg.value >= amount, "Not enough ether sent");
_;
}
```

Part 3 of 4
Code Eater

Modifier
In this example, `checkValue` is a modifier that checks if the amount of ether sent with the function call is greater
than or equal to a specified amount. The amount is passed to the modifier as an argument, like this:

```
function buy(uint amount) public payable checkValue(amount) {
// function code
}
```

In this example, the `buy` function is only executed if the `checkValue` modifier is successful, meaning that the
caller has sent enough ether. If the modifier fails, then the transaction will be reverted with the error message
"Not enough ether sent".

Part 4 of 4
Code Eater

Modifier
contract demo{

modifier onlytrue {
require(false==true,"_a is not equal to true");
_;
}
function check1() public pure onlytrue returns(uint){
return 1;
}
function check2() public pure onlytrue returns(uint){
return 1;
}
function check3() public pure onlytrue returns(uint){
return 1;
}

}
Code Eater

Loop
contract demo{

function check1() public pure{


for(uint i=0;i<7;i++){
//1st Loop
}

while(true==true){
//2nd Loop
}

do{
//3rd Loop
}while(true==true);
}

}
Code Eater

Visibility

PUBLIC PRIVATE INTERNAL EXTERNAL


Outside
World

Within
Contract

Derived
Contract
Other
Contracts
• Please Like and Subscribe :)
• Instagram - @codeeater21
Thank You • LinkedIn - @KshitijWeb3
SOLIDITY
NOTES
CONTENTS

Reference Data Type Calldata vs Memory Mapping

Data Locations Storage vs Memory


Global Variables

Fixed Array Structures


Much more
Dynamic Array Enum
BASIC DATA TYPE

Integer

Bool

Address

Byte
Code Eater

What are data types?


Data types in programming languages are like different containers that can hold specific kinds of data. Just as you
can put different things in a box or a bag, you can assign different types of values to different data types in
programming. Here are some examples:

1. Integer: This data type is used to represent whole numbers. For example, you might use an integer data type
to represent the number of items in a shopping cart, like this: `num_items = 5`. Here, `num_items` is the name of
the variable, and `5` is the integer value assigned to it.

2. String: This data type is used to represent text or characters. For example, you might use a string data type to
represent a person's name, like this: `name = "Alice"`. Here, `name` is the variable name, and `"Alice"` is the
string value assigned to it.

3. Boolean: This data type is used to represent true or false values. For example, you might use a boolean data
type to represent whether an item is in stock or not, like this: `in_stock = True`. Here, `in_stock` is the variable
name, and `True` is the boolean value assigned to it.
Code Eater

What are reference data types in solidity?


In Solidity, a reference data type is a type of data that stores a reference to a location in memory where the
actual data is stored. This is different from a value data type, which stores the actual data directly in the variable.

There are three main reference data types in Solidity:

1. Arrays: An array is a collection of values of the same data type. In Solidity, arrays can be either fixed-size or
dynamic. A fixed-size array has a fixed length that is specified when the array is declared, while a dynamic array
can grow or shrink in size as needed. When you declare an array variable, you are creating a reference to a
location in memory where the array is stored.

2. Structs: A struct is a user-defined data type that groups together related data of different data types. When
you declare a struct variable, you are creating a reference to a location in memory where the struct is stored.

3. Mapping: A mapping is a key-value data structure that allows you to store and retrieve values based on a key.
When you declare a mapping variable, you are creating a reference to a location in memory where the mapping
is stored.

Part 1 of 2
Code Eater

What are reference data types in solidity?


Reference data types are useful in Solidity because they allow you to work with complex data structures and pass
them as function arguments. However, they require more memory than value data types, and you need to be
careful when working with them to avoid memory leaks or other issues.

Part 1 of 2
REFERENCE DATA TYPE

Strings

Arrays

Mappings

Struct
DATA LOCATIONS
• Data types such as Array, Structs, Mapping are known as reference data type.
• If we use a reference type, we always have to explicitly provide the data area where the type is
stored.

• Every reference type has an additional annotation, the “data location”, about where it is
stored. There are three data locations: memory, storage and calldata.
DATA LOCATIONS

Data Location About


Memory lifetime is limited to an external function call
the location where the state variables are stored,
Storage where the lifetime is limited to the lifetime of a
contract
special data location that contains the
Calldata
function arguments
ARRAYS

Fixed Array

Dynamic Array
Code Eater

What are fixed arrays in solidity?


In Solidity, fixed-size arrays are arrays with a predetermined length that cannot be changed after their
declaration. The length of a fixed array is specified at the time of declaration and remains constant throughout
the execution of the contract.

Fixed arrays in Solidity are denoted by declaring the type followed by the desired length in square brackets ([]).
For example, `uint256[5]` represents a fixed-size array of `uint256` type with a length of 5.

Here are a few key characteristics and considerations regarding fixed arrays in Solidity:

1. Length: The length of a fixed array is determined at compile-time and cannot be modified dynamically during
runtime.

2. Element Access: Elements within a fixed array can be accessed using their index, starting from 0. For example,
`myArray[0]` accesses the first element of the array.
Code Eater

What are fixed arrays in solidity?


3. Initialization: Fixed arrays can be initialized during declaration or assigned values later using individual
element assignment or bulk assignment.

4. Memory Consumption: Fixed arrays allocate a contiguous block of memory to store all their elements. The size
of the fixed array determines the amount of memory consumed.

5. Iteration: Iterating through a fixed array can be done using a for loop or other looping constructs by iterating
over the indices of the array.

6. Limitations: Fixed arrays have a maximum length of 2^256 - 1 elements due to the inherent limitations of the
EVM (Ethereum Virtual Machine).

Fixed arrays are commonly used in Solidity to store and manipulate a fixed number of elements, such as holding
a collection of values or implementing data structures like queues, stacks, or matrices. They provide efficiency in
terms of memory management and access time when the size of the array is known and remains constant.
FIXED ARRAY

• uint[number_of_elements] public arr;


• uint[5] public arr;

0 0 0 0 0
0 1 2 3 4

• uint[5] public arr = [10,20,30,40,50];

10 20 30 40 50
0 1 2 3 4
Code Eater

What are dynamic arrays in solidity?


In Solidity, dynamic size arrays are arrays whose length can be dynamically changed during runtime. Unlike fixed-
size arrays, the length of dynamic size arrays can be modified by adding or removing elements as needed.

Dynamic size arrays in Solidity are denoted by declaring the type followed by empty square brackets ([]). For
example, `uint256[]` represents a dynamic size array of `uint256` type.

Here are some key characteristics and considerations regarding dynamic size arrays in Solidity:

1. Length: The length of a dynamic size array can be modified by using built-in functions such as `push`, `pop`, or
by direct assignment to a specific index.

2. Element Access: Elements within a dynamic size array can be accessed using their index, starting from 0,
similar to fixed arrays. For example, `myArray[0]` accesses the first element of the array.
Code Eater

What are dynamic arrays in solidity?


3. Initialization: Dynamic size arrays can be initialized during declaration or left empty and later populated with
elements.

4. Memory Consumption: Dynamic size arrays allocate memory dynamically as elements are added or removed.
The amount of memory consumed increases or decreases depending on the length of the array.

5. Iteration: Iterating through a dynamic size array can be done using a for loop or other looping constructs by
iterating over the indices of the array.

6. Limitations: Dynamic size arrays can potentially consume more gas (transaction cost) compared to fixed-size
arrays due to the dynamic memory management involved.

Dynamic size arrays are commonly used in Solidity when the length of an array needs to be flexible and
changeable during the execution of a contract. They are suitable for scenarios where the number of elements
may vary or when data needs to be dynamically stored and manipulated.
DYNAMIC ARRAY

• uint[] public arr;


• To insert an element we use arr.push(element)
• To remove an element we use arr.pop() . It removes the last element every time it is executed.

• To find the length of an arry we use arr.length. It returns the length of the array in uint data type.
DYNAMIC ARRAY

contract demo{
uint[] public arr1;

function returnArray() public


{
arr1.push(1);
arr1.push(2);
}
}

Example - 5
DYNAMIC ARRAY – BYTE

• bytes1[] public arr; • bytes2[] public arr; • bytes32[] public arr;

• Array member functions are push, pop and length.


DYNAMIC ARRAY - BYTE

contract demo{
bytes[] public arr1;

function insertArray() public


{
arr1.push("abcde");
arr1.push("b");
}
}

Example - 7
Code Eater

Memory vs Calldata
In Solidity, `memory` and `calldata` are two distinct storage locations used to handle data within smart contracts.
Here's an explanation of each:

1. `memory`: The `memory` keyword represents a temporary storage area used for storing variables and data
during contract execution. It is primarily used for storing function parameters, local variables, and dynamic arrays
that are created and used within the scope of a function. Memory is volatile, meaning its contents are cleared
once the function execution is completed.

Key points about `memory`:


- Data in `memory` is non-persistent and is not stored on the blockchain.
- Dynamic arrays in `memory` can be resized using functions like `push` or `pop`.
- Assigning a value from storage or `calldata` to `memory` creates a copy of the data.
Code Eater

Memory vs Calldata
2. `calldata`: The `calldata` keyword refers to the input data provided when calling a contract's function. It is a
read-only area that stores the function arguments and data passed from external contracts or transactions.
Contract functions can access and read values from `calldata` but cannot modify its contents.

Key points about `calldata`:


- `calldata` is an immutable storage area, meaning its contents cannot be modified.
- It is used for retrieving function arguments, allowing contract functions to access the data provided during
contract invocation.
- Using `calldata` instead of `memory` can save gas costs when working with large amounts of data since no
copy is made.

In summary, `memory` is used for temporary storage within functions, allowing the contract to store and
manipulate data during execution. On the other hand, `calldata` provides access to the input data provided when
calling a contract function, enabling retrieval of function arguments and data from external contracts or
transactions. Understanding the distinction between `memory` and `calldata` is crucial for efficient data handling
and gas optimization in Solidity contracts.
MEMORY VS CALLDATA

Memory Calldata

Can be used anywhere inside Can be used only in a


a function function argument

Mutable Immutable
DATA LOCATIONS

contract demo{

function returnArray() public pure returns(uint[5] memory)


{
uint[5] memory arr;
return arr;
}
}

Example - 1
DATA LOCATIONS

contract demo{

function returnArray(uint[5] memory _arr,uint length) public pure returns(uint[5] memory)


{
for(uint i=0;i<length;i++){
_arr[i]=_arr[i]*2;
}
return _arr;
}
}

Example - 2
DATA LOCATIONS

contract demo{

function returnArray(uint[5] calldata _arr,uint length) public pure returns(uint[5] memory)


{
uint[5] memory brr;
for(uint i=0;i<length;i++){
brr[i]=_arr[i]*2;
}
return _arr;
}

} Example - 3
Code Eater

Memory vs Storage
In Solidity, the `memory` and `storage` keywords are used to specify the storage location for variables within
smart contracts. Here's an explanation of each:

1. `memory`: The `memory` keyword represents a temporary storage area used for variables and data that are
required during contract execution but are not permanently stored on the blockchain. It is primarily used for
function parameters, local variables, and dynamic arrays that are created and used within the scope of a
function.

Key points about `memory`:


- Data in `memory` is non-persistent and is not stored on the blockchain.
- Variables in `memory` are allocated dynamically during function execution and deallocated afterward.
- Assigning a value from `storage` or `calldata` to `memory` creates a copy of the data.
Code Eater

Memory vs Storage
2. `storage`: The `storage` keyword refers to the persistent storage area on the blockchain. It is used for storing
state variables, which retain their values across multiple function calls and throughout the lifetime of the
contract. State variables declared with the `storage` keyword are stored on the blockchain and can be accessed
and modified by different functions within the contract.

Key points about `storage`:


- Data in `storage` is persistent and is stored on the blockchain.
- State variables declared with `storage` keyword have a fixed storage slot allocated to them.
- Changes made to variables in `storage` are reflected in subsequent function calls and persist across the
contract's lifetime.

In summary, `memory` is used for temporary storage within functions, while `storage` is used for persistent
storage on the blockchain. `memory` is ideal for variables that are only needed during the execution of a
function, while `storage` is suitable for variables that require persistence and can be accessed and modified
across multiple function calls. Understanding the distinction between `memory` and `storage` is essential for
managing data effectively and designing efficient smart contracts.
MEMORY VS STORAGE

uint[3] public arr =[ 10,20,30]; 10 20 30


0 1 2

uint[3] memory arr1 = arr; 10 20 30


0 1 2

arr1[0] = 90; arr1


MEMORY VS STORAGE

uint[3] public arr =[ 10,20,30]; 10 20 30


0 1 2

uint[3] memory arr1 = arr; 90 20 30


0 1 2

arr1[0] = 90; arr1


MEMORY VS STORAGE

uint[3] public arr =[10,20,30]; 10 20 30


0 1 2

uint[3] storage arr2 = arr;

arr2[0] = 90; arr2


MEMORY VS STORAGE

uint[3] public arr =[ 10,20,30]; 90 20 30


0 1 2

uint[3] storage arr2 = arr;

arr2[0] = 90; arr2


STRING DATA TYPE
• string public str ="hello world";

• Solidity does not have string manipulation functions, but there are third-party string libraries.

• We can compare two strings by their keccak256 hash using-


keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2))

• Concatenate two strings using- string.concat(s1, s2)


STRING VS BYTES

• Variables of type bytes and string are special arrays.


• string is equal to bytes but does not allow length or index access.

• By explicit type casting you can convert bytes form to string form.
Code Eater

Struct
• In Solidity, a struct is a user-defined data structure that allows you to create custom composite types by
combining multiple variables of different types into a single entity. It enables you to define your own data
structures with specific properties and behaviors.

• To define a struct in Solidity, you use the `struct` keyword followed by the name of the struct and a list of
member variables enclosed in curly braces. Each member variable has a name and a type.

• Here's an example of a struct representing a person's information:

```solidity
struct Person {
string name;
uint age;
address wallet;
}
```
Code Eater

Struct
In this example, the struct named `Person` consists of three member variables: `name` of type `string`, `age` of
type `uint` (unsigned integer), and `wallet` of type `address`.

Structs in Solidity have the following characteristics:

1. Custom Data Structure: Structs allow you to define your own composite data types with multiple member
variables.

2. Grouping Data: Structs enable you to group related variables together, making it easier to organize and
manage complex data.

3. Reusability: Once a struct is defined, you can create multiple instances (objects) of that struct, each with its
own set of values.

4. Nesting: Structs can be nested within other structs, allowing for the creation of more complex data structures.

5. Passing and Returning: Structs can be passed as arguments to functions or returned as function return values.
Code Eater

Struct
6. Storage Location: Structs can be stored in different locations, such as memory or storage, depending on how
they are used within the contract.

Structs are commonly used in Solidity contracts for various purposes, such as representing complex data entities,
defining data schemas, storing multiple related values together, or creating custom data types that facilitate
contract functionality.
STRUCT

• Struct is a complex data type. A complex data type is usually a composite of other existing data types.

name
struct Student{
string name;
uint roll; roll
bool pass;
}
pass

• struct_type public var_name;

• Student public s1;


STRUCT
contract Classroom {

struct Student{
string name;
uint roll;
bool pass;
}

Student public s1;

function insert() public returns(Student memory){


s1.name="Kshitij";
s1.roll=12;
s1.pass=true;
return s1;
}
}
Output-
0: string: name Kshitij
1:uint256: roll 12
2:bool: pass true
STRUCT
contract Classroom {
struct Student{
string name;
uint roll;
bool pass;
}
Student public s1;
function insert() public returns(Student memory){
s1=Student("Kshitij",12,true);
return s1;
}
}

Output-
0: string: name Kshitij
1:uint256: roll 12
2:bool: pass true
IMPORTANT

• When struct passed as an argument. It takes input in form of tupple.

struct Student{
string name;
["Raj","120","true"]
uint roll;
bool pass;
}

• When struct type is returned it returns data in form of a tupple.


ARRAY WITHIN STRUCT

struct Student{ name


string name;
uint roll;
bool pass; roll
uint8[3] marks;
}
pass

marks
ARRAY WITHIN STRUCT
contract Classroom {

struct Student{
string name;
uint roll;
bool pass;
uint8[3] marks;
}

Student public s1;

function insert(string calldata _name,uint _roll,bool _pass, uint8[3] calldata _marks) public returns(Student
memory){
s1=Student(_name,_roll,_pass,_marks);
s1.marks[0]=2;
return s1;
}
}
ARRAY OF STRUCT

struct Student{
string name;
uint roll;
bool pass; name name name name
}
roll roll roll roll

pass pass pass pass


Student[4] public s1;

0 1 2 3
Code Eater

Enum
• In Solidity, an enum (short for enumeration) is a user-defined data type that allows you to define a set of
named values. Enums provide a way to represent a fixed set of possible options or states for a variable.

• To define an enum in Solidity, you use the `enum` keyword followed by the name of the enum and a list of
member names enclosed in curly braces. Each member name represents a distinct value within the enum.

• Here's an example of an enum representing different states of a contract:

```solidity
enum ContractState {
Active,
Inactive,
Suspended
}
```
Code Eater

Enum
• In this example, the enum named `ContractState` defines three possible states: `Active`, `Inactive`, and
`Suspended`.

• Enums in Solidity have the following characteristics:

1. Predefined Set of Values: Enums define a fixed set of possible values that a variable of that enum type can
take.

2. Named Values: Each value within the enum is assigned a name, which can be used to represent a specific
option or state.

3. Integer Mapping: Internally, each enum value is automatically assigned an integer value starting from zero,
incremented by one for each subsequent value. In the example above, `Active` is assigned the value `0`, `Inactive`
is assigned `1`, and `Suspended` is assigned `2`.

4. Comparisons and Assignments: Enum values can be compared for equality using the `==` operator, and they
can be assigned to variables of the same enum type.
Code Eater

Enum

• Enums are often used in Solidity contracts to represent different states, options, or choices. They provide a
clear and expressive way to define and work with a finite set of distinct values, making the code more
readable and maintainable when dealing with specific conditions or options within the contract logic.
ENUM

• Enums are user-defined data types that restrict the variable to have only one of the predefined values.

• enum Button { ON, OFF }

• Button button;
Code Eater

Mapping
In Solidity, a mapping is a key-value data structure used to associate values (referred to as "values") with unique
keys. It is similar to a hash table or a dictionary in other programming languages.

A mapping is defined using the `mapping` keyword, followed by the key and value types enclosed in angle
brackets (`<` and `>`). For example, `mapping(address => uint256)` declares a mapping where Ethereum
addresses are the keys and unsigned integers (`uint256`) are the corresponding values.

Here are some key characteristics of mappings in Solidity:

1. Key-Value Association: Each key in a mapping is associated with a value. The keys must be of a non-reference
type, such as `address`, `uint`, or `bytes32`, but cannot be arrays or structs.

2. Uniqueness of Keys: Each key in a mapping must be unique. When a value is assigned to an existing key, it
replaces the previous value associated with that key.
Code Eater

Mapping
3. Automatic Initialization: Mappings are automatically initialized with default values. For example, a
`mapping(address => uint256)` will have an initial value of `0` for each address key.

4. No Iteration: Mappings do not support direct iteration over their keys or values. To iterate through the keys, it
is common to use a separate data structure like an array or a set to store the keys.

5. Efficient Lookups: Mappings provide efficient key-value lookups, as retrieving the value associated with a given
key is a constant-time operation.

Mappings are widely used in Solidity for various purposes, such as storing balances of accounts, keeping track of
ownership, managing access control, or implementing data registries. They provide a convenient way to map
unique identifiers (keys) to associated data (values) in a contract.
MAPPING
• Concept of keys and values.
• mapping(key => value)
• mapping(uint => string) public data;
SIMPLE MAPPING
• mapping(uint => string) public data;

_roll​ name​

1​ Ravi​

5​ John​

40​ Alice​

50​ Akash​
Code Eater

Mapping Vs Array
• Mappings and arrays are both data structures in Solidity, but they serve different purposes and have distinct
characteristics. Here's a comparison between mappings and arrays:

Mappings:
- Mappings are key-value data structures, where each key is associated with a value.
- Keys in mappings must be of a non-reference type, such as `address`, `uint`, or `bytes32`.
- Mappings are typically used when you need to efficiently access or store data based on unique keys.
- Mappings provide constant-time lookup for values based on their keys, making them suitable for efficient
retrieval.
- Mappings do not support direct iteration over their keys or values, so separate data structures like arrays or sets
are often used to store the keys for iteration purposes.
- Adding, modifying, or deleting elements in a mapping requires direct manipulation using key-value assignment
or deletion.
Code Eater

Mapping Vs Array
Arrays:
- Arrays are ordered lists of elements of the same type, accessed by their index.
- Elements in arrays can be of any type, including reference types like structs or arrays themselves.
- Arrays are useful when you need to store and retrieve multiple elements sequentially or access them by their
index.
- Arrays support direct iteration using loops or other constructs, allowing you to iterate over all elements in the
array.
- Arrays can be resized dynamically, and elements can be added, modified, or removed at specific indices.
- Arrays have length properties indicating the number of elements they contain.

When to use mappings:


- When you need to efficiently store and retrieve values based on unique keys.
- When you want to associate values with specific identifiers or addresses.
- When you don't require direct iteration over the keys or values.

When to use arrays:


- When you need to store and access multiple elements sequentially or by index.
- When you want to iterate over all elements in a collection.
- When you need dynamic resizing and flexibility in adding, modifying, or removing elements.
MAPPING VS ARRAY

_roll​ name​

1​ Ravi​

2 John​

4 Alice​

7 Akash​

Mapping
MAPPING VS ARRAY

index name
0 Location Waste
1 Ravi
2 John
3 Location Waste
4 Alice
5 Location Waste
6 Location Waste
7 Akash

The array has a lot of empty slots.


MAPPING WITH STRUCT
• mapping(uint=>Student) public data;
name

roll

pass

Student
• mapping(uint=>Student) public data;

uint Student

0
name

roll name
pass
roll

12
name pass
roll
pass

Student

100
name

roll
pass
Code Eater
MAPPING WITH STRUCT

roll​ _name​ _class​ _age​

1​ John​ 7​ 13​

5​ Alice​ 8​ 14​

10​ Ravi​ 3​ 9​
MAPPING WITH ARRAY
mapping(address=>uint[ ]) private marks;

address​ uint[ ]​

0xabc​ 10​ 20​ 30​ 40​ 50​

0xdef​ 1​ 2​ 3​

0x121​ 1​21 2​21 243​ 52

0x23f​ 1​2 22 23​

0x73e​ 10​ 20​ 30​ 40​ 50​


NESTED MAPPING
mapping(address=>mapping(address=>bool)) private check;

address1

address2

address3
address1 true
check[address1][address2] = true

address2 false check[address2][address3] = false

check[address3][address1] = false
address3 false
NESTED MAPPING
mapping(uint=>mapping(uint=>bool)) private check;

2
0 true
check[0][1] = true

1 false check[1][2] = false

check[2][0] = false
2 false
NESTED MAPPING
mapping(address=>mapping(address=>bool)) ownership;

address1

address2

address3
address1 true
ownership[address1][address2] = true

address2 false ownership[address2][address3] = false

ownership[address3][address1] = false
address3 false
IMPORTANT POINTS

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;

contract Demo {
mapping(uint=>uint) public arr;
function check() public {
mapping(uint=>uint) storage arr1=arr;//referencing
arr1[1]=2;
}
}
IMPORTANT POINTS
• Mapping cannot be iterated.

• Mappings can only have a data location of storage and thus are allowed for state variables. In simple
words, you cannot declare mapping inside a function.

• They cannot be used as parameters or return parameters of contract functions that are publicly visible.

• These restrictions are also true for arrays and structs that contain mappings.
PAYABLE ADDRESS
• Same as address, but with the additional members transfer and send.

// function contractTransfer() public payable{


// //code or no code
// }
// function contractBalance() public view returns(uint){
// return address(this).balance;
// }

// function sendUser(address payable reciever) public payable{


// payable(reciever).transfer(msg.value);
// }
// }
PAYABLE FUNCTION
• If a function is payable, this means that it also accepts a payment of zero Ether, so it also
is non-payable.

• On the other hand, a non-payable function will reject Ether sent to it, so non-
payable functions cannot be converted to payable functions.​
FALLBACK
• The fallback function is executed on a call to the contract if none of the other functions
match the given function signature, or if no data was supplied at all and there is no receive
Ether function.

• Fallback function is optionally payable.

• A contract can have at most one fallback function, declared using


either fallback () external [payable] or fallback (bytes calldata input) external [payable] return
s (bytes memory output)

• This function must have external visibility.

• A fallback function can be virtual, can override and can have modifiers.

• The fallback function always receives data, but in order to also receive Ether it must be
marked payable.
RECEIVE
• A contract can have at most one receive function, declared using receive() external payable { ... }.

• This function cannot have arguments, cannot return anything, and


must have external visibility and payable state mutability.

• It can be virtual, can override and can have modifiers.

• If neither a receive Ether nor a payable fallback function is present, the contract cannot
receive Ether through regular transactions and throws an exception.

• Using payable fallback functions for receiving Ether is not recommended.


GLOBAL VARIABLE
blockhash(uint blockNumber) returns (bytes32): hash of the given block when blocknumber is one of the 256 most recent blocks; otherwise returns zero

block.basefee (uint): current block’s base fee (EIP-3198 and EIP-1559)

block.chainid (uint): current chain id

block.coinbase (address payable): current block miner’s address

block.difficulty (uint): current block difficulty

block.gaslimit (uint): current block gaslimit

block.number (uint): current block number

block.timestamp (uint): current block timestamp as seconds since unix epoch

gasleft() returns (uint256): remaining gas

msg.data (bytes calldata): complete calldata

msg.sender (address): sender of the message (current call)

msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier)

msg.value (uint): number of wei sent with the message

tx.gasprice (uint): gas price of the transaction

tx.origin (address): sender of the transaction (full call chain)


www.codeeater.in

THANK YOU
Instagram - @codeeater21
LinkedIn – @kshitijWeb3
YouTube - @codeeater21

You might also like