0% found this document useful (0 votes)
16 views103 pages

SOLIDITY

Solidity is a high-level programming language for writing smart contracts on the Ethereum blockchain, enabling the creation of decentralized applications. It supports various deployment environments, including private networks for testing, public testnets for simulation, and the public mainnet for live transactions. Key features include data types, access modifiers, variable scopes, and interfaces, which facilitate secure and efficient contract development.
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)
16 views103 pages

SOLIDITY

Solidity is a high-level programming language for writing smart contracts on the Ethereum blockchain, enabling the creation of decentralized applications. It supports various deployment environments, including private networks for testing, public testnets for simulation, and the public mainnet for live transactions. Key features include data types, access modifiers, variable scopes, and interfaces, which facilitate secure and efficient contract development.
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/ 103

SOLIDITY

A solidity is a contract high-level programming


language. High-level programming languages are
compiled to native bytecode to execute in the EVM
environment.

It is a static-typed high-level programming language,


which means each variable stored and assigned with
type

Solidity code runs on Ethereum Virtual


Machine(EVM). EVMs are run-time environments for
running contract code in the Ethereum platform.
Multiple ways to deploy Contract deployment types in the blockchain

You can use frameworks or REMIX to deploy to blockchain environments.

Private Network:

● A private network is a blockchain network that is restricted to a specific group of participants. It


is often used for testing and development purposes within a closed environment.

● Private networks are useful for developers to experiment with smart contracts without the cost
and security implications of deploying on a public network.

● Examples of private blockchain frameworks include Hyperledger Fabric, Quorum, and Corda.

Example:

● A group of developers working on a project might set up a private Ethereum network for testing
smart contracts among themselves before deploying to a wider audience.
Public Testnet:

○ A public testnet is a blockchain network that mirrors the functionalities of the mainnet but uses
testnet tokens, which have no real-world value. It allows developers to test their smart contracts in
an environment that simulates the conditions of the mainnet without the risk of losing real assets.

○ Public testnets are open to the public, and anyone can interact with them to test decentralized
applications (DApps) and smart contracts.

Example:

○ The Ethereum testnet, such as Ropsten or Rinkeby, allows developers to deploy and test their
smart contracts using testnet ETH instead of real Ether.

Public Mainnet:

○ The public mainnet is the live and production-ready blockchain network where real assets, such as
cryptocurrency, are used. It is the network that is open to the public, and transactions on this
network have real-world consequences.

○ Deploying a smart contract on the mainnet means that it is accessible to everyone, and the
contract's code and state are immutable.

Example:

○ Deploying a smart contract on the Ethereum mainnet means that it becomes part of the Ethereum
blockchain, and users can interact with it using real Ether.
What is a Contract in Solidity?

In Solidity, a contract is a fundamental building block representing a


collection of code (functions) and data (state variables) that resides
at a specific address on the Ethereum blockchain. Contracts are
written in the Solidity programming language, and they enable the
creation of decentralized applications (DApps) and smart contracts
on the Ethereum platform.
Example of a Solidity Contract:
// Solidity version declaration

pragma solidity ^0.8.0;


// Contract definition

contract SimpleContract {
// State variable
uint256 public counter;
// Constructor (executed once during contract deployment)
constructor() {
counter = 0;
}

// Function to increment the counter

function incrementCounter() public {


counter++;
}

// Function to get the current counter value

function getCounter() public view returns (uint256) {


return counter;
}
}
Solidity - Smart Contract

Solidity is a programming language specifically designed


for writing smart contracts on blockchain platforms, with
Ethereum being one of the most popular ones. A smart
contract is a self-executing contract with the terms of the
agreement directly written into code. Once deployed to
the blockchain, a smart contract automatically executes
its predefined logic when triggered by certain conditions.
Example of a Solidity Smart Contract:

// Solidity version declaration

pragma solidity ^0.8.0;

// Contract definition

contract SimpleSmartContract {
// State variables

address public owner;


uint256 public value;

// Event triggered on value change

event ValueChanged(uint256 newValue);

// Constructor executed on contract deployment


constructor() {
owner = msg.sender; // Set the contract deployer as the owner
value = 0; // Initial value
}
// Modifier to restrict access to the owner
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function");
_;
}
// Function to get the current value
function getValue() public view returns (uint256) {
return value;
}
// Function to update the value (only owner can call)
function updateValue(uint256 newValue) public onlyOwner {
value = newValue;
emit ValueChanged(newValue); // Trigger the ValueChanged event
}
}
Solidity - Variable
Data Types in Solidity:

1. Primitive Data Types:


○ uint/int: Unsigned and signed integers of various sizes (e.g., uint256,
int32).
○ bool: Boolean type representing true or false.
○ address: Ethereum address, representing an external account or contract.
○ bytes: Dynamically-sized byte array.
2. Composite Data Types:
○ string: Dynamically-sized string of UTF-8 characters.
○ bytes: Fixed-size byte arrays and dynamically-sized byte arrays.
○ array: Fixed-size or dynamic array of a specific type.
3. User-Defined Data Types:
○ struct: Composite data type allowing the grouping of variables under a single
name.
○ enum: User-defined data type consisting of a set of named values.
Access Modifiers:
Access modifiers in Solidity are keywords that determine the visibility and accessibility of
functions and state variables. There are three main access modifiers:
Public (public):
● Description: A public function or state variable can be accessed from any external contract
or by anyone.
Example:
uint256 public totalSupply;
Internal (internal):
● Description: An internal function or state variable can only be accessed by the current
contract and any contracts that inherit from it.
● Example:

function internalFunction() internal {


// Function logic
}
● External (external):

○ Description: An external function can only be called from outside the contract.
External functions cannot be called internally or by other contracts.
○ Example:

function externalFunction() external {

// Function logic

● Private (private):

○ Description: A private function or state variable can only be accessed within the
current contract. It is not accessible by derived contracts or external contracts.
○ Example:

uint256 private secretNumber;


Variable Naming:

Variable names in Solidity, like in many programming languages, are used to identify
and reference different pieces of data. Some conventions for naming variables in
Solidity include:

1. Camel Case:
○ Example: myVariableName
2. Descriptive Names:
○ Use names that clearly describe the purpose of the variable.
○ Example: totalSupply, userAddress, contractOwner
3. Avoid Ambiguous Names:
○ Choose names that reduce the chances of confusion and ambiguity.
○ Example: Instead of temp, use a more descriptive name like
temporaryVariable.
4. Constants:
○ Use uppercase letters and underscores for constant variable names.
○ Example: MAX_SUPPLY, TOKEN_DECIMALS
Variable type initial default values
Solidity - Variable Scopes
In Solidity, variable scopes determine where a variable can be accessed and
modified within the code. Understanding variable scopes is crucial for writing secure
and efficient smart contracts. Here are the main variable scopes in Solidity:
1. Global Scope:
○ Definition: Variables declared outside any function or block have global
scope.
○ Accessibility: Global variables can be accessed and modified from
anywhere within the contract.
○ Example:
uint256 globalVariable;

function setGlobalVariable(uint256 newValue) public {


globalVariable = newValue;
}
Global Inbuilt Variable
Solidity defines the Global scope of predefined variables and is accessible anywhere contract
running in the blockchain.
Function Scope:

● Definition: Variables declared within a function have function scope.


● Accessibility: Function-scope variables can only be accessed and modified
within the function where they are declared.

● Example:

function exampleFunction() public {

uint256 functionVariable = 42;

// functionVariable is only accessible within this function

}
Block Scope:

● Definition: Variables declared within a block (enclosed by curly braces {})


have block scope.
● Accessibility: Block-scope variables are limited to the block in which they are
defined.
● Example:

function exampleFunction() public {

if (someCondition) {

uint256 blockScopedVariable = 123;

// blockScopedVariable is only accessible within this if block

}
Constructor Scope:

● Definition: Variables declared within the constructor have constructor scope.


● Accessibility: Constructor-scope variables can only be accessed and modified
during the contract deployment.

● Example:

constructor() {

uint256 constructorVariable = 789;

// constructorVariable is only accessible during contract deployment

}
Parameter Scope:

● Definition: Parameters passed to a function have parameter scope.


● Accessibility: Parameter-scope variables can only be accessed within the
function where they are declared.

● Example:

function exampleFunction(uint256 parameter) public {

// parameter is only accessible within this function

}
Abstract Contracts in Solidity
In Solidity, an abstract contract is a contract that cannot be instantiated on its own, and it serves as a blueprint for other
contracts. It can contain abstract functions that must be implemented by the contracts that inherit from it. Abstract
contracts are used to define common interfaces and ensure that certain functions are present in derived contracts
without providing the full implementation.

Abstract Contract Definition:

● An abstract contract is declared using the abstract keyword.


● It can contain both abstract functions (functions without an implementation) and functions with a full
implementation.
● Abstract contracts cannot be deployed on the blockchain by themselves.

// Abstract contract definition

abstract contract MyAbstractContract {

function abstractFunction() public virtual returns (uint256);

function implementedFunction() public returns (string memory) {

return "This function is implemented in the abstract contract.";

}
Abstract Functions:

● Abstract functions are declared without providing the actual implementation.


● Derived contracts must implement all abstract functions from the abstract contract.
● Abstract functions are marked with the abstract keyword.

// Abstract contract with an abstract function

abstract contract MyAbstractContract {

function abstractFunction() public virtual returns (uint256);

}
Derived Contract Implementation:

● Contracts that inherit from an abstract contract must provide concrete implementations for all
abstract functions.
● Use the override keyword to indicate that a function in the derived contract is intended to
override an abstract function.

// Derived contract implementing the abstract functions

contract MyConcreteContract is MyAbstractContract {

function abstractFunction() public override returns (uint256) {

// Provide the implementation for the abstract function

return 42;

}
Solidity Comments :

In Solidity, comments are annotations within the code that are not executed but provide additional
information to developers. Comments are essential for documenting code, making it more
readable, and helping others understand the logic and purpose of different parts of the codebase.
Solidity supports two types of comments: single-line comments and multi-line comments.

Single-Line Comments:

Single-line comments start with // and continue until the end of the line. Anything written after //
on that line is treated as a comment and is ignored by the Solidity compiler.

// This is a single-line comment

uint256 public myVariable; // Another single-line comment


Multi-Line Comments:
Multi-line comments are enclosed between /* and */. They can span multiple lines and are useful for commenting on larger
sections of code.

/*

This is a

multi-line comment

*/

contract MyContract {

/*

Function description:

This function performs some specific task.

*/

function myFunction() public {

// Code logic here

}
Solidity Address Type :
In Solidity, the address type is used to store Ethereum addresses. Ethereum addresses are
hexadecimal identifiers that represent user accounts or smart contracts on the Ethereum blockchain.
Solidity also has several address-related types and functions to interact with addresses. Here's a brief
overview:

1. Address Type:
○ Definition: The basic address type is address. It is 20 bytes long and represents an
Ethereum address.
○ Usage: Used to store Ethereum addresses of user accounts or smart contracts.

Example:

address public owner;


Address Literals:

● Definition: An address literal is an explicit way to represent an Ethereum address in code.


● Usage: Used to assign a specific address to an address type variable.

Example:

address public myAddress = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;

Address Members:

● Members: The balance and transfer members are associated with the address type.
● Usage:
○ balance: Returns the balance of the address in Wei.
○ transfer(uint256 amount): Sends a certain amount of Ether from one address to another.

Example:

address public recipient;

uint256 public recipientBalance = recipient.balance;

function sendEther() public {

recipient.transfer(1 ether);

}
● Address Payable:
○ Definition: The address payable type is an extension of the address type, allowing it to receive Ether and
interact with functions like transfer.
○ Usage: Used for variables and function parameters that can receive Ether.

Example:
address payable public receiver;

function receiveEther() public payable {

// Function logic to receive Ether

● Address Functions:
○ Functions: Solidity provides various functions and modifiers for working with addresses, such as msg.sender and
require.
○ Usage: Used for access control, authentication, and conditional execution based on the sender's address.

Example:
function onlyOwner() public view {

require(msg.sender == owner, "Only the owner can call this function");

}
Solidity If Statement:
The if statement is used to execute a block of code if a specified condition evaluates to
true. If the condition is false, the block is skipped.

// Example of if statement

if (condition) {

// Code to be executed if the condition is true

}
Solidity if-else Statement :
In Solidity, as in many programming languages, the if and else statements are used for
conditional execution of code. These statements allow you to create branches in your code
based on specified conditions.

if Statement:

The basic structure of an if statement is as follows:

if (condition) {

// Code to be executed if the condition is true

} else {

// Code to be executed if the condition is false

}
Example:

/ SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract IfElseExample {
// State variable

uint256 public value;

// Function to update the value based on a condition

function updateValue(uint256 newValue) public {


// If-else statement

if (newValue > 10) {


// Executed if the condition is true

value = newValue;
} else {
// Executed if the condition is false

value = 0;
}
}
}
Solidity if - else if - else conditional expressions
:

The if-else if-else statement allows you to test multiple conditions in a sequential manner.
Each condition is tested one by one, and the block of code associated with the first true condition is
executed. If none of the conditions are true, the else block (if provided) is executed.

// Syntax of if-else if-else statement

if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition2 is true

} else {

// Code to be executed if none of the conditions are true

}
Example :
// Solidity version declaration
pragma solidity ^0.8.0;

// Contract definition
contract ExampleIfElse {
// State variable
uint256 public age;

// Function to categorize age range


function categorizeAge() public view returns (string memory) {
if (age < 18) {
return "You are a minor.";
} else if (age >= 18 && age < 65) {
return "You are an adult.";
} else {
return "You are a senior citizen.";
}
}
}
Solidity Interface
In Solidity, an interface is a way to declare the structure of a contract without
implementing its functionality. It defines the method signatures (function
names, parameters, and return types) that other contracts must implement.
Interfaces are primarily used to enforce a standard or API that multiple contracts
can adhere to, allowing for interoperability and interaction between different
smart contracts.

// Interface declaration

interface MyInterface {

// Function declaration without implementation

function myFunction() external returns (uint256);

}
Key Points:

1. Interface Keyword (interface):


○ Interfaces are declared using the interface keyword.
2. Function Declaration:
○ Interfaces consist of function declarations without providing any implementation
details.
○ The keyword external is often used to specify that the function can only be called
from external contracts.
3. No Implementation:
○ Interfaces do not contain the actual implementation of functions; they only declare the
function signatures.
○ Functions inside interfaces lack curly braces and any logic.
4. Implementation in Contracts:
○ Contracts that implement an interface must provide the actual implementation for
each function declared in the interface.
○ The contract must explicitly mention that it is implementing a specific interface using
the implements keyword.
// ERC-20 Interface
interface ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

event Transfer(address indexed from, address indexed to, uint256 value);


event Approval(address indexed owner, address indexed spender, uint256 value);
}

In this example, the ERC20 interface declares the function signatures for standard ERC-20 token
functions such as totalSupply, balanceOf, transfer, allowance, approve, and
transferFrom. It also declares two events, Transfer and Approval. Contracts that claim to
implement this interface must provide actual implementations for all the functions declared in the
interface.
Loops In Solidity :

In Solidity, loops are used to execute a set of statements repeatedly until a specified condition is met.
Solidity supports two main types of loops: for and while.

For Loop:

The for loop is used when the number of iterations is known in advance. It consists of three parts:
initialization, condition, and iteration expression.

// Example of a for loop

pragma solidity ^0.8.0;

contract ForLoopExample {

uint256 public sum;

function calculateSum(uint256 n) public {

sum = 0;

for (uint256 i = 1; i <= n; i++) {

sum += i;

}
While Loop:
The while loop is used when the number of iterations is not known in advance, and the loop continues until a specified condition becomes false.

// Example of a while loop

pragma solidity ^0.8.0;

contract WhileLoopExample {

uint256 public factorial;

function calculateFactorial(uint256 n) public {

factorial = 1;

uint256 i = 1;

while (i <= n) {

factorial *= i;

i++;

}
Do-While Loop:

While Solidity doesn't have a native do-while loop, you can achieve similar functionality using a while loop
with an initial condition that always evaluates to true.

// Example of a do-while loop (using while)

pragma solidity ^0.8.0;

contract DoWhileLoopExample {

uint256 public sum;

function calculateSum(uint256 n) public {

sum = 0;

uint256 i = 1;

do {

sum += i;

i++;

} while (i <= n);

}
Solidity Constructor :
In Solidity, a constructor is a special function that is automatically executed only once when a smart contract is
deployed to the Ethereum blockchain. The constructor is used to initialize the state variables and perform any
one-time setup that needs to be done during contract deployment. It is defined using the constructor keyword.

// Solidity version declaration

pragma solidity ^0.8.0;

// Contract definition with constructor

contract MyContract {

// State variables

uint256 public myNumber;

// Constructor

constructor(uint256 initialValue) {

// Initialization logic

myNumber = initialValue;

}
Key Points:
1. Declaration:
○ The constructor is declared with the constructor keyword.
○ It has the same name as the contract.
2. Execution:
○ The constructor is executed only once during the contract deployment.
○ It is responsible for initializing state variables and performing any necessary setup.
3. Arguments:
○ Constructors can take parameters, allowing external actors to pass initial values
during contract deployment.
○ Parameters are specified within the parentheses after the constructor keyword.
4. Initialization:
○ The constructor's body contains the initialization logic for state variables and any
other setup that should occur during deployment.
○ State variables can be assigned initial values within the constructor.
Example:

// Solidity version declaration


pragma solidity ^0.8.0;

// Contract definition with constructor


contract SimpleToken {
// State variables
string public name;
string public symbol;
uint256 public totalSupply;
address public owner;

// Constructor
constructor(string memory _name, string memory _symbol, uint256 _totalSupply) {
// Initialization logic
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
owner = msg.sender; // Set the contract deployer as the owner
}
}
Constructor Inheritance in Solidity :

In Solidity, constructor inheritance refers to the way constructors are handled when a contract
inherits from another contract. When a derived contract inherits from a base contract, it may have
its own constructor, and it can choose to explicitly invoke the constructor of the base contract
during deployment. This process ensures that both the base and derived contracts perform their
initialization logic.

In this example, we have two contracts:

1. BaseContract: It has a constructor that initializes a state variable baseValue.


2. DerivedContract: It inherits from BaseContract and has its own constructor. In the
constructor, it explicitly invokes the constructor of the base contract using
BaseContract(_baseInitialValue). The derived constructor also initializes a state
variable derivedValue.
Example :

// Solidity version declaration


pragma solidity ^0.8.0;

// Base contract with a constructor


contract BaseContract {
uint256 public baseValue;

// Constructor of the base contract


constructor(uint256 _baseInitialValue) {
baseValue = _baseInitialValue;
}
}

// Derived contract inheriting from the base contract


contract DerivedContract is BaseContract {
uint256 public derivedValue;

// Constructor of the derived contract


constructor(uint256 _baseInitialValue, uint256 _derivedInitialValue) BaseContract(_baseInitialValue) {
derivedValue = _derivedInitialValue;
}
}
Key Points:

1. Base Constructor Invocation:


○ The DerivedContract constructor includes a call to the constructor of
the BaseContract using BaseContract(_baseInitialValue). This
ensures that the initialization logic of the base contract is executed.
2. Order of Execution:
○ Constructors are executed in the order of inheritance hierarchy, starting
from the most base contract and progressing to the most derived contract.
3. Initialization Order:
○ State variables of the base contract are initialized before those of the
derived contract.
4. Initialization Values:
○ Constructors can take parameters, allowing values to be passed during
deployment for initializing state variables.
Solidity - Events in Smart Contracts
In Solidity, events are a way for smart contracts to communicate and provide
information about specific occurrences to external applications. Events are often
used to notify external parties or other contracts about state changes within the
contract. They are part of the contract's interface and can be subscribed to by
external applications to receive real-time updates.

// Event declaration

event MyEvent(address indexed _from, uint256 _value);

// Triggering the event

function triggerEvent(uint256 _value) public {

// ... some logic ...

emit MyEvent(msg.sender, _value);

}
Key Points:

1. Event Declaration:
○ Events are declared using the event keyword.
○ The event can have parameters, and these parameters define the data that
will be logged when the event is triggered.
2. Indexed Parameters:
○ You can specify certain parameters as indexed. Indexed parameters
allow efficient searching for specific values when querying logs.
3. Event Emission:
○ The emit keyword is used to trigger or emit an event.
○ Events are typically emitted within the functions of the smart contract
where a relevant state change occurs.
Example:

// Solidity version declaration


pragma solidity ^0.8.0;

// Token contract with event


contract MyToken {
mapping(address => uint256) public balances;

// Event declaration for transfer


event Transfer(address indexed _from, address indexed _to, uint256 _value);

// Function to transfer tokens


function transfer(address _to, uint256 _value) public {
require(balances[msg.sender] >= _value, "Insufficient balance");

// Perform the transfer


balances[msg.sender] -= _value;
balances[_to] += _value;

// Trigger the Transfer event


emit Transfer(msg.sender, _to, _value);
}
}
How to emit events in solidity?
In Solidity, events are emitted using the emit keyword within a function. Events are declared using the event
keyword and can include parameters that define the data to be logged when the event is triggered.

// Solidity version declaration


pragma solidity ^0.8.0;

// Contract definition
contract EventExample {
// State variable
uint256 public counter;

// Event declaration
event IncrementEvent(address indexed _caller, uint256 _newValue);

// Function to increment the counter and emit an event


function incrementCounter() public {
// Increment the counter
counter++;

// Trigger the IncrementEvent


emit IncrementEvent(msg.sender, counter);
}
}
1. Event Declaration:
○ The IncrementEvent event is declared with two parameters: _caller (indexed)
and _newValue.
○ The indexed keyword is used to specify that _caller is an indexed parameter,
allowing for more efficient log searches.
2. Function to Increment Counter:
○ The incrementCounter function increments the counter state variable and
triggers the IncrementEvent by using emit.
○ The msg.sender represents the address of the account that called the function.
○ The current value of the counter is also included as a parameter in the event.
3. Event Emission:
○ The emit keyword is used to trigger the event with specific parameter values.
○ The event is recorded in the contract's logs, and external applications or services can
listen for these events to react to state changes.

When this contract is deployed and the incrementCounter function is called, it increments the
counter and triggers the IncrementEvent, logging the caller's address (msg.sender) and
the new value of the counter.
How to listen to events in Solidity?
Listening to events in Solidity is typically done using external applications, tools, or
libraries, rather than directly within Solidity code. In the context of decentralized
applications (DApps), front-end or back-end applications often listen for events
emitted by smart contracts to react to changes in the contract's state.

Example:
// Import web3.js library
const Web3 = require('web3');

// Connect to a local Ethereum node (you should replace this with your node's URL)
const web3 = new Web3('http://localhost:8545');

// Specify the address of the deployed smart contract


const contractAddress = '0x1234567890123456789012345678901234567890';

// Specify the ABI (Application Binary Interface) of the smart contract


const contractABI = [...]; // Replace with the actual ABI of your smart contract
// Create a contract instance

const myContract = new web3.eth.Contract(contractABI, contractAddress);

// Subscribe to the Transfer event

myContract.events.Transfer()

.on('data', (event) => {

console.log('Transfer event received:', event.returnValues);

// Handle the event data as needed

})

.on('error', (error) => {

console.error('Error listening to Transfer event:', error);

});
1. Import the web3.js library.
2. Connect to an Ethereum node using the Web3 constructor.
3. Specify the address and ABI of the deployed smart contract.
4. Create a contract instance using the smart contract's ABI and address.
5. Subscribe to the Transfer event using the events object on the contract instance.
6. Handle the data event when a new Transfer event is emitted by the smart contract.

Note:

● Make sure to replace http://localhost:8545 with the actual URL of your Ethereum
node.
● Replace the contractABI array with the ABI of your specific smart contract.
● The web3.js version and usage might vary depending on the version you are using.
Solidity - Functions in Smart Contracts

In Solidity, functions are units of code that perform specific tasks or operations within a smart contract.
Functions can be called by external actors, such as users or other contracts, to interact with the contract's
state and behavior.

Function Declaration:

// Function declaration

function myFunction(uint256 arg1, address arg2) public returns (uint256) {

// Function logic

return arg1 * 2;

}
Key Points:

1. Visibility Modifiers:
○ Functions can have visibility modifiers (public, internal, external, or private)
to specify who can call them.
2. Function Name:
○ Functions have names that are used to identify and call them.
3. Parameters:
○ Functions can take parameters, which are input values provided when calling the
function.
4. Return Values:
○ Functions can return values, which represent the output or result of the function's
computation.
5. Function Modifiers:
○ Function modifiers (e.g., view, pure, payable) specify additional characteristics of
the function.
Examples:

1. Simple Function without Parameters or Return Value:

// Simple function without parameters or return value

function simpleFunction() public {

// Function logic

// No return statement

2. Function with Parameters and Return Value:

// Function with parameters and return value

function add(uint256 a, uint256 b) public pure returns (uint256) {

// Function logic

return a + b;

}
3. Internal Function with Function Modifier:

// Internal function with a function modifier

function internalFunction() internal view returns (string memory) {

// Function logic

return "Internal function";

4. External Function with Payable Modifier:

// External function with payable modifier

function receiveEther() external payable {

// Function logic to receive Ether

}
Function Modifiers:
1. view and pure:
○ Use view for functions that do not modify state.
○ Use pure for functions that do not read or modify state.

// View function
function getBalance() public view returns (uint256) {
return address(this).balance;
}
// Pure function
function multiply(uint256 a, uint256 b) public pure returns (uint256) {
return a * b;
}

2. payable:

○ Use payable for functions that can receive Ether.

// Payable function

function receiveEther() external payable {

// Function logic to receive Ether

}
Function Overloading:

Solidity supports function overloading, allowing you to define multiple functions with the same name but
different parameter lists. Overloaded functions must have different parameter types or a different number
of parameters.

// Function overloading

function process(uint256 data) public pure returns (uint256) {


// Function logic for processing data of type uint256
return data * 2;
}
function process(string memory data) public pure returns (string memory) {
// Function logic for processing data of type string

return string(abi.encodePacked(data, " processed"));


}
Functions play a crucial role in defining the behavior of smart contracts. They encapsulate the logic that can
be executed and interacted with by external entities, providing the necessary flexibility and functionality to
decentralized applications on the Ethereum blockchain.
Modifiers in Solidity Functions :
Modifiers are reusable pieces of code that can be applied to functions, altering their behavior. They are often used to
enforce conditions before allowing the execution of a function. Modifiers are defined using the modifier keyword, and they
can be combined with various visibility specifiers.

contract ModifierExample {
address public owner;

// Modifier to check if the caller is the owner


modifier onlyOwner() {
require(msg.sender == owner, "Not the owner");
_; // Continue with the function body if the condition is met
}

// Function using the onlyOwner modifier


function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}

In this example:

● The onlyOwner modifier checks if the caller of the function is the owner of the contract.
● The changeOwner function uses the onlyOwner modifier to restrict access to only the contract owner.
Fallback Function:

The fallback function is a special function that is executed when a contract receives Ether without any specific function call.
It is a way for a contract to handle unexpected or direct Ether transfers. The fallback function does not take any parameters
and is marked with the fallback keyword.

Example:

contract FallbackExample {

receive() external payable {

// Fallback function logic for handling Ether transfers

In this example:

● The receive function serves as the fallback function, and it is triggered when the contract receives Ether without a
specific function call.
● The external payable modifier indicates that the function can receive Ether.
Function visibility specifier
In Solidity, function visibility specifiers determine who is allowed to call a function. There are four visibility
specifiers: public, internal, external, and private. Each specifier has different access rules, and
the choice of visibility affects how functions can be accessed and by whom.

1. public:

Public functions can be called from anywhere, both within the contract and externally.

Example:

contract VisibilityExample {
uint256 public publicValue;

// Public function
function setPublicValue(uint256 newValue) public {
publicValue = newValue;
}
}

In this example, the setPublicValue function is declared as public, allowing external actors (other contracts or users)
to call it. The publicValue state variable is also marked as public, making it accessible from outside the contract.
2. internal:

Internal functions can only be called from within the current contract and its derived contracts.

Example:

contract VisibilityExample {

uint256 internalValue;

// Internal function

function setInternalValue(uint256 newValue) internal {

internalValue = newValue;

In this example, the setInternalValue function is marked as internal, making it accessible only from within the
current contract and any contracts that inherit from it.
3. external:

External functions can only be called from outside the current contract.

Example:

contract VisibilityExample {

uint256 externalValue;

// External function

function setExternalValue(uint256 newValue) external {

externalValue = newValue;

In this example, the setExternalValue function is marked as external, making it accessible only from external
contracts or transactions. External functions cannot be called from within the contract itself.
private:
Private functions can only be called from within the current contract. They are not accessible from derived contracts
or external contracts.

Example:

contract VisibilityExample {

uint256 privateValue;

// Private function

function setPrivateValue(uint256 newValue) private {

privateValue = newValue;

In this example, the setPrivateValue function is marked as private, making it accessible only from within the current
contract. It is not visible to external contracts or derived contracts.
Solidity - Arrays in Smart Contracts
In Solidity, arrays are data structures that allow you to store and manipulate collections of elements of the
same data type. Solidity supports both fixed-size arrays and dynamic arrays.

Fixed-Size Arrays:

1. Declaration:

Fixed-size arrays have a predetermined size that cannot be changed after declaration.

// Fixed-size array declaration

uint256[5] public fixedArray;

2. Initialization:

Elements of a fixed-size array can be initialized during declaration.

// Fixed-size array initialization

uint256[5] public fixedArray = [1, 2, 3, 4, 5];


3. Accessing Elements:

Elements in a fixed-size array are accessed using their index.

// Accessing elements in a fixed-size array

uint256 public firstElement = fixedArray[0];

Dynamic Arrays:

1. Declaration:
○ Dynamic arrays can change in size during execution.

// Dynamic array declaration

uint256[] public dynamicArray;


2. Initialization:
Dynamic arrays can be initialized during declaration or later using the push function.

// Dynamic array initialization

uint256[] public dynamicArray = [1, 2, 3];

// Adding elements to a dynamic array

function addElement(uint256 newValue) public {

dynamicArray.push(newValue);

3. Accessing Elements:
Elements in a dynamic array are accessed using their index.

// Accessing elements in a dynamic array

uint256 public firstElement = dynamicArray[0];


4. Array Length:

The length of a dynamic array can be obtained using the length property.

// Getting the length of a dynamic array

uint256 public arrayLength = dynamicArray.length;

Multi-dimensional Arrays:

In Solidity, multi-dimensional arrays are arrays of arrays, allowing you to create structures with multiple
dimensions. You can have arrays with two or more dimensions, and each dimension can have its own length.
Multi-dimensional arrays are particularly useful for representing grids, matrices, or other complex data
structures.
1. Declaration:
A multi-dimensional array is declared by specifying the size of each dimension.

// Two-dimensional array declaration

uint256[][] public twoDimArray;

2. Initialization:
Elements of a multi-dimensional array can be initialized during declaration.

// Two-dimensional array initialization

uint256[][] public twoDimArray = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

];
3. Accessing Elements:
Elements in a multi-dimensional array are accessed using two indices.

// Accessing elements in a two-dimensional array

uint256 public element = twoDimArray[1][2]; // Retrieves the element at row

Example Contract that demonstrates the use of a two-dimensional array :


pragma solidity ^0.8.0;

contract MultiDimArrayExample {
// Two-dimensional array
uint256[][] public twoDimArray;

// Constructor to initialize the two-dimensional array


constructor() {
twoDimArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
}
// Function to retrieve an element from the two-dimensional array

function getElement(uint256 row, uint256 col) public view returns (uint256) {

return twoDimArray[row][col];

In this contract:

● twoDimArray is a two-dimensional array initialized in the constructor.


● The getElement function allows you to retrieve an element from the two-dimensional array by specifying the row
and column indices.
Operators and Methods in Solidity

Operators in Solidity are symbols or keywords that perform operations on variables and values. Solidity
supports a variety of operators, including arithmetic operators, comparison operators, logical operators,
and assignment operators. Here's a brief explanation of some common operators with examples:

Arithmetic Operators:

1. Addition (+):

Adds two values.

uint256 result = 5 + 3; // Result is 8

2. Subtraction (-):

Subtracts the right operand from the left operand.

uint256 result = 10 - 7; // Result is 3


3. Multiplication (*):

Multiplies two values.

uint256 result = 4 * 6; // Result is 24

4. Division (/):

Divides the left operand by the right operand.

uint256 result = 15 / 3; // Result is 5

5. Modulus (%):

Returns the remainder of the division.

uint256 result = 17 % 4; // Result is 1


Comparison Operators:
1. Equality (==):

Checks if the left and right operands are equal.


bool isEqual = (5 == 5); // isEqual is true

2. Inequality (!=):

Checks if the left and right operands are not equal.

bool isNotEqual = (10 != 5); // isNotEqual is true

3. Greater Than (>):

Checks if the left operand is greater than the right operand.

bool isGreaterThan = (8 > 5); // isGreaterThan is true

4. Less Than (<):

Checks if the left operand is less than the right operand.

bool isLessThan = (3 < 7); // isLessThan is true


Logical Operators:

1. Logical AND (&&):

Returns true if both the left and right operands are true.

bool result = (true && false); // result is false

2. Logical OR (||):

Returns true if at least one of the operands is true.

bool result = (true || false); // result is true

3. Logical NOT (!):

Returns true if the operand is false and vice versa.

bool result = !true; // result is false


Assignment Operators:

1. Assignment (=):
○ Assigns the value on the right to the variable on the left.

uint256 x = 10;

2. Addition Assignment (+=):


○ Adds the right operand to the left operand and assigns the result to the left operand.

uint256 x = 5;

x += 3; // x is now 8

3. Subtraction Assignment (-=):


○ Subtracts the right operand from the left operand and assigns the result to the left
operand.

uint256 x = 10;

x -= 4; // x is now 6
Solidity - Enumerations (Enums)

In Solidity, enumerations, often referred to as enums, are user-defined data types that allow
developers to create a set of named values. Enums are useful for representing a finite set of possible
states or options within a contract. Each value in an enum is assigned an integer value starting from
zero, and these values are used as identifiers.

Enum Declaration:

Enums are declared using the enum keyword, followed by the name of the enumeration and a list of possible values.

// Enum declaration
enum Status {
Pending,
Approved,
Rejected
}

In this example, we have an enum named Status with three possible values: Pending, Approved, and Rejected. By
default, these values are assigned integer values starting from zero (Pending is 0, Approved is 1, and Rejected is 2).
Using Enums in Contracts:
Enums can be used within contracts to define variables and function parameters with the enum type.

contract DocumentApproval {
// Enum declaration
enum Status {
Pending,
Approved,
Rejected
}

// Struct to represent a document


struct Document {
string name;
Status status;
}

// Mapping to store document status


mapping(uint256 => Document) public documents;

// Function to update document status


function updateDocumentStatus(uint256 documentId, Status newStatus) public {
documents[documentId].status = newStatus;
}
}
In the above example:

● The DocumentApproval contract contains an enum named Status with the possible states of a document: Pending,
Approved, and Rejected.
● The contract includes a Document struct with a field for the document name and a field of the Status enum type to
represent the status of the document.
● The contract uses a mapping to associate each document ID with its corresponding Document struct.
● The updateDocumentStatus function allows changing the status of a document by providing the document ID and the
new status from the Status enum.

Enum with Explicit Values:

You can also assign explicit values to enum members if needed.

// Enum with explicit values


enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
In this example, Monday is explicitly assigned the value 1, and the subsequent values are assigned automatically, incrementing
from the previous value.
Solidity - Strings in Smart Contracts
Declaration and Initialization:
// String declaration and initialization

string public greeting = "Hello, World!";

In this example, a public string variable named greeting is declared and initialized with the value "Hello,
World!".

Concatenation:
Solidity does not directly support string concatenation. However, you can use the abi.encodePacked function to
concatenate strings.

// String concatenation using abi.encodePacked

string public greeting = "Hello";

string public name = "Alice";

string public greetingWithName = string(abi.encodePacked(greeting, " ", name));

In this example, greetingWithName will be "Hello Alice".


Length:

You can obtain the length of a string using the bytes type, which represents the raw bytes of the string.

// Getting the length of a string

string public message = "Greetings!";

uint256 public messageLength = bytes(message).length;

In this example, messageLength will be the number of bytes in the string "Greetings!".
Solidity - Structs
Structs are used to represent the object or classes in java, interface, and
classes in typescript.
Struct Initialization:

● Structs allow you to group related variables together.


● Initialization can be done using the struct constructor.

Struct Operations:

Access individual struct members using dot notation.

Struct Arrays:

Arrays of structs are also common.


Solidity - Mapping in Smart Contracts
Mapping Operations:

Set and retrieve values using square bracket notation.

In Solidity, you declare a mapping by specifying the key and value types within the
mapping keyword.
You can also declare mappings with other data types as keys or values, and even use more
complex data structures as values. For instance:
How to add values to Mapping in solidity?
In Solidity, you can add values to a mapping by assigning a value to a specific key using the
square bracket notation.
In this example:

● The setBalance function takes two parameters: an address representing the


account and a uint representing the balance amount.
● Inside the function, balances[account] = amount; assigns the specified
amount to the mapping key account.

You can then call the setBalance function to add or update balances for different
addresses:

After calling the setBalance function, the balances mapping will contain the
assigned values for the corresponding addresses.
Solidity - Memory VS Storage
Storage:

● Persistent data storage on the Ethereum blockchain.


● State variables are stored in storage.
Stack:

● Used for small, local variables.


● Limited in size and typically holds function arguments and local variables.

Memory vs. Storage:

● Memory is temporary, used for function execution.


● Storage is persistent, used for state variables.
● Explicitly manage data location for efficiency.
Difference between Memory and Storage and Stack in Solidity?
Solidity - Ether in Smart Contracts
- Ether (ETH) is the native cryptocurrency of the Ethereum blockchain.

- Smart contracts can send, receive, and manage Ether.


Sending Ether:

Checking Ether Balance:


Ether and Currency Units in Solidity
- Ether (ETH) is the default currency on the Ethereum blockchain.

- Wei is the smallest unit of Ether (1 Ether = 10^18 Wei).

Currency Units:

● Common currency units include wei, szabo, finney, and ether.


● Use these units for readability and to avoid mistakes.
Conversion Functions:

● Solidity provides conversion functions for different units.


Thank
You !!!

You might also like