Blockchain Essentials | Part 3

 Solidity Basics

Solidity is a contract-oriented programming language for writing smart contracts on the Ethereum blockchain. It is similar to JavaScript and is used to create decentralized applications (dapps) on the Ethereum platform. Some key features of Solidity include:

  • Support for inheritance and complex user-defined types
  • Support for libraries and complex user-defined functions
  • Support for contract-level events and logging
  • Support for contract-level access control and security
  • Support for decentralized deployment and execution of smart contracts

A basic example of a Solidity contract is as follows:

pragma solidity ^0.7.0;

contract MyContract {
    uint256 myVariable;

    function setMyVariable(uint256 _newValue) public {
        myVariable = _newValue;
    }

    function getMyVariable() public view returns (uint256) {
        return myVariable;
    }
}

This simple contract has a single variable, “myVariable,” that can be set and read using the “setMyVariable” and “getMyVariable” functions, respectively. These functions are defined as “public,” meaning that they can be called from any external account.

It’s important to note that smart contracts are immutable once deployed, and can only be modified by creating and deploying a new version.

Structure of Solidity Smart Contract

A Solidity smart contract is a program that runs on the Ethereum Virtual Machine (EVM). It is written in the Solidity programming language and is stored on the Ethereum blockchain.

A Solidity contract typically has the following structure:

  1. pragma statement: This specifies the version of the Solidity compiler that the contract is written for.
  2. contract statement: This defines the contract name and its visibility (public or internal).
  3. state variables: These are variables that store the contract’s data and persist on the blockchain.
  4. constructor: This is a special function that is executed when the contract is deployed. It is used to initialize state variables.
  5. functions: These are the contract’s functions that can be called by external parties or other contracts.
  6. modifiers: These are used to modify the behavior of functions.
  7. events: These are used to emit log messages that can be read by external parties.
  8. address and mapping: These are used to interact with other contracts or addresses on the Ethereum blockchain.
  9. require and assert statement: These used to check conditions and validity of the input, before executing the functions.
  10. modifiers: These are used to modify the behavior of functions.
  11. events: These are used to emit log messages that can be read by external parties.
  12. address and mapping: These are used to interact with other contracts or addresses on the Ethereum blockchain.
  13. structs: These are used to define custom data types that can be used to organize complex data.

Types of Solidity

Solidity is a programming language for writing smart contracts on the Ethereum blockchain. In Solidity, there are several types of data that can be used in a smart contract:

  1. Boolean: a true or false value. Example: bool isValid; declares a boolean variable named “isValid”.
  2. Integer: a whole number, either signed or unsigned. Example: uint256 count; declares an unsigned 256-bit integer named “count”.
  3. Address: a 20-byte value representing the address of an Ethereum account. Example: address owner; declares a variable named “owner” that will hold the address of an Ethereum account.
  4. Fixed-point decimal: a decimal number with a fixed number of decimal places.
  5. String: a sequence of characters. Example: string name; declares a variable named “name” that will hold a string.
  6. Bytes: a sequence of bytes of a fixed or dynamic length.
  7. Enum: a custom type with a fixed set of named values. Example: enum Action {Approve, Reject} declares an enumeration type named “Action” with two possible values “Approve” and “Reject”.
  8. Array: a fixed or dynamic-sized list of elements of a given type. Example: uint[] numbers; declares an array of unsigned integers named “numbers”.
  9. Mapping: a collection of key-value pairs, where the keys and values can be of any type. Example: mapping (address => uint) balances; declares a variable named “balances” that map addresses to unsigned integers.
  10. Struct: a custom data structure that can contain multiple fields of different types. Example: struct User {string name; uint age;} declares a struct type named “User” that has two fields “name” and “age” which are string and uint respectively.
  11. Function: a function type which can be used to represent the type of a function pointer.
  12. Contract: a contract type which can be used to represent the type of a contract instance.
  13. Tuple: a collection of multiple values of different types.

Additionally, Solidity also supports the use of user-defined types, such as libraries and interfaces, which can be used to create reusable code and abstract contracts.

Solidity Variables

In Solidity, variables are used to store data within a smart contract. There are several types of variables that can be used in Solidity, each with their own specific properties and use cases.

  1. State variables: These variables are used to store the contract’s current state and can be accessed by other contracts or functions. They are stored on the blockchain and their values persist after a contract execution.
  2. Local variables: These variables are used within a function or a block scope, they are not visible outside of that scope, and they are stored in memory.
  3. Global variable: A global variable is a type of state variable that can be accessed from any contract or function within the same contract. They are stored on the blockchain and their values persist after a contract execution.
  4. Memory variables: These variables are used to temporarily store data during the execution of a function. They are stored in the memory of the EVM and their values are lost after the function execution.
  5. Storage variables: These variables are used to store data that is persistent but not part of the blockchain state. They are stored in the storage of the EVM and their values persist after a contract execution, but they can only be accessed from within the contract.
  6. Function parameters: These variables are used to pass data into a function when it is called. They are stored in memory and are only visible within the function scope.

