DApp

2.4.2 Structure of a Contract

2018-12-05  本文已影响14人  furnace

Structure of a Contract

Solidity中的Contracts与面向对象语言中的类相似。每个合约都可以包含状态变量 (State Variables),函数 (Functions),函数修饰符 (Function Modifiers),事件 (https://solidity.readthedocs.io/en/latest/structure-of-a-contract.html#structure-events),结构类型 (Struct Types) 和 枚举类型 (https://solidity.readthedocs.io/en/latest/structure-of-a-contract.html#structure-enum-types) 的声明。此外,合约可以继承其他合约。

还有一些特殊的合约称为库 (libraries) 和接口 (interfaces)。

有关合约的部分包含的详细信息比本部分更详细,本节用于快速概述。

State Variables

状态变量是其值永久存储在合约存储中的变量。

pragma solidity >=0.4.0 <0.6.0;

contract SimpleStorage {
    uint storedData; // State variable
    // ...
}

有关可见性的可能选择,请参阅类型 (Types) 部分以获取有效的状态变量类型和可见性和获取者 (Visibility and Getters)。

Functions

函数是合约中可执行的代码单元。

pragma solidity >=0.4.0 <0.6.0;

contract SimpleAuction {
    function bid() public payable { // Function
        // ...
    }
}

函数调用 (Function Calls) 可以在内部或外部发生,并且对其他合约具有不同的可见性 (visibility) 级别。函数 (Functions) 接受参数并返回变量 (parameters and return variables) 以在它们之间传递参数和值。

Function Modifiers

函数修饰符可用于以声明方式修改函数的语义(请参阅合约部分中的函数修饰符 (Function Modifiers))。

pragma solidity >=0.4.22 <0.6.0;

contract Purchase {
    address public seller;

    modifier onlySeller() { // Modifier
        require(
            msg.sender == seller,
            "Only seller can call this."
        );
        _;
    }

    function abort() public view onlySeller { // Modifier usage
        // ...
    }
}

Events

事件是与EVM日志记录工具的便捷接口。

pragma solidity >=0.4.21 <0.6.0;

contract SimpleAuction {
    event HighestBidIncreased(address bidder, uint amount); // Event

    function bid() public payable {
        // ...
        emit HighestBidIncreased(msg.sender, msg.value); // Triggering event
    }
}

有关如何声明事件以及可以在dapp中使用事件的信息,请参阅合约部分中的事件 (Events)。

Struct Types

结构是自定义类型,可以对多个变量进行分组(请参阅类型部分中的结构 (Structs))。

pragma solidity >=0.4.0 <0.6.0;

contract Ballot {
    struct Voter { // Struct
        uint weight;
        bool voted;
        address delegate;
        uint vote;
    }
}

Enum Types

枚举可用于创建具有有限“常量值”集的自定义类型(请参阅类型部分中的枚举 (Enums))。

pragma solidity >=0.4.0 <0.6.0;

contract Purchase {
    enum State { Created, Locked, Inactive } // Enum
}

项目源代码

项目源代码会逐步上传到 Github,地址为 https://github.com/windstamp/dapp

Contributor

  1. Windstamp, https://github.com/windstamp

Reference

  1. https://solidity.readthedocs.io/en/v0.5.0/
  2. https://solidity-cn.readthedocs.io/zh/develop/
上一篇 下一篇

猜你喜欢

热点阅读