decrypt101
SocialOpen ProjectsSupport me My Resumes
  • Preface
    • Motivation
    • Roadmap’s
  • Introduction to Blockchain
    • A Brief History
    • Growth of Blockchain
    • Structure of Blockchain
    • Types of Blockchain
    • Key Technologies of Blockchain
    • Features of Blockchain
    • How Blockchain Works ?
    • Implementation of Blockchain
    • Summary
  • Components of Blockchain Architecture
    • Distributed Ledger
    • Blocks
    • Transaction
    • Chain
    • Peer-to-Peer Network
    • Blockchain Layers
    • Off-Chain & On-Chain
    • Wallet
    • Mining
    • Tokens
    • Assets
    • State Channels
    • Sidechains
    • Oracles on Blockchain
    • Atomic Swaps
    • Decentralized Identity (DID)
    • Blockchain Data Storage
    • Interoperability
    • Data structures for Scaling Blockchain
    • Maximal Extractable Value (MEV)
  • Consensus Mechanisms
    • Proof of Work (PoW)
      • Implemation Using Rust
    • Proof of Stake (PoS)
    • Proof of Burn (PoB)
    • Proof of Capacity (PoC)
    • Proof of Activity (PoAc)
    • Proof of Weight (PoWe)
    • Proof of Luck (PoL)
    • Proof of Ownership (PoO)
    • Proof of Existence (PoE)
    • Proof of Believability (PoBe)
    • Proof of History (PoH)
    • Proof of Authority (PoA)
    • Proof of Elapsed Time (PoET)
  • Cryptographics
    • Encryption & Decryption
      • Symmetric Encryption
      • Asymmetric Encryption
      • Key Management and Exchange
      • Implementation
    • Cryptographic Hashing
      • Secure Hash Algorithms (SHA)
      • Message Digest Algorithms
      • Ethash
      • Blake2
      • SCrypt
      • RIPEMD-160
    • Digital Signature
      • Digital Signature Algorithms
      • Digital Signature in Blockchain
    • Zero-Knowledge Proofs (ZKPs)
      • Types of Zero-Knowledge Proof and Protocols
      • A Case Study of Polygon Platform
    • Multi-Party Computation (MPC)
    • Cryptanalysis
    • Practical Implementation
  • Decentralized Application (DApp)
    • Design and UX in Web3
  • Smart Contract
    • Development Tools
    • Solidity
    • Testing Smart Contract
    • Developing Smart Contract
    • Interacting & Deploying with Smart Contract
    • Verifying Smart Contracts
    • Upgrading Smart Contracts
    • Securing Smart Contract
    • Smart Contract Composability
    • Testnet and Mainnet
    • Blockchain Platform Using Smart Contract
    • Application of Smart Contract
    • Practical Implementation
  • Blockchain Platforms
    • Ethereum
      • Ethereum Virtual Machine (EVM)
      • ETHER and GAS
      • Ethereum transaction
      • Ethereum Accounts
      • Ethereum Stacking
      • Ethereum Network
      • Ethereum Scaling Solutions
      • Ethereum Use-Cases
      • Getting Started with Ethereum
      • Ethereum Ecosystem and Support
    • Solana
      • Solana Architecture
        • Solana Account Model
        • Solana Wallet
        • Transactions and Instructions
        • Solana Programs
        • Program Derived Address (PDA)
        • Cross Program Invocation (CPI)
        • Tokens on Solana
        • Clusters and Public RPC Endpoints
        • Transaction Confirmation & Expiration
        • Retrying Transactions
        • Versioned Transactions
        • Address Lookup Tables
        • State Compression
        • Actions and Blinks
      • Solana Developments
      • Solana Client
      • Advanced Solana
      • Solana Scaling and Performance Architecture
      • Solana Solutions and cases
      • Practical Implemenation
    • Binance Smart Chain (BSC)
      • Create a BEP20 Token
    • Hyperledger Fabric
    • Cosmos
    • Polkadot
    • Quorum
    • Polygon
    • Algorand
    • Corda
    • Avalanche
    • TRON
    • Summary
  • Decentralized Finance (DeFi)
    • DeFi Components
    • DeFi Protocols
    • DeFi Platforms
    • DeFi Risk Classification
      • Infrastructure-layer Attacks
      • Smart Contract Layer-attacks
      • Application Layer-attacks
      • DeFi Risks
    • DeFi and Blockchain
    • DeFi Impact
  • Decentralized Ecosystem and Digital Innovation
    • Layer 2 Scaling Fundamental
    • Tokenomics
    • Cryptocurrency
    • Quantative Trading
    • NFTs
    • GameFi
    • Metaverse
  • Blockchain as a Service (BaaS)
    • Building Fullstack Blockchain Platform
    • Decentralized Digital Identity
    • Build a Cryptocurrencies Exchange
    • Play-to-Earn Gaming
    • Solana Token Airdrop Manager
    • Smart Contract Development on Solana with Rust
    • Quantitative Trading Platform
    • Insurances protocols
    • Flash Loans
    • Asset Management
    • Tokenized Derivatives
    • Automated Market Makers (AMMs)
    • Staking
    • Lending and Borrowing Platforms
    • Yield Farming
    • Stablecoin System
    • Security Token Offerings (STOs)
    • Initial Coin Offerings (ICOs)
    • On-Chain Voting Systems
    • Decentralized Autonomous Organizations (DAOs)
    • NFT Marketplaces
    • Provenance Verification
    • Supply Chain Tracking
    • Commodities Tokenization
    • Real Estate Tokenization
    • Digital Certificates
    • KYC (Know Your Customer)
  • Blockchain Development Across Languages
    • Blockchain using Go(Golang)
    • Blockchain using Rust
    • Blockchain using Python
    • Blockchain using Cairo
  • Distributed Systems & Infrastructure Technology
    • Classification of Distributed Systems
    • Networked systems versus Distributed systems
    • Parallel systems vs Distributed systems
    • Distributed versus Decentralized systems
    • Processes of Distributed Systems
    • Architecture of Distributed systems
    • Infrastructure Technologies
  • Distributed System Patterns
    • Distributed Agreements Algorithms
      • HoneyBadgerBFT
    • Data Replications
    • Data Partition
    • Consistency
    • Distributed Time
    • Cluster Management
    • Communication between Nodes
    • Fault Tolerance and Resilience
      • How to design better fault tolerance systems
      • Resilience Patterns
    • Coordination systems
      • Clock synchronization
    • Security
      • Trust in distributed systems
      • Design of Principal Security
      • Security threats, policies, and mechanisms
      • Authentication and Authorizations
      • Cryptography
      • Monitoring in Security
  • Distributed System Design
    • Page 1
    • Distributed Shared Memory
    • Distributed Data Management
    • Distributed Knowledge Management
    • Distributed Ledger
  • FAQs
  • Support and Community
Powered by GitBook
On this page
  • Solidity Compilation Process
  • What is Solidity?
  • 2. Data Types and Variables
  • 3. State and Local Variables
  • 4. Constants and Immutable Variables
  • 5. Functions
  • 6. Events
  • 7. Control Structures
  • 8. Constructor and Inheritance
  • 9. Payable Functions
  • 10. Error Handling
  • Example Case
  1. Smart Contract

Solidity

Fundamentals of Solidity

PreviousDevelopment ToolsNextTesting Smart Contract

Last updated 8 months ago

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:

Solidity Compilation Process

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.

https://solidity-by-example.org/
How Compilation Process of Solidity work