Each variable in Solidity must be declared with a specific type, such as uint256 for a 256-bit unsigned integer or address for an Ethereum address. Additionally, variables can be declared as constant, which means their value cannot be changed after they are set, or as a public or private, which controls the visibility and accessibility of the variable.

State variables

Solidity is a statically typed language, which means that the type of each variable (state and local). State variables are variables whose values are permanently stored in contract storage. These Variables are those variables that are defined outside a function whereas Local variables are those variables that are defined inside a function.

In Solidity, state variables are used to store the current state of a smart contract on the Ethereum blockchain. They are stored on the blockchain, and their values persist after a contract execution. They can be accessed and modified from any contract or function within the same contract and their visibility can be defined as public, internal or private.

Public state variables: Public state variables can be accessed and modified from any contract or function, regardless of its address. They can be also accessed outside of the contract, using web3 library for example.

Internal state variable: Internal state variables can be accessed and modified from any contract or function within the same contract. They are not accessible from other contracts.

Private state variables: Private state variables can only be accessed and modified from within the same contract and cannot be accessed from other contracts or functions.

It’s important to note that, since state variables are stored on the blockchain, every time their value is changed, it will cost gas to write to the blockchain, so it’s best to minimize the usage of state variables and use memory or storage variables whenever possible.

Local variables

Variables whose values are available only within a function where it is defined. Function parameters are always local to that function.

In Solidity, local variables are used to temporarily store data within a specific scope, such as within a function or a block. They are stored in memory and their values are lost after the function execution or the block scope is exited.

Local variables can be of any data types, such as integers, booleans, addresses, and arrays. They can be declared with the “var” or “let” keyword, and it is common practice to explicitly define their type.

Local variables are used to store temporary data that is needed for the execution of a specific function or block, such as temporary results or loop counters. Because they are stored in memory, they are not permanent and their values are lost after the function execution or the block scope is exited.

Unlike state variables, local variables do not have visibility properties such as public, internal, or private. They are only accessible within the scope they are declared, they are not accessible from other functions or contract.

It’s also important to note that, since local variables are stored in memory, their usage does not cost gas, therefore it’s best to use them whenever possible in order to minimize the gas cost.

Global Variable

In Solidity, global variables are state variables that can be accessed from any contract or function within the same contract. They are stored on the blockchain and their values persist after a contract execution.

Global variables are declared outside of any function or constructor and are usually declared as public or internal, which determines their accessibility. Public global variables can be accessed from any contract or function, while internal global variables can only be accessed from within the same contract.

For example,

pragma solidity ^0.8.0;

contract Example {
    uint256 public globalVar;

    function setGlobalVar(uint256 _value) public {
        globalVar = _value;
    }
}

In the above example, globalVar is a public global variable of type uint256 that can be accessed and modified from any function within the Example contract.

It’s important to note that, since global variables are stored on the blockchain, every time their value is changed, it will cost gas to write to the blockchain, so it’s best to minimize the usage of global variables and use memory or storage variables whenever possible.

Functions

Functions are the executable units of code. Functions are usually defined inside a contract, but they can also be defined outside of contracts.

In Solidity, functions are blocks of code that can be called by external contracts or users to interact with the contract’s state. Functions can be used to perform specific tasks, such as updating the contract’s state, sending ether or tokens to other accounts, or performing complex calculations.

Example of Function in solidity
Syntax of Function

Functions have the following basic structure:

  1. Function declaration: This includes the function name, input parameters, and return type (if any).
  2. Function body: This is the code that is executed when the function is called.
  3. Function visibility: This defines whether the function can be accessed from other contracts or from outside the contract. Public functions can be accessed from any contract or from outside the contract, while internal and private functions can only be accessed from within the same contract.

Here is an example of a simple Solidity function:

pragma solidity ^0.8.0;

contract Example {
    uint256 public balance;

    function deposit(uint256 _value) public payable {
        require(_value > 0);
        balance += _value;
    }
}

In this example, the deposit function allows external contracts or users to send ether to the contract and update the contract’s balance. The function requires that the value passed as an argument is greater than zero and adds the value to the balance state variable.

Functions in Solidity can also have modifiers, which can be used to add additional functionality or constraints to a function, such as access control or error handling.

Remix IDE

Smart contracts can be executed on Remix IDE. It is a no-setup tool with a GUI for developing smart contracts. Link for online Remix idehttps://remix-project.org/

Remix is an Integrated Development Environment (IDE) for writing, testing, and deploying smart contracts on the Ethereum blockchain. It is a browser-based tool that provides a user-friendly interface for writing, debugging, and testing smart contracts written in Solidity, the programming language for Ethereum.

