Solidity Notes
Solidity Notes
Day - 2
Code Eater
Contents
What is a smart contract ? Remix IDE Visibility Specifier
Solidity Compilation
Functions Much more
Process
Videos To Watch
• Solidity Course – Click Here
• Solidity Project Playlist – Click Here
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
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
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
A B
Code Eater
A
B
Code Eater
No
Note-Assuming
optimum Do delivery and
temperature <30 transfer crypto to
degree Celsius. A.
Code Eater
What is solidity?
• Solidity is an object-oriented programming language for implementing smart
contracts for the ethereum blockchain.
• Case sensitive.
• With Solidity you can create contracts for uses such as voting, crowdfunding,
blind auctions, and multi-signature wallets.
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
source.sol file
Solidity Compiler
Ethereum
Blockchain
Code Eater
• 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.
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) .
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.
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.
• 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.
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.
Part 2 of 2
Code Eater
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
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
Output - 0x61
Example - 1
Code Eater
Output - 0x6162
Example - 2
Code Eater
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
• 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.
```
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.
```
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.
```
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{
while(true==true){
//2nd Loop
}
do{
//3rd Loop
}while(true==true);
}
}
Code Eater
Visibility
Within
Contract
Derived
Contract
Other
Contracts
• Please Like and Subscribe :)
• Instagram - @codeeater21
Thank You • LinkedIn - @KshitijWeb3
SOLIDITY
NOTES
CONTENTS
Integer
Bool
Address
Byte
Code Eater
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
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
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
Fixed Array
Dynamic Array
Code Eater
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
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
0 0 0 0 0
0 1 2 3 4
10 20 30 40 50
0 1 2 3 4
Code Eater
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
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
• 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;
Example - 5
DYNAMIC ARRAY – BYTE
contract demo{
bytes[] public arr1;
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.
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.
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
Mutable Immutable
DATA LOCATIONS
contract demo{
Example - 1
DATA LOCATIONS
contract demo{
Example - 2
DATA LOCATIONS
contract demo{
} 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.
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.
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
• Solidity does not have string manipulation functions, but there are third-party string libraries.
• 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.
```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`.
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 Student{
string name;
uint roll;
bool pass;
}
Output-
0: string: name Kshitij
1:uint256: roll 12
2:bool: pass true
IMPORTANT
struct Student{
string name;
["Raj","120","true"]
uint roll;
bool pass;
}
marks
ARRAY WITHIN STRUCT
contract Classroom {
struct Student{
string name;
uint roll;
bool pass;
uint8[3] marks;
}
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
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.
```solidity
enum ContractState {
Active,
Inactive,
Suspended
}
```
Code Eater
Enum
• In this example, the enum named `ContractState` defines three possible states: `Active`, `Inactive`, and
`Suspended`.
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.
• 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.
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.
_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
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
1 John 7 13
5 Alice 8 14
10 Ravi 3 9
MAPPING WITH ARRAY
mapping(address=>uint[ ]) private marks;
address uint[ ]
0xdef 1 2 3
address1
address2
address3
address1 true
check[address1][address2] = true
check[address3][address1] = false
address3 false
NESTED MAPPING
mapping(uint=>mapping(uint=>bool)) private check;
2
0 true
check[0][1] = true
check[2][0] = false
2 false
NESTED MAPPING
mapping(address=>mapping(address=>bool)) ownership;
address1
address2
address3
address1 true
ownership[address1][address2] = true
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.
• 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.
• 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 { ... }.
• If neither a receive Ether nor a payable fallback function is present, the contract cannot
receive Ether through regular transactions and throws an exception.
msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier)
THANK YOU
Instagram - @codeeater21
LinkedIn – @kshitijWeb3
YouTube - @codeeater21