智能合約源文件的基本要素概覽(Structure of a Contract)
- 合約類似面向對象語言中的類。
- 支持繼承
每個合約中可包含狀態變量(State Variables)
,函數(Functions)
,函數修飾符(Function Modifiers)
,事件(Events)
,結構類型(Structs Types)
和枚舉類型(Enum Types)
。
狀態變量(State Variables)
變量值會永久存儲在合約的存儲空間
pragma solidity ^0.4.0;
// simple store example
contract simpleStorage{
uint valueStore; //state variable
}
詳情見類型(Types)
章節,關于所有支持的類型和變量相關的可見性(Visibility and Accessors)。
函數(Functions)
智能合約中的一個可執行單元。
示例
pragma solidity ^0.4.0;
contract simpleMath{
//Simple add function,try a divide action?
function add(uint x, uint y) returns (uint z){
z = x + y;
}
}
上述示例展示了一個簡單的加法函數。
函數調用可以設置為內部(Internal)的和外部(External)的。同時對于其它合同的不同級別的可見性和訪問控制(Visibility and Accessors)。具體的情況詳見后面類型中關于函數的章節。
函數修飾符(Function Modifiers)
函數修飾符用于增強語義。詳情見函數修飾符相關章節。
事件(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);
}
}
關于事件如何聲明和使用,詳見后面事件相關章節。
結構體類型(Structs Types)
自定義的將幾個變量組合在一起形成的類型。詳見關于結構體相關章節。
示例
pragma solidity ^0.4.0;
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;
}
}
枚舉類型
特殊的自定義類型,類型的所有值可枚舉的情況。詳情見后續相關章節。
示例
pragma solidity ^0.4.0;
contract Home {
enum Switch{On,Off}
}