Remix allows developers to easily test and deploy contracts on the Ethereum network, which makes it a popular choice for developers who are new to smart contract development or for those who want to quickly test their code without setting up a local development environment.

  1. Code editor: Remix provides a built-in code editor with support for syntax highlighting, error checking, and autocompletion for Solidity code.
  2. Compiler: Remix has a built-in Solidity compiler that can be used to check for errors and optimize code.
  3. Virtual Machine: A built-in JavaScript VM allows testing smart contracts without the need for a local or test blockchain.
  4. Debugger: Remix includes a built-in debugger that can be used to step through contract execution and view variable values, which helps to identify and fix errors.
  5. Deployment: Remix supports connecting to a local or test blockchain for deploying and testing contracts on a live network.
  6. File explorer: A built-in file explorer allows managing contract files, making it easy to organize and navigate through your project.
  7. Terminal: The built-in terminal can be used to run command line tools, which allows developers to use additional tools and plugins.
  8. UI Design: User-friendly interface and easy to use for developers.
  9. Plugins : Remix allows developers to add plugins for additional functionalities and features.
  10. Multi-Language Support: Remix provides a multi-language interface for developers who are more comfortable with languages other than English.
  11. Real-time analysis: With Remix, developers can get real-time analysis of their code, including errors, warnings, and suggestions for better coding practices.

These features are designed to make the process of smart contract development faster, more efficient, and more reliable.

Related Questions

Give a preview of a program in remix Ide.

Open the Remix Ide

To create Smart Contracts under File Explorer go to contracts folder. Right Click to create new File “file_name.sol”

After writing contract. Compile it to find errors. After compilation Run and Deploy the smart contract on Blockchain.

On successful deployment a transaction will be created

Interact with smart contract

For each function call get and set. A new transaction is created


Write a Smart Contract to implement Arithmetic operations.

//Solidity program to

//demonstrate addition

pragma solidity 0.6.6;
contract MathPlus
{
// Declaring the state
// variables

uint first; 
uint second ;

// Defining the function 
// to set the value of the first variable 

function firstNoSet (uint x) public 
 {
    First = x;
 }

// Defining the function
// to set the value of the second variable

function secondNoSet (uint y) public
 {
    second = y;
 }

// Defining the function
// to add the two variables

function add() view public returns (uint)
 {
    uint Sum = first + second;

    //Sum of two variables 
     return Sum;
 }
}

Write a smart contract to find the greatest of three numbers.

Here is an example of a smart contract written in Solidity that finds the greatest of three numbers:

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract GreatestNumber {
    function findGreatest(uint a, uint b, uint c) public pure returns (uint) {
        if (a >= b && a >= c) {
            return a;
        } else if (b >= a && b >= c) {
            return b;
        } else {
            return c;
        }
    }
}

This contract defines a single function, findGreatest, which takes in three unsigned integers (a, b, and c) and returns the greatest of the three. The function uses an if-else statement to determine which of the three input numbers is the largest and returns that number.

Note: the contract is not optimized for gas consumption and doesn’t handle edge cases like NaN, Infinity or negative numbers.


Write a smart contract to find whether the number is odd or even.

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract OddEven {
    function isOddOrEven(uint256 num) public view returns (string memory) {
        if (num % 2 == 0) {
            return "Even";
        } else {
            return "Odd";
        }
    }
}

This contract, called “OddEven”, has one function called “isOddOrEven” which takes an input of type “uint256” (unsigned integer of 256 bits) and returns a string “Even” if the number is even and “Odd” if it’s odd. The function uses the modulo operator(%) to check the remainder of dividing the input number by 2. If the remainder is 0, the number is even, otherwise it is odd.


Write a smart contract to swap two numbers.

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract NumberSwap {
    uint256 private firstNumber;
    uint256 private secondNumber;

    function setNumbers(uint256 _firstNumber, uint256 _secondNumber) public {
        firstNumber = _firstNumber;
        secondNumber = _secondNumber;
    }

    function swapNumbers() public {
        uint256 temp = firstNumber;
        firstNumber = secondNumber;
        secondNumber = temp;
    }

    function getFirstNumber() public view returns (uint256) {
        return firstNumber;
    }

    function getSecondNumber() public view returns (uint256) {
        return secondNumber;
    }
}

This is a smart contract written in the Solidity programming language, which is used to write smart contracts for the Ethereum blockchain. It defines a contract named “NumberSwap” which has two private state variables named “firstNumber” and “secondNumber” to store the numbers that need to be swapped.


Create a smart contract of grade system using following range:

90-100

75-90

50-75

35-50

0-35

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;


contract Grading
{
    uint marks;


    function inputMarks(uint x) public{
        marks=x;
    }
    function GradeGiven() public view returns(string memory){
        if(marks>=90 && marks<=100){
            string memory str="Grade A";
            return str;
        }
        else if(marks>75 && marks<90){
            string memory str="Grade B";
            return str;
        } else if(marks>50 && marks<70){
            string memory str="Grade C";
            return str;

        }
        else if(marks>35 && marks<50){
            string memory str="Grade D";
            return str;
        }
        else{
            string memory str="Fail";
            return str;
        }
    }

}

* The material and content uploaded on this website are for general information and reference purposes only and don’t copy the answers of this website to any other domain without any permission or else copyright abuse will be in action.

Please do it by your own first!

DMCA.com Protection Status

To understand more about Solidity language,

Click here
4 1 vote
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments



3
0
Would love your thoughts, please comment.x
()
x