Solidity

Fundamentals of Solidity

In this Part, we will deep dive into Ethereum's most popular contract-oriented language, called Solidity. We will cover Solidity's source code file structure and the different data types supported. We will also understand the different units, global variables, and functions it supports and where these should be used, and maany more’s.

Top resource to learn solidty by Example: https://solidity-by-example.org/

Solidity Compilation Process

How Compilation Process of Solidity work

A successful compilation will generate several outputs depending on the compiler options used:

  • Bytecode: This is the primary output, consisting of machine code the EVM can execute. It represents the compiled version of your smart contract.

  • Application Binary Interface (ABI): This defines how to interact with your smart contract's functions, variables, and events from an external application.

  • Other Outputs (Optional): The compiler can also generate additional outputs like assembly code for debugging or gas usage estimates.

What is Solidity?

Solidity is a statically-typed programming language designed for developing smart contracts that run on the Ethereum Virtual Machine (EVM). It was influenced by C++, Python, and JavaScript and is used to create contracts for voting, crowdfunding, blind auctions, multi-signature wallets, and more

Sample Contract Structure

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

contract MyFirstContract {
    // Contract code goes here
}
  • pragma solidity: Specifies the version of Solidity.

  • contract MyFirstContract: Declares a contract named MyFirstContract.


2. Data Types and Variables

Solidity supports several basic data types. Variables are used to store data, and every variable in Solidity has a type.

Value Types

  1. Boolean:

    • true or false

    bool public isTrue = true;
  2. Integer:

    • Supports both signed (int) and unsigned (uint) integers. You can specify the bit size, e.g., uint8, uint256.

    uint public myNumber = 42; // Unsigned integer
    int public myInt = -10; // Signed integer
  3. Address:

    • Represents an Ethereum address.

    address public myAddress = 0x1234567890123456789012345678901234567890;
  4. Bytes:

    • Fixed-size byte arrays from bytes1 to bytes32.

    bytes32 public myBytes = "hello";

Reference Types

  1. Arrays:

    • Arrays can be fixed or dynamic in size.

    uint[] public dynamicArray;
    uint[5] public fixedArray;
  2. Mappings:

    • Used for key-value pairs.

    mapping(address => uint) public balances;

3. State and Local Variables

State Variables

State variables are stored on the blockchain and persist between function calls.

contract StateExample {
    uint public stateVariable = 10;  // Stored on the blockchain
}

Local Variables

Local variables are temporary and exist only within the scope of a function.

contract LocalExample {
    function setLocal() public pure returns(uint) {
        uint localVariable = 20;  // Exists only in this function
        return localVariable;
    }
}

4. Constants and Immutable Variables

Constant Variables

These variables' values cannot be modified after initialization.

contract ConstantExample {
    uint public constant constantValue = 100;
}

Immutable Variables

Immutable variables can be set only once, typically in the constructor.

contract ImmutableExample {
    uint public immutable immutableValue;

    constructor(uint _value) {
        immutableValue = _value;  // Set once during deployment
    }
}

5. Functions

Functions in Solidity contain executable units of code that can be invoked externally or internally.

Basic Function

contract FunctionExample {
    function add(uint x, uint y) public pure returns (uint) {
        return x + y;
    }
}
  • public: The function can be called both internally and externally.

  • pure: Declares that the function doesn't read or modify state variables.

View Functions

Functions that only read state variables are declared with the view keyword.

contract ViewExample {
    uint public num = 5;

    function getNum() public view returns (uint) {
        return num;  // Reads state variable but does not modify it
    }
}

Modifiers in Functions

Modifiers control the visibility and behavior of functions, such as:

  • public: Accessible by everyone.

  • private: Accessible only within the contract.

  • external: Called only from outside the contract.

  • internal: Called only by this contract or derived contracts.


6. Events

Events in Solidity are used for logging. Applications can listen to these events and execute responses.

contract EventExample {
    event MyEvent(address indexed from, uint value);

    function triggerEvent(uint _value) public {
        emit MyEvent(msg.sender, _value);  // Emits the event
    }
}
  • emit: Keyword to trigger an event.

  • indexed: Marks a field to be searchable in logs.


