Solidity合约结构
123458262
发表于 2022-12-27 10:28:22
154
0
0
0 m. z' Z/ b6 v' t8 E4 _; T
在 Solidity 中,合约类似于面向对象编程语言中的类。2 E4 T* u8 U9 R! p
每个合约中可以包含 :ref:structure-state-variables、 :ref:structure-functions、
:ref:structure-function-modifiers、:ref:structure-events、 :ref:structure-struct-types、* a$ x: U8 Y$ I2 E
和 :ref:structure-enum-types 的声明,且合约可以从其他合约继承。' M; @- _6 d3 G/ g
状态变量
状态变量是永久地存储在合约存储中的值。; U% v _* ~% q% {6 B: D& [
pragma solidity ^0.4.0;2 C& S: |: ]0 M7 L2 L
contract SimpleStorage {& \: k) l$ R; M' u! \0 s3 g
uint storedData; // 状态变量
// ...
}
有效的状态变量类型参阅 :ref:types 章节,+ l8 G* O3 x( I; h% \. C. J
对状态变量可见性有可能的选择参阅 :ref:visibility-and-getters 。: e0 @; \4 w$ H& E8 v
函数
函数是合约中代码的可执行单元。
pragma solidity ^0.4.0;
contract SimpleAuction {
function bid() public payable { // 函数( M% K" ^; u' ]# }
// ...
}* t: v4 `! ]! |7 E; s5 |
}. R4 \+ u% L" y5 W% G. x
:ref:function-calls 可发生在合约内部或外部,且函数对其他合约有不同程度的可见性( :ref:visibility-and-getters)。
函数修饰器/ J( p% i+ Q( u
函数修饰器可以用来以声明的方式改良函数语义(参阅合约章节中 :ref:modifiers)。
pragma solidity ^0.4.22;
contract Purchase {
address public seller;6 V& z `2 b7 M( F+ R! q
modifier onlySeller() { // 修饰器- U4 i5 g; v( ?) t( L
require(+ }/ S* e8 d% }6 \ g9 ~( m
msg.sender == seller,
"Only seller can call this."
);# w: C% A1 V7 k! f5 g" ?
_;
}
1 J/ G, g* o$ t6 N
function abort() public onlySeller { // Modifier usage
// ...
}. j2 c2 {0 @6 }2 _; R
}
事件
事件是能方便地调用以太坊虚拟机日志功能的接口。; Z0 R/ A8 ?' s0 ]0 Q$ S
pragma solidity ^0.4.21;
contract SimpleAuction {7 G9 v1 z9 w9 r) P/ q
event HighestBidIncreased(address bidder, uint amount); // 事件1 i$ o; Q% {" w1 k
function bid() public payable {* L e- h/ X4 s; _/ D
// ...
emit HighestBidIncreased(msg.sender, msg.value); // 触发事件( A1 N) [1 E, f4 t- V: q. x- g
}5 C: Q& W, J% X0 D( T6 O) ]
}
有关如何声明事件和如何在 dapp 中使用事件的信息,参阅合约章节中的 :ref:events。3 P) T1 X a( _( q
结构类型
结构是可以将几个变量分组的自定义类型(参阅类型章节中的 :ref:structs)。4 O# }8 w9 J- M5 h/ ?# W
pragma solidity ^0.4.0;
contract Ballot {
struct Voter { // 结构
uint weight;
bool voted;* P) Q8 X2 c* N
address delegate;
uint vote;
}0 J# d. I5 ^! E) E& F* m8 x
}
枚举类型) e1 Y, S! i. {! N; a, c
枚举可用来创建由一定数量的“常量值”构成的自定义类型(参阅类型章节中的 :ref:enums)。
pragma solidity ^0.4.0;
contract Purchase {' M2 A D% b' B' X
enum State { Created, Locked, Inactive } // 枚举& g, o E/ b$ z, `4 }
}
成为第一个吐槽的人