智能合约源文件基本要素

智能合约源文件基本要素

一个合约(contract)类似于我们面向对象里面所说的类。一个合约中包含状态变量(State Variables),函数(Functions),函数修饰符(Function Modifiers),事件(Events),结构类型(Structs Types)和枚举类型(Enum Types)

1. 状态变量(State Variables)

变量值会永久存储在合约的存储空间

pragma solidity ^0.5.1;
contract hello{
    uint value; //state variable
}

2.函数(Functions)

智能合约中的一个可执行单元。

pragma solidity ^0.5.1;
contract simpleMath{
    function add(uint x, uint y) public returns (uint z){
        z = x + y;
    }
}

3.函数修饰符(Function Modifiers)

函数修饰符用于增强语义。

4.事件(Events)

事件是以太坊虚拟机(EVM)日志基础设施提供的一个便利接口。用于获取当前发生的事件。

pragma solidity ^0.4.0;
contract SimpleAuction {
    event aNewHigherBid(address bidder, uint amount);
    function  bid(uint bidValue) external {
        aNewHigherBid(msg.sender, msg.value);
    }
}

5.结构体类型(Structs Types)

自定义的将几个变量组合在一起形成的类型。

pragma solidity ^0.5.1;
contract Company {
    //user defined `Employee` struct type
    //group with serveral variables
    struct employee{
        string name;
        uint age;
        uint salary;
    }
    //User defined `manager` struct type
    //group with serveral variables
    struct manager{
        employee employ;
        string title;
    }
}

6.枚举类型

特殊的自定义类型,类型的所有值可枚举的情况。

pragma solidity ^0.5.1;
contract Home {
    enum Switch{On,Off}
}
发布了16 篇原创文章 · 获赞 4 · 访问量 1775

猜你喜欢

转载自blog.csdn.net/qq_40509206/article/details/104196610