7. Control Structures

Solidity supports common control structures like if, for, and while loops.

If-Else Statement

contract IfElseExample {
    function checkNumber(uint _num) public pure returns (string memory) {
        if (_num > 10) {
            return "Greater than 10";
        } else {
            return "Less than or equal to 10";
        }
    }
}

For Loop

contract LoopExample {
    uint[] public numbers;

    function loop() public {
        for (uint i = 0; i < 10; i++) {
            numbers.push(i);
        }
    }
}

8. Constructor and Inheritance

Constructor

A constructor is an optional function that runs only once at the time of deployment.

contract ConstructorExample {
    uint public x;

    constructor(uint _x) {
        x = _x;  // Initialize state variable during deployment
    }
}

Inheritance

Solidity supports inheritance, enabling contracts to inherit functionality from other contracts.

contract ParentContract {
    function greet() public pure returns (string memory) {
        return "Hello from Parent";
    }
}

contract ChildContract is ParentContract {
    function callParentGreet() public view returns (string memory) {
        return greet();  // Calls Parent contract's function
    }
}

9. Payable Functions

Payable functions allow a contract to receive Ether.

contract PayableExample {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    function deposit() public payable {}

    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

10. Error Handling

Solidity provides mechanisms to handle errors, including require, assert, and revert.

Require

Used to validate conditions before executing the function.

function validate(uint _x) public pure {
    require(_x > 0, "Input must be greater than 0");
}

Assert

Used for internal errors and invariants (conditions that must hold true).

function checkInvariant(uint _x) public pure {
    assert(_x > 0);
}

Example Case

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// is a special function that is automatically called once when the contract 
// is deployed (created) on the blockchain. It's used to initialize state variables.
contract Demo {
    int number;

    constructor() public {
        number = 5;
    }

    // This getter we want to get the value
    function getter() public view returns (int) {
        return number;
    }

    // this function we want to increment the value
    function increment() public {
        number = number + 1;
    }

    string public sentence = "hello world"; // Commented out for clarity
}

Explanation:

  1. License Identifier:

    • The first line // SPDX-License-Identifier: MIT is a comment that specifies the license under which your code is distributed. In this case, it's the MIT License, a permissive open-source license.

  2. Solidity Version:

    • pragma solidity 0.8.26; declares the version of Solidity you're using. This version (0.8.26) is relatively recent, ensuring compatibility with newer features and security fixes.

  3. Smart Contract Definition:

    • contract Demo { ... } defines a smart contract named Demo. Smart contracts are self-executing programs stored on the blockchain that can hold data and execute code under certain conditions.

  4. State Variable:

    • int number; declares a state variable named number of type int. State variables store data within the smart contract that persists across function calls and transactions. In this case, number can hold whole numbers (positive, negative, or zero).

  5. Constructor:

    • constructor() public { ... } is a special function that is automatically called once when the contract is deployed (created) on the blockchain. It's used to initialize state variables.

    • number = 5; assigns the initial value of 5 to the number variable.

  6. Getter Function (getter)

    • function getter() public view returns (int) { ... } defines a function named getter.

      • public: This keyword allows anyone to call this function from outside the contract.

      • view: This keyword indicates that the function doesn't modify the contract's state (it only reads data).

      • returns (int): This specifies that the function returns an integer value.

    • return number; returns the current value of the number variable.

  7. Incrementer Function (increment)

    • function increment() public { ... } defines a function named increment.

      • public: Similar to the getter function.

    • number = number + 1; increments the value of number by 1.

  8. Commented-Out Line (Optional)

    • // string public sentence = "hello world"; This line is commented out (preceded by //), meaning it's not executed. It's likely included for demonstration purposes, declaring a string variable named sentence with the value "hello world".

In Summary:

This Solidity code defines a simple smart contract named Demo that:

  • Stores an integer value (number) initialized to 5.

  • Provides a getter function to retrieve the current value of number.

  • Offers an increment function to increase number by 1.

I hope this explanation is clear and helpful! Feel free to ask if you have any further questions.

Last updated