solidity cheatsheet

141 阅读1分钟
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;

contract SimpleStorage {
    bool a = true;

    //storage variable
    uint256 b = 5;

    string c = "Five";
    int256 d = -5;
    address e = 0x8aB283a872500C3c876771F811Aac38940b5b476;
    bytes f = "cat";

    // This gets initialized to zero
    uint256 public favoriteNumber;

    struct People {
        uint256 favoriteNumber;
        string name;
    }

    People public person = People({favoriteNumber: 1, name: "edwin"});

    People[] public people;

    mapping(string => uint256) public nameToFavoriteNumber;

    // stack, memory, storage, calldata, code, logs
    // memory: temporarily variable during the function call
    // calldata: temporarily variable that cannot be modified
    // storage: variables exist, even outside of the function executing
    function addPerson(string memory _name, uint256 _favoriteNumber) public {
        people.push(People(_favoriteNumber, _name));
        nameToFavoriteNumber[_name] = _favoriteNumber;
    }

    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
        retrieve(); // pay the gas
    }

    // view: read state (does not make a transaction)
    function retrieve() public view returns (uint256) {
        return favoriteNumber;
    }

    // pure: disallowd read and modify (does not make a transaction)
    function add() public pure returns (uint256) {
        return 1 + 1; // it does not update any state (variable)
    }
}