Lesson 3: Outline

Lesson 3 introduction and outline.

Lesson 3: Functions and Modifiers in Solidity

Objective: To understand how to write and use functions in Solidity, and to learn about function modifiers for enforcing certain conditions and managing access control in smart contracts.

Part 1: Functions in Solidity

  • Function Declaration and Types:

    • Understand the syntax for declaring functions.

    • Different types of functions: public, private, internal, and external.

  • Return Values and Visibility:

    • How to define return values for functions.

    • Understand the implications of function visibility.

  • Function Modifiers:

    • Usage of view, pure, and state-changing functions.

  • Function Parameters:

    • Passing parameters to functions.

    • Using memory and storage keywords for complex data types.

  • Example: Creating a Function

    pragma solidity ^0.8.0;
    
    contract MyContract {
        uint public count = 0;
    
        function increment() public {
            count += 1;
        }
    
        function getCount() public view returns (uint) {
            return count;
        }
    }

Part 2: Modifiers in Solidity

  • Understanding Modifiers:

    • Purpose of modifiers in Solidity.

    • Writing custom modifiers to enforce conditions.

  • Common Use Cases:

    • Restricting access to certain functions.

    • Validating inputs or conditions before executing function logic.

  • Example: Using a Modifier

    pragma solidity ^0.8.0;
    
    contract MyContract {
        address public owner;
    
        constructor() {
            owner = msg.sender;
        }
    
        modifier onlyOwner() {
            require(msg.sender == owner, "Not the owner");
            _;
        }
    
        function changeOwner(address newOwner) public onlyOwner {
            owner = newOwner;
        }
    }

Last updated