Skip to content
Solidity

Contract Basics

Define a basic smart contract with state and functions.

By EZ4Code Team
contractstatemodifier

Code

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

contract SimpleStorage {
    // State variable (stored on chain)
    uint256 public storedData;
    address public owner;

    // Constructor runs once on deploy
    constructor() {
        owner = msg.sender;
        storedData = 0;
    }

    // Modifier: reusable check
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;  // placeholder for function body
    }

    // External function (callable from other contracts/EOAs)
    function set(uint256 value) external onlyOwner {
        storedData = value;
    }

    // View function (read-only, free)
    function get() external view returns (uint256) {
        return storedData;
    }

    // Pure function (no state access)
    function compute(uint a, uint b) external pure returns (uint) {
        return a * b + 42;
    }
}

Explanation

Solidity contracts are like classes — state variables persist on-chain. pragma sets the compiler version. public auto-generates a getter. Constructor runs once at deployment. Modifiers (modifier name { require(...); _; }) wrap functions — _; is where the body executes. view (reads state) and pure (no state access) are free (no gas) when called externally.

More Solidity Snippets