Skip to content
Solidity

合约基础

定义带状态和函数的基本智能合约。

#contract#state#modifier

Code

solidity
// 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;
    }
}