[TIL] Solidity 02. Syntax

June 21, 2022

01. Syntax of Solidity

interface HelloWorldInterface {
    // private function is not visible so that cannot be used in the interface
    function helloWorld() external view returns (string memory);
    function setText(string memory newText) external;
}

// overriding the interface
contract HelloWorld is HelloWorldInterface {
    string private text;

    constructor() {
        text = "Hello World";
    }

    function helloWorld() public view override returns (string memory)  {
        return text;
    }

    // can use calldata instead of memory
    // cuz newText doesn't need to save into memory for setter
    function setText(string calldata newText) public override {
        text = newText;
    }
}
  • Replacing memory with calldata when stack is enough
    data location : kinda low level thing... related w/ the cost
      - memory
      - storage
      - calldate: non-modifier, non-persistant 
  • Relation between identifier and parameters and MethodID
  • Fallback and receive functions
    contract HelloWorld is HelloWorldInterface {
      ...
      // it hits the fallback function because the attached function does not exist
      // when an error is occurred, just fallback
      fallback() external {
          text = "error";
      }
      ...
    }
  • Definitions
    • Visibility
      access point
       - public: inside + outside
       - private: inside
       - internal: inside
       - external: outside
    • State mutability
      pure
      view
      payable
    • Modifiers
    • Virtual
    • Override

Error

Panic via assert and Error via require Properly functioning code should never create a Panic, not even on invalid external input. If this happens, then there is a bug in your contract which you should fix.

https://docs.soliditylang.org/en/latest/control-structures.html?highlight=require#error-handling-assert-require-revert-and-exceptions

contract HelloWorld is HelloWorldInterface {
    string private text;
    address public owner;

    constructor() {
        text = "Hello World";
        owner = msg.sender;
    }

    function helloWorld() public view override returns (string memory) {
        return text;
    }

    // function setText(string calldata newText) public override {
    //     require(msg.sender == owner, "Error");
    //     text = newText;
    // }

    function setText(string calldata newText) public override onlyOwner {
        text = newText;
    }

    function transferOwnership(address newOwner) public onlyOwner {
        owner = newOwner;
    }

    modifier onlyOwner()
    {
        require (msg.sender == owner, "Caller is not the owner");
        _; // next function
    }
}


Profile picture

Written by Yerin Hong who lives in London and works in the